commons-httpclient-3.1/ 40755 0 0 0 10661532632 12242 5ustar 0 0 commons-httpclient-3.1/docs/ 40755 0 0 0 10661532631 13171 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/ 40755 0 0 0 10661532631 14613 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/ 40755 0 0 0 10661532627 15407 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/ 40755 0 0 0 10661532627 16630 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/ 40755 0 0 0 10661532627 20303 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ 40755 0 0 0 10661532627 22461 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/ 40755 0 0 0 10661532627 23422 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/ 40755 0 0 0 10661532627 25321 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ 40755 0 0 0 10661532627 24360 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/ 40755 0 0 0 10661532627 23732 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/ 40755 0 0 0 10661532627 25631 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/ 40755 0 0 0 10661532627 24124 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/ 40755 0 0 0 10661532627 26023 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/ 40755 0 0 0 10661532627 26145 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/ 40755 0 0 0 10661532627 30044 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/ 40755 0 0 0 10661532627 23744 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/ 40755 0 0 0 10661532627 25643 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/ 40755 0 0 0 10661532627 24322 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/ 40755 0 0 0 10661532627 26221 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/ 40755 0 0 0 10661532627 23436 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/ 40755 0 0 0 10661532627 25335 5ustar 0 0 commons-httpclient-3.1/docs/apidocs/resources/ 40755 0 0 0 10661532627 16632 5ustar 0 0 commons-httpclient-3.1/docs/images/ 40755 0 0 0 10661532627 14443 5ustar 0 0 commons-httpclient-3.1/docs/images/logos/ 40755 0 0 0 10661532627 15566 5ustar 0 0 commons-httpclient-3.1/docs/junit-report/ 40755 0 0 0 10661532627 15640 5ustar 0 0 commons-httpclient-3.1/docs/junit-report/org/ 40755 0 0 0 10661532627 16427 5ustar 0 0 commons-httpclient-3.1/docs/junit-report/org/apache/ 40755 0 0 0 10661532627 17650 5ustar 0 0 commons-httpclient-3.1/docs/junit-report/org/apache/commons/ 40755 0 0 0 10661532627 21323 5ustar 0 0 commons-httpclient-3.1/docs/junit-report/org/apache/commons/httpclient/ 40755 0 0 0 10661532627 23501 5ustar 0 0 commons-httpclient-3.1/docs/methods/ 40755 0 0 0 10661532631 14634 5ustar 0 0 commons-httpclient-3.1/docs/style/ 40755 0 0 0 10661532627 14336 5ustar 0 0 commons-httpclient-3.1/docs/xref/ 40755 0 0 0 10661532632 14136 5ustar 0 0 commons-httpclient-3.1/docs/xref-test/ 40755 0 0 0 10661532631 15112 5ustar 0 0 commons-httpclient-3.1/docs/xref-test/org/ 40755 0 0 0 10661532627 15706 5ustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/ 40755 0 0 0 10661532627 17127 5ustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/ 40755 0 0 0 10661532627 20602 5ustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/ 40755 0 0 0 10661532631 22753 5ustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/auth/ 40755 0 0 0 10661532631 23714 5ustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/ 40755 0 0 0 10661532631 24224 5ustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/params/ 40755 0 0 0 10661532631 24236 5ustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/ 40755 0 0 0 10661532631 24261 5ustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/ssl/ 40755 0 0 0 10661532631 23554 5ustar 0 0 commons-httpclient-3.1/docs/xref/org/ 40755 0 0 0 10661532627 14731 5ustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/ 40755 0 0 0 10661532627 16152 5ustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/ 40755 0 0 0 10661532627 17625 5ustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/ 40755 0 0 0 10661532632 21777 5ustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/ 40755 0 0 0 10661532632 22740 5ustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/ 40755 0 0 0 10661532632 23250 5ustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/ 40755 0 0 0 10661532632 23442 5ustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/ 40755 0 0 0 10661532632 25463 5ustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/ 40755 0 0 0 10661532632 23262 5ustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/ 40755 0 0 0 10661532632 23640 5ustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/ 40755 0 0 0 10661532632 22754 5ustar 0 0 commons-httpclient-3.1/src/ 40755 0 0 0 10661532626 13034 5ustar 0 0 commons-httpclient-3.1/src/conf/ 40755 0 0 0 10661532627 13762 5ustar 0 0 commons-httpclient-3.1/src/contrib/ 40755 0 0 0 10661532626 14474 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/ 40755 0 0 0 10661532626 15263 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/ 40755 0 0 0 10661532626 16504 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/ 40755 0 0 0 10661532626 20157 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/ 40755 0 0 0 10661532626 22335 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ 40755 0 0 0 10661532626 23775 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/auth/ 40755 0 0 0 10661532626 24736 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/benchmark/ 40755 0 0 0 10661532626 25727 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/methods/ 40755 0 0 0 10661532626 25440 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/methods/multipart/ 40755 0 0 0 10661532626 27461 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/proxy/ 40755 0 0 0 10661532632 25153 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/ 40755 0 0 0 10661532627 24577 5ustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/utils/ 40755 0 0 0 10661532626 25135 5ustar 0 0 commons-httpclient-3.1/src/examples/ 40755 0 0 0 10661532627 14653 5ustar 0 0 commons-httpclient-3.1/src/java/ 40755 0 0 0 10661532626 13755 5ustar 0 0 commons-httpclient-3.1/src/java/org/ 40755 0 0 0 10661532626 14544 5ustar 0 0 commons-httpclient-3.1/src/java/org/apache/ 40755 0 0 0 10661532626 15765 5ustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/ 40755 0 0 0 10661532626 17440 5ustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/ 40755 0 0 0 10661532627 21617 5ustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/ 40755 0 0 0 10661532632 22554 5ustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/ 40755 0 0 0 10661532627 23070 5ustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/ 40755 0 0 0 10661532627 23262 5ustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/ 40755 0 0 0 10661532626 25302 5ustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/ 40755 0 0 0 10661532627 23102 5ustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/ 40755 0 0 0 10661532627 23460 5ustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/ 40755 0 0 0 10661532627 22574 5ustar 0 0 commons-httpclient-3.1/src/resources/ 40755 0 0 0 10661532626 15046 5ustar 0 0 commons-httpclient-3.1/src/resources/META-INF/ 40755 0 0 0 10661532626 16206 5ustar 0 0 commons-httpclient-3.1/src/test/ 40755 0 0 0 10661532626 14013 5ustar 0 0 commons-httpclient-3.1/src/test/org/ 40755 0 0 0 10661532626 14602 5ustar 0 0 commons-httpclient-3.1/src/test/org/apache/ 40755 0 0 0 10661532626 16023 5ustar 0 0 commons-httpclient-3.1/src/test/org/apache/commons/ 40755 0 0 0 10661532626 17476 5ustar 0 0 commons-httpclient-3.1/src/test/org/apache/commons/httpclient/ 40755 0 0 0 10661532630 21647 5ustar 0 0 commons-httpclient-3.1/src/test/org/apache/commons/httpclient/auth/ 40755 0 0 0 10661532626 22615 5ustar 0 0 commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/ 40755 0 0 0 10661532630 23120 5ustar 0 0 commons-httpclient-3.1/src/test/org/apache/commons/httpclient/params/ 40755 0 0 0 10661532630 23132 5ustar 0 0 commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/ 40755 0 0 0 10661532630 23155 5ustar 0 0 commons-httpclient-3.1/src/test/org/apache/commons/httpclient/ssl/ 40755 0 0 0 10661532630 22450 5ustar 0 0 commons-httpclient-3.1/LICENSE100644 0 0 23675 10661532632 13401 0ustar 0 0 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 commons-httpclient-3.1/LICENSE.txt100644 0 0 24155 10661532632 14211 0ustar 0 0 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 commons-httpclient-3.1/NOTICE100644 0 0 263 10661532632 13224 0ustar 0 0 Apache Jakarta HttpClient Copyright 1999-2007 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). commons-httpclient-3.1/NOTICE.txt100644 0 0 270 10661532632 14040 0ustar 0 0 Apache Jakarta HttpClient Copyright 1999-2007 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). commons-httpclient-3.1/README100644 0 0 471 10661532632 13201 0ustar 0 0 Jakarta HttpClient =========================== Welcome to the HttpClient component of the Jakarta HttpComponents project. Visit us online at http://jakarta.apache.org/httpcomponents/index.html for more information. Visit http://jakarta.apache.org/httpcomponents/status.html for the status of the project. commons-httpclient-3.1/README.txt100644 0 0 504 10661532632 14014 0ustar 0 0 Jakarta HttpClient =========================== Welcome to the HttpClient component of the Jakarta HttpComponents project. Visit us online at http://jakarta.apache.org/httpcomponents/index.html for more information. Visit http://jakarta.apache.org/httpcomponents/status.html for the status of the project. commons-httpclient-3.1/RELEASE_NOTES100644 0 0 347255 10661532632 14372 0ustar 0 0 Release 3.1 Final ------------------- New features: ------------------- (1) HTTP state management * RFC 2965 cookie specification support ------------------- Changes since 3.1 RC 1 * [HTTPCLIENT-679] - Fixed RFC3986 compliance problem in URI absolutization code. Contributed by Jeff Dalton * [HTTPCLIENT-676] - Fixed memory leak in MultiThreadedHttpConnectionManager. Contributed by Roland Weber * [HTTPCLIENT-675] - Fixed potential race condition in MultiThreadedHttpConnectionManager. Contributed by Roland Weber * [HTTPCLIENT-665] - Internal collections of HttpState visible to subclasses. Contributed by Roland Weber * [HTTPCLIENT-651] - Improved API Doc regarding response buffering. Contributed by Ortwin Glueck * [HTTPCLIENT-645] - Cookie#compare() changed to do a simple case-sensitive string comparison when comparing path attributes instead of using a static instance of RuleBasedCollator Contributed by Oleg Kalnichevski * [HTTPCLIENT-650] - Wire log for headers written one by one while parsing instead of all at once afterwards, which fails on parse errors. Contributed by Roland Weber API changes since release 3.0.1 ------------------- Class added: public org.apache.commons.httpclient.HttpContentTooLargeException extends org.apache.commons.httpclient.HttpException Class added: public org.apache.commons.httpclient.InvalidRedirectLocationException extends org.apache.commons.httpclient.RedirectException Class added: public org.apache.commons.httpclient.cookie.Cookie2 extends org.apache.commons.httpclient.Cookie Class added: public abstract org.apache.commons.httpclient.cookie.CookieAttributeHandler extends java.lang.Object Class added: public final org.apache.commons.httpclient.cookie.CookieOrigin extends java.lang.Object Class added: public org.apache.commons.httpclient.cookie.CookiePathComparator extends java.lang.Object implements java.util.Comparator Class added: public abstract org.apache.commons.httpclient.cookie.CookieVersionSupport extends java.lang.Object Class added: public org.apache.commons.httpclient.cookie.RFC2965Spec extends org.apache.commons.httpclient.cookie.CookieSpecBase implements org.apache.commons.httpclient.cookie.CookieVersionSupport Class added: public org.apache.commons.httpclient.methods.FileRequestEntity extends java.lang.Object implements org.apache.commons.httpclient.methods.RequestEntity Class changed: org.apache.commons.httpclient.ConnectMethod Methods added: public ConnectMethod(org.apache.commons.httpclient.HostConfiguration); public java.lang.String getPath(); public org.apache.commons.httpclient.URI getURI() throws org.apache.commons.httpclient.URIException; Method changed: old: public ConnectMethod(); new: deprecated: public ConnectMethod(); Class changed: org.apache.commons.httpclient.ContentLengthInputStream Methods added: public int available() throws java.io.IOException; Class changed: org.apache.commons.httpclient.HttpHost Method changed: old: public java.lang.Object clone(); new: public java.lang.Object clone() throws java.lang.CloneNotSupportedException; Class changed: org.apache.commons.httpclient.HttpMethodBase Methods added: public byte[] getResponseBody(int) throws java.io.IOException; public java.lang.String getResponseBodyAsString(int) throws java.io.IOException; protected void processCookieHeaders(org.apache.commons.httpclient.cookie.CookieSpec, org.apache.commons.httpclient.Header[], org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection); Fields added: protected org.apache.commons.httpclient.HttpVersion effectiveVersion; protected org.apache.commons.httpclient.StatusLine statusLine; Class changed: org.apache.commons.httpclient.HttpState Fields added: protected java.util.ArrayList cookies; protected java.util.HashMap credMap; protected java.util.HashMap proxyCred; Class changed: org.apache.commons.httpclient.ProxyHost Method changed: old: public java.lang.Object clone(); new: public java.lang.Object clone() throws java.lang.CloneNotSupportedException; Class changed: org.apache.commons.httpclient.SimpleHttpConnectionManager Methods added: public SimpleHttpConnectionManager(boolean); public void shutdown(); Class changed: org.apache.commons.httpclient.URI Methods removed: protected void readObject(java.io.ObjectInputStream) throws java.lang.ClassNotFoundException, java.io.IOException; protected void writeObject(java.io.ObjectOutputStream) throws java.io.IOException; Method changed: old: public synchronized java.lang.Object clone(); new: public synchronized java.lang.Object clone() throws java.lang.CloneNotSupportedException; Field changed: old: protected static char[] rootPath; new: protected final static char[] rootPath; Class changed: org.apache.commons.httpclient.auth.AuthSchemeBase Methods removed: deprecated: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; deprecated: public abstract java.lang.String getID(); public abstract java.lang.String getParameter(java.lang.String); public abstract java.lang.String getRealm(); public abstract java.lang.String getSchemeName(); public abstract boolean isComplete(); public abstract boolean isConnectionBased(); public abstract void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class changed: org.apache.commons.httpclient.auth.RFC2617Scheme Methods removed: deprecated: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract java.lang.String getSchemeName(); public abstract boolean isComplete(); public abstract boolean isConnectionBased(); Class changed: org.apache.commons.httpclient.cookie.CookiePolicy Methods added: public static java.lang.String[] getRegisteredCookieSpecs(); Fields added: deprecated: public final static int RFC2965 = 3; public final static java.lang.String RFC_2965 = rfc2965; Class changed: org.apache.commons.httpclient.cookie.RFC2109Spec Fields added: public final static java.lang.String SET_COOKIE_KEY = set-cookie; Class changed: org.apache.commons.httpclient.methods.StringRequestEntity Method changed: old: public StringRequestEntity(java.lang.String); new: deprecated: public StringRequestEntity(java.lang.String); Class changed: org.apache.commons.httpclient.params.HttpMethodParams Methods added: public java.lang.String getUriCharset(); public void setUriCharset(java.lang.String); Fields added: public final static java.lang.String HTTP_URI_CHARSET = http.protocol.uri-charset; Class changed: org.apache.commons.httpclient.util.IdleConnectionTimeoutThread Methods added: protected void handleCloseIdleConnections(org.apache.commons.httpclient.HttpConnectionManager); API diff generated by JarDiff http://www.osjava.org/jardiff/ ------------------- Release 3.1 RC 1 ------------------- Changes since Release 3.1 Beta1: * [HTTPCLIENT-641] - Resource Leakage when loading keystore in AuthSSLProtocolSocketFactory. Contributed by Hanson Char * [HTTPCLIENT-634] - Default host config can override scheme of absolute URL. Contributed by John Kristian * [HTTPCLIENT-633] - Changed MultiThreadedHttpConnectionManager's handling of thread interrupts. IllegalThreadStateException is now thrown when waiting threads are interrupted from outside of the connection manager. Contributed by Michael Becke * [HTTPCLIENT-628] - IOException in AutoCloseInputStream.available() Contributed by Roland Weber * [HTTPCLIENT-625] - revised shutdown of MultiThreadedHttpConnectionManager Contributed by Roland Weber * [HTTPCLIENT-622] - Leak in MultiThreadedHttpConnectionManager.ConnectionPool.mapHosts Contributed by Michael Becke and Ortwin Glueck * [HTTPCLIENT-612] - FileRequestEntity now always closes the input file. Contributed by Sebastian Bazley * [HTTPCLIENT-616] - HttpMethodDirector.executeWithRetry method fixed to close the underlying connection if a RuntimeException is thrown Contributed by Jason Bird * [HTTPCLIENT-606] - Added a HTTP method level parameter for URI charset Contributed by Oleg Kalnichevski * [HTTPCLIENT-610] - Added for convenience HttpMethodBase.getResponseBodyAsString(int) Contributed by Ortwin Glueck Release 3.1 Alpha 1 ------------------- Changes since Release 3.0.1: * [HTTPCLIENT-588] - Fixed parsing of relative URIs with internal double-slashes ('//') Contributed by Gordon Mohr * [HTTPCLIENT-587] - Fixed incorrect derelativizing of relative URIs with a scheme Contributed by Gordon Mohr * [HTTPCLIENT-494] - Invalid redirect location now causes a protocol exception Contributed by Oleg Kalnichevski * [HTTPCLIENT-582] - Allow access to registered cookie policies Contributed by Sebastian Bazley * [HTTPCLIENT-189] - Added support for Set-Cookie2 response headers Contributed by Samit Jain * [HTTPCLIENT-66] - Implemented RFC 2965 cookie spec (Cookie2); Added support for port sensitive cookies Contributed by Samit Jain * [HTTPCLIENT-506] - Digest auth scheme now uses correct digest uri in HTTP CONNECT requests Contributed by Oleg Kalnichevski * [HTTPCLIENT-570] - Failed CONNECT no longer leaves connection in an inconsistent state Contributed by Oleg Kalnichevski Release 3.0.1 ------------------- Changes since Release 3.0: * 38636 - Calling HttpState.clearCookies() is now safe from a different thread. Contributed by Peter Dolberg * 38385 - Fixed NPE when creating URI from scheme specific part with null fragment Contributed by Michele Vivoda * 38043 - Digest URI changed to include query parameters Contributed by Oleg Kalnichevski * 38004 - Fixed bug causing cyclic redirects when virtual host is set Contributed by Oleg Kalnichevski * 38139 - Calling deprecated MultiThreadedHttpConnectionManager.setMaxTotalConnections(int) had no effect Contributed by Ortwin Glueck * 37988 - Fixed bug in URI#toString() causing user name / password to stripped from the resultant String Contributed by Oleg Kalnichevski Release 3.0 ------------------- New features: ------------------- (1) Architecture * New preference architecture * Improved exception handling framework * Granular non-standards configuration and tracking * Improved HTTP Version configuration and tracking * Support for streaming entities * Support for tunneled HTTP proxies via the ProxyClient * Ability to abort execution of HTTP methods (2) Connection management * Support for closing idle connections * Support for JDK1.4 connect timeout through reflection * Support for connection manager shutdown (3) Authentication * Improved authentication framework * Plug-in mechanism for authentication modules * Interactive authentication support * Alternate authentication support (4) Cookie management * Cookie specification plug-in mechanism * 'Ignore cookies' cookie policy * Improved Netscape cookie support (5) Redirects * Cross-site redirect support ------------------- API changes since 2.0 Class removed: deprecated: public org.apache.commons.httpclient.Authenticator extends java.lang.Object Class removed: public org.apache.commons.httpclient.HttpConnection.ConnectionTimeoutException extends java.io.IOException Class removed: deprecated: public abstract org.apache.commons.httpclient.HttpUrlMethod extends java.lang.Object implements org.apache.commons.httpclient.HttpMethod Class removed: deprecated: public final org.apache.commons.httpclient.NTLM extends java.lang.Object Class removed: deprecated: public org.apache.commons.httpclient.RequestOutputStream extends java.io.OutputStream Class removed: deprecated: public org.apache.commons.httpclient.ResponseInputStream extends java.io.InputStream Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlDeleteMethod extends org.apache.commons.httpclient.methods.DeleteMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlGetMethod extends org.apache.commons.httpclient.methods.GetMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlHeadMethod extends org.apache.commons.httpclient.methods.HeadMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlOptionsMethod extends org.apache.commons.httpclient.methods.OptionsMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlPostMethod extends org.apache.commons.httpclient.methods.PostMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlPutMethod extends org.apache.commons.httpclient.methods.PutMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public final org.apache.commons.httpclient.util.Base64 extends java.lang.Object Class added: public org.apache.commons.httpclient.CircularRedirectException extends org.apache.commons.httpclient.RedirectException Class added: public org.apache.commons.httpclient.ConnectTimeoutException extends java.io.InterruptedIOException Class added: public org.apache.commons.httpclient.ConnectionPoolTimeoutException extends org.apache.commons.httpclient.ConnectTimeoutException Class added: public org.apache.commons.httpclient.DefaultHttpMethodRetryHandler extends java.lang.Object implements org.apache.commons.httpclient.HttpMethodRetryHandler Class added: public org.apache.commons.httpclient.HttpClientError extends java.lang.Error Class added: public org.apache.commons.httpclient.HttpHost extends java.lang.Object implements java.lang.Cloneable Class added: public abstract org.apache.commons.httpclient.HttpMethodRetryHandler extends java.lang.Object Class added: public org.apache.commons.httpclient.HttpVersion extends java.lang.Object implements java.lang.Comparable Class added: public org.apache.commons.httpclient.NoHttpResponseException extends java.io.IOException Class added: public org.apache.commons.httpclient.ProtocolException extends org.apache.commons.httpclient.HttpException Class added: public org.apache.commons.httpclient.ProxyClient extends java.lang.Object Class added: public org.apache.commons.httpclient.ProxyClient.ConnectResponse extends java.lang.Object Class added: public org.apache.commons.httpclient.ProxyHost extends org.apache.commons.httpclient.HttpHost Class added: public org.apache.commons.httpclient.RedirectException extends org.apache.commons.httpclient.ProtocolException Class added: public org.apache.commons.httpclient.auth.AuthChallengeException extends org.apache.commons.httpclient.auth.AuthenticationException Class added: public final org.apache.commons.httpclient.auth.AuthChallengeProcessor extends java.lang.Object Class added: public abstract org.apache.commons.httpclient.auth.AuthPolicy extends java.lang.Object Class added: public org.apache.commons.httpclient.auth.AuthScope extends java.lang.Object Class added: public org.apache.commons.httpclient.auth.AuthState extends java.lang.Object Class added: public org.apache.commons.httpclient.auth.CredentialsNotAvailableException extends org.apache.commons.httpclient.auth.AuthenticationException Class added: public abstract org.apache.commons.httpclient.auth.CredentialsProvider extends java.lang.Object Class added: public org.apache.commons.httpclient.auth.InvalidCredentialsException extends org.apache.commons.httpclient.auth.AuthenticationException Class added: public org.apache.commons.httpclient.cookie.IgnoreCookiesSpec extends java.lang.Object implements org.apache.commons.httpclient.cookie.CookieSpec Class added: public org.apache.commons.httpclient.methods.ByteArrayRequestEntity extends java.lang.Object implements org.apache.commons.httpclient.methods.RequestEntity Class added: public org.apache.commons.httpclient.methods.InputStreamRequestEntity extends java.lang.Object implements org.apache.commons.httpclient.methods.RequestEntity Class added: public abstract org.apache.commons.httpclient.methods.RequestEntity extends java.lang.Object Class added: public org.apache.commons.httpclient.methods.StringRequestEntity extends java.lang.Object implements org.apache.commons.httpclient.methods.RequestEntity Class added: public org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity extends java.lang.Object implements org.apache.commons.httpclient.methods.RequestEntity Class added: public org.apache.commons.httpclient.params.DefaultHttpParams extends java.lang.Object implements org.apache.commons.httpclient.params.HttpParams, java.io.Serializable, java.lang.Cloneable Class added: public org.apache.commons.httpclient.params.DefaultHttpParamsFactory extends java.lang.Object implements org.apache.commons.httpclient.params.HttpParamsFactory Class added: public org.apache.commons.httpclient.params.HostParams extends org.apache.commons.httpclient.params.DefaultHttpParams Class added: public org.apache.commons.httpclient.params.HttpClientParams extends org.apache.commons.httpclient.params.HttpMethodParams Class added: public org.apache.commons.httpclient.params.HttpConnectionManagerParams extends org.apache.commons.httpclient.params.HttpConnectionParams Class added: public org.apache.commons.httpclient.params.HttpConnectionParams extends org.apache.commons.httpclient.params.DefaultHttpParams Class added: public org.apache.commons.httpclient.params.HttpMethodParams extends org.apache.commons.httpclient.params.DefaultHttpParams Class added: public abstract org.apache.commons.httpclient.params.HttpParams extends java.lang.Object Class added: public abstract org.apache.commons.httpclient.params.HttpParamsFactory extends java.lang.Object Class added: public final org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory extends java.lang.Object Class added: public abstract org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory.SocketTask extends java.lang.Object implements java.lang.Runnable Class added: public final org.apache.commons.httpclient.protocol.ReflectionSocketFactory extends java.lang.Object Class added: public org.apache.commons.httpclient.util.DateUtil extends java.lang.Object Class added: public org.apache.commons.httpclient.util.ExceptionUtil extends java.lang.Object Class added: public org.apache.commons.httpclient.util.IdleConnectionHandler extends java.lang.Object Class added: public org.apache.commons.httpclient.util.IdleConnectionTimeoutThread extends java.lang.Thread Class added: public org.apache.commons.httpclient.util.LangUtils extends java.lang.Object Class added: public org.apache.commons.httpclient.util.ParameterFormatter extends java.lang.Object Class added: public org.apache.commons.httpclient.util.ParameterParser extends java.lang.Object Class changed: org.apache.commons.httpclient.ChunkedInputStream Methods added: public ChunkedInputStream(java.io.InputStream) throws java.io.IOException; Class changed: org.apache.commons.httpclient.ChunkedOutputStream Methods removed: public void print(java.lang.String) throws java.io.IOException; public void println() throws java.io.IOException; public void println(java.lang.String) throws java.io.IOException; Methods added: public ChunkedOutputStream(java.io.OutputStream, int) throws java.io.IOException; public void finish() throws java.io.IOException; protected void flushCache() throws java.io.IOException; protected void flushCacheWithAppend(byte[], int, int) throws java.io.IOException; public void write(byte[]) throws java.io.IOException; Method changed: old: public ChunkedOutputStream(java.io.OutputStream); new: public ChunkedOutputStream(java.io.OutputStream) throws java.io.IOException; Method changed: old: public void write(int) throws java.io.IOException, java.lang.IllegalStateException; new: public void write(int) throws java.io.IOException; Method changed: old: public void writeClosingChunk() throws java.io.IOException; new: protected void writeClosingChunk() throws java.io.IOException; Class changed: org.apache.commons.httpclient.ConnectMethod Methods removed: protected void addAuthorizationRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected void addContentLengthRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; Methods added: public ConnectMethod(); Method changed: old: public ConnectMethod(org.apache.commons.httpclient.HttpMethod); new: deprecated: public ConnectMethod(org.apache.commons.httpclient.HttpMethod); Class changed: org.apache.commons.httpclient.ContentLengthInputStream Methods added: public ContentLengthInputStream(java.io.InputStream, long); Method changed: old: public ContentLengthInputStream(java.io.InputStream, int); new: deprecated: public ContentLengthInputStream(java.io.InputStream, int); Class changed: org.apache.commons.httpclient.Cookie Methods removed: deprecated: public static org.apache.commons.httpclient.Header createCookieHeader(java.lang.String, int, java.lang.String, boolean, java.util.Date, org.apache.commons.httpclient.Cookie[]) throws java.lang.IllegalArgumentException; deprecated: public static org.apache.commons.httpclient.Header createCookieHeader(java.lang.String, int, java.lang.String, boolean, org.apache.commons.httpclient.Cookie[]) throws java.lang.IllegalArgumentException; deprecated: public static org.apache.commons.httpclient.Header createCookieHeader(java.lang.String, java.lang.String, boolean, org.apache.commons.httpclient.Cookie[]) throws java.lang.IllegalArgumentException; deprecated: public static org.apache.commons.httpclient.Header createCookieHeader(java.lang.String, java.lang.String, org.apache.commons.httpclient.Cookie[]); deprecated: public boolean matches(java.lang.String, int, java.lang.String, boolean); deprecated: public boolean matches(java.lang.String, int, java.lang.String, boolean, java.util.Date); deprecated: public static org.apache.commons.httpclient.Cookie[] parse(java.lang.String, int, java.lang.String, org.apache.commons.httpclient.Header) throws org.apache.commons.httpclient.HttpException, java.lang.IllegalArgumentException; deprecated: public static org.apache.commons.httpclient.Cookie[] parse(java.lang.String, int, java.lang.String, boolean, org.apache.commons.httpclient.Header) throws org.apache.commons.httpclient.HttpException; deprecated: public static org.apache.commons.httpclient.Cookie[] parse(java.lang.String, java.lang.String, org.apache.commons.httpclient.Header) throws org.apache.commons.httpclient.HttpException, java.lang.IllegalArgumentException; deprecated: public static org.apache.commons.httpclient.Cookie[] parse(java.lang.String, java.lang.String, boolean, org.apache.commons.httpclient.Header) throws org.apache.commons.httpclient.HttpException, java.lang.IllegalArgumentException; Class changed: org.apache.commons.httpclient.DefaultMethodRetryHandler Class descriptor changed: old: public org.apache.commons.httpclient.DefaultMethodRetryHandler extends java.lang.Object implements org.apache.commons.httpclient.MethodRetryHandler new: deprecated: public org.apache.commons.httpclient.DefaultMethodRetryHandler extends java.lang.Object implements org.apache.commons.httpclient.MethodRetryHandler Class changed: org.apache.commons.httpclient.Header Methods added: public Header(java.lang.String, java.lang.String, boolean); public org.apache.commons.httpclient.HeaderElement[] getElements(); public boolean isAutogenerated(); Method changed: old: public org.apache.commons.httpclient.HeaderElement[] getValues() throws org.apache.commons.httpclient.HttpException; new: deprecated: public org.apache.commons.httpclient.HeaderElement[] getValues() throws org.apache.commons.httpclient.HttpException; Class changed: org.apache.commons.httpclient.HeaderElement Methods removed: protected void setParameters(org.apache.commons.httpclient.NameValuePair[]); Methods added: public HeaderElement(char[]); public HeaderElement(char[], int, int); public final static org.apache.commons.httpclient.HeaderElement[] parseElements(java.lang.String); public final static org.apache.commons.httpclient.HeaderElement[] parseElements(char[]); Method changed: old: public final static org.apache.commons.httpclient.HeaderElement[] parse(java.lang.String) throws org.apache.commons.httpclient.HttpException; new: deprecated: public final static org.apache.commons.httpclient.HeaderElement[] parse(java.lang.String) throws org.apache.commons.httpclient.HttpException; Class changed: org.apache.commons.httpclient.HeaderGroup Methods added: public java.util.Iterator getIterator(); Class changed: org.apache.commons.httpclient.HostConfiguration Methods added: public org.apache.commons.httpclient.params.HostParams getParams(); public synchronized void setHost(org.apache.commons.httpclient.HttpHost); public void setParams(org.apache.commons.httpclient.params.HostParams); public synchronized void setProxyHost(org.apache.commons.httpclient.ProxyHost); Fields added: public final static org.apache.commons.httpclient.HostConfiguration ANY_HOST_CONFIGURATION; Method changed: old: public synchronized java.lang.String getVirtualHost(); new: deprecated: public synchronized java.lang.String getVirtualHost(); Method changed: old: public int hashCode(); new: public synchronized int hashCode(); Method changed: old: public synchronized boolean isHostSet(); new: deprecated: public synchronized boolean isHostSet(); Method changed: old: public synchronized boolean isProxySet(); new: deprecated: public synchronized boolean isProxySet(); Method changed: old: public synchronized void setHost(java.lang.String, java.lang.String, int, org.apache.commons.httpclient.protocol.Protocol); new: deprecated: public synchronized void setHost(java.lang.String, java.lang.String, int, org.apache.commons.httpclient.protocol.Protocol); Class changed: org.apache.commons.httpclient.HttpClient Methods removed: deprecated: public void endSession() throws java.io.IOException; deprecated: public void startSession(java.lang.String, int); deprecated: public void startSession(java.lang.String, int, java.lang.String, int); deprecated: public void startSession(java.lang.String, int, java.lang.String, int, boolean); deprecated: public void startSession(java.lang.String, int, org.apache.commons.httpclient.Credentials); deprecated: public void startSession(java.lang.String, int, org.apache.commons.httpclient.Credentials, boolean); deprecated: public void startSession(java.lang.String, int, boolean); deprecated: public void startSession(java.net.URL) throws java.lang.IllegalArgumentException; deprecated: public void startSession(java.net.URL, org.apache.commons.httpclient.Credentials) throws java.lang.IllegalArgumentException; deprecated: public void startSession(org.apache.commons.httpclient.URI) throws org.apache.commons.httpclient.URIException, java.lang.IllegalStateException; Methods added: public HttpClient(org.apache.commons.httpclient.params.HttpClientParams); public HttpClient(org.apache.commons.httpclient.params.HttpClientParams, org.apache.commons.httpclient.HttpConnectionManager); public org.apache.commons.httpclient.params.HttpClientParams getParams(); public void setParams(org.apache.commons.httpclient.params.HttpClientParams); Method changed: old: public synchronized boolean isStrictMode(); new: deprecated: public synchronized boolean isStrictMode(); Method changed: old: public synchronized void setConnectionTimeout(int); new: deprecated: public synchronized void setConnectionTimeout(int); Method changed: old: public synchronized void setHttpConnectionFactoryTimeout(long); new: deprecated: public synchronized void setHttpConnectionFactoryTimeout(long); Method changed: old: public synchronized void setStrictMode(boolean); new: deprecated: public synchronized void setStrictMode(boolean); Method changed: old: public synchronized void setTimeout(int); new: deprecated: public synchronized void setTimeout(int); Class changed: org.apache.commons.httpclient.HttpConnection Methods removed: deprecated: public HttpConnection(java.lang.String, int, java.lang.String, int, boolean); deprecated: public HttpConnection(java.lang.String, int, boolean); deprecated: public java.io.OutputStream getRequestOutputStream(boolean) throws java.io.IOException, java.lang.IllegalStateException; deprecated: public java.io.InputStream getResponseInputStream(org.apache.commons.httpclient.HttpMethod) throws java.io.IOException, java.lang.IllegalStateException; deprecated: public void setSecure(boolean) throws java.lang.IllegalStateException; Methods added: public HttpConnection(java.lang.String, int, java.lang.String, int, org.apache.commons.httpclient.protocol.Protocol); public boolean closeIfStale() throws java.io.IOException; public org.apache.commons.httpclient.params.HttpConnectionParams getParams(); protected java.net.Socket getSocket(); protected boolean isLocked(); public void print(java.lang.String, java.lang.String) throws java.io.IOException, java.lang.IllegalStateException; public void printLine(java.lang.String, java.lang.String) throws java.io.IOException, java.lang.IllegalStateException; public java.lang.String readLine(java.lang.String) throws java.io.IOException, java.lang.IllegalStateException; protected void setLocked(boolean); public void setParams(org.apache.commons.httpclient.params.HttpConnectionParams); public void setSocketTimeout(int) throws java.net.SocketException, java.lang.IllegalStateException; Method changed: old: public HttpConnection(java.lang.String, int, java.lang.String, java.lang.String, int, org.apache.commons.httpclient.protocol.Protocol); new: deprecated: public HttpConnection(java.lang.String, int, java.lang.String, java.lang.String, int, org.apache.commons.httpclient.protocol.Protocol); Method changed: old: public int getSoTimeout() throws java.net.SocketException; new: deprecated: public int getSoTimeout() throws java.net.SocketException; Method changed: old: public java.lang.String getVirtualHost(); new: deprecated: public java.lang.String getVirtualHost(); Method changed: old: protected boolean isStale(); new: protected boolean isStale() throws java.io.IOException; Method changed: old: public boolean isStaleCheckingEnabled(); new: deprecated: public boolean isStaleCheckingEnabled(); Method changed: old: public void print(java.lang.String) throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: deprecated: public void print(java.lang.String) throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void printLine() throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: public void printLine() throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void printLine(java.lang.String) throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: deprecated: public void printLine(java.lang.String) throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public java.lang.String readLine() throws java.io.IOException, java.lang.IllegalStateException; new: deprecated: public java.lang.String readLine() throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void setConnectionTimeout(int); new: deprecated: public void setConnectionTimeout(int); Method changed: old: public void setSendBufferSize(int) throws java.net.SocketException; new: deprecated: public void setSendBufferSize(int) throws java.net.SocketException; Method changed: old: public void setSoTimeout(int) throws java.net.SocketException, java.lang.IllegalStateException; new: deprecated: public void setSoTimeout(int) throws java.net.SocketException, java.lang.IllegalStateException; Method changed: old: public void setStaleCheckingEnabled(boolean); new: deprecated: public void setStaleCheckingEnabled(boolean); Method changed: old: public void setVirtualHost(java.lang.String) throws java.lang.IllegalStateException; new: deprecated: public void setVirtualHost(java.lang.String) throws java.lang.IllegalStateException; Method changed: old: public void shutdownOutput(); new: deprecated: public void shutdownOutput(); Method changed: old: public void write(byte[]) throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: public void write(byte[]) throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void write(byte[], int, int) throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: public void write(byte[], int, int) throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void writeLine() throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: public void writeLine() throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void writeLine(byte[]) throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: public void writeLine(byte[]) throws java.io.IOException, java.lang.IllegalStateException; Class changed: org.apache.commons.httpclient.HttpConnectionManager Methods added: public abstract void closeIdleConnections(long); public abstract org.apache.commons.httpclient.HttpConnection getConnectionWithTimeout(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.ConnectionPoolTimeoutException; public abstract org.apache.commons.httpclient.params.HttpConnectionManagerParams getParams(); public abstract void setParams(org.apache.commons.httpclient.params.HttpConnectionManagerParams); Method changed: old: public abstract org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.HttpException; new: deprecated: public abstract org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.HttpException; Class changed: org.apache.commons.httpclient.HttpConstants Class descriptor changed: old: public org.apache.commons.httpclient.HttpConstants extends java.lang.Object new: deprecated: public org.apache.commons.httpclient.HttpConstants extends java.lang.Object Class changed: org.apache.commons.httpclient.HttpException Methods added: public HttpException(java.lang.String, java.lang.Throwable); public java.lang.Throwable getCause(); deprecated: public java.lang.String getReason(); deprecated: public int getReasonCode(); public void printStackTrace(); public void printStackTrace(java.io.PrintStream); public void printStackTrace(java.io.PrintWriter); deprecated: public void setReason(java.lang.String); deprecated: public void setReasonCode(int); Class descriptor changed: old: public org.apache.commons.httpclient.HttpException extends org.apache.commons.httpclient.URIException new: public org.apache.commons.httpclient.HttpException extends java.io.IOException Class changed: org.apache.commons.httpclient.HttpMethod Methods added: public abstract void abort(); public abstract org.apache.commons.httpclient.auth.AuthState getHostAuthState(); public abstract org.apache.commons.httpclient.params.HttpMethodParams getParams(); public abstract org.apache.commons.httpclient.auth.AuthState getProxyAuthState(); public abstract org.apache.commons.httpclient.Header[] getRequestHeaders(java.lang.String); public abstract org.apache.commons.httpclient.Header[] getResponseHeaders(java.lang.String); public abstract boolean isRequestSent(); public abstract void removeRequestHeader(org.apache.commons.httpclient.Header); public abstract void setParams(org.apache.commons.httpclient.params.HttpMethodParams); public abstract void setURI(org.apache.commons.httpclient.URI) throws org.apache.commons.httpclient.URIException; Method changed: old: public abstract org.apache.commons.httpclient.HostConfiguration getHostConfiguration(); new: deprecated: public abstract org.apache.commons.httpclient.HostConfiguration getHostConfiguration(); Method changed: old: public abstract byte[] getResponseBody(); new: public abstract byte[] getResponseBody() throws java.io.IOException; Method changed: old: public abstract java.lang.String getResponseBodyAsString(); new: public abstract java.lang.String getResponseBodyAsString() throws java.io.IOException; Method changed: old: public abstract boolean isStrictMode(); new: deprecated: public abstract boolean isStrictMode(); Method changed: old: public abstract void setStrictMode(boolean); new: deprecated: public abstract void setStrictMode(boolean); Class changed: org.apache.commons.httpclient.HttpMethodBase Methods removed: protected void addAuthorizationRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected void addContentLengthRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected void addProxyAuthorizationRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected void fakeResponse(org.apache.commons.httpclient.StatusLine, org.apache.commons.httpclient.HeaderGroup, java.io.InputStream); protected int getRequestContentLength(); protected int getResponseContentLength(); Methods added: public void abort(); public org.apache.commons.httpclient.HttpVersion getEffectiveVersion(); public org.apache.commons.httpclient.auth.AuthState getHostAuthState(); public org.apache.commons.httpclient.params.HttpMethodParams getParams(); public org.apache.commons.httpclient.auth.AuthState getProxyAuthState(); public org.apache.commons.httpclient.Header[] getRequestHeaders(java.lang.String); public long getResponseContentLength(); public org.apache.commons.httpclient.Header[] getResponseHeaders(java.lang.String); public boolean isAborted(); public boolean isRequestSent(); public void removeRequestHeader(org.apache.commons.httpclient.Header); public void setParams(org.apache.commons.httpclient.params.HttpMethodParams); public void setURI(org.apache.commons.httpclient.URI) throws org.apache.commons.httpclient.URIException; Fields removed: protected final static org.apache.commons.httpclient.Header USER_AGENT; Method changed: old: public int execute(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws org.apache.commons.httpclient.HttpException, org.apache.commons.httpclient.HttpRecoverableException, java.io.IOException; new: public int execute(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws org.apache.commons.httpclient.HttpException, java.io.IOException; Method changed: old: public java.lang.String getAuthenticationRealm(); new: deprecated: public java.lang.String getAuthenticationRealm(); Method changed: old: protected static java.lang.String getContentCharSet(org.apache.commons.httpclient.Header); new: protected java.lang.String getContentCharSet(org.apache.commons.httpclient.Header); Method changed: old: public org.apache.commons.httpclient.HostConfiguration getHostConfiguration(); new: deprecated: public org.apache.commons.httpclient.HostConfiguration getHostConfiguration(); Method changed: old: public org.apache.commons.httpclient.MethodRetryHandler getMethodRetryHandler(); new: deprecated: public org.apache.commons.httpclient.MethodRetryHandler getMethodRetryHandler(); Method changed: old: public java.lang.String getProxyAuthenticationRealm(); new: deprecated: public java.lang.String getProxyAuthenticationRealm(); Method changed: old: public int getRecoverableExceptionCount(); new: deprecated: public int getRecoverableExceptionCount(); Method changed: old: public byte[] getResponseBody(); new: public byte[] getResponseBody() throws java.io.IOException; Method changed: old: public java.lang.String getResponseBodyAsString(); new: public java.lang.String getResponseBodyAsString() throws java.io.IOException; Method changed: old: public boolean isHttp11(); new: deprecated: public boolean isHttp11(); Method changed: old: public boolean isStrictMode(); new: deprecated: public boolean isStrictMode(); Method changed: old: protected void readResponse(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws org.apache.commons.httpclient.HttpException; new: protected void readResponse(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; Method changed: old: protected void readStatusLine(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpRecoverableException, org.apache.commons.httpclient.HttpException; new: protected void readStatusLine(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; Method changed: old: public void setHostConfiguration(org.apache.commons.httpclient.HostConfiguration); new: deprecated: public void setHostConfiguration(org.apache.commons.httpclient.HostConfiguration); Method changed: old: public void setHttp11(boolean); new: deprecated: public void setHttp11(boolean); Method changed: old: public void setMethodRetryHandler(org.apache.commons.httpclient.MethodRetryHandler); new: deprecated: public void setMethodRetryHandler(org.apache.commons.httpclient.MethodRetryHandler); Method changed: old: public void setStrictMode(boolean); new: deprecated: public void setStrictMode(boolean); Class changed: org.apache.commons.httpclient.HttpParser Methods added: public static org.apache.commons.httpclient.Header[] parseHeaders(java.io.InputStream, java.lang.String) throws java.io.IOException, org.apache.commons.httpclient.HttpException; public static java.lang.String readLine(java.io.InputStream, java.lang.String) throws java.io.IOException; Method changed: old: public static org.apache.commons.httpclient.Header[] parseHeaders(java.io.InputStream) throws java.io.IOException, org.apache.commons.httpclient.HttpException; new: deprecated: public static org.apache.commons.httpclient.Header[] parseHeaders(java.io.InputStream) throws java.io.IOException, org.apache.commons.httpclient.HttpException; Method changed: old: public static java.lang.String readLine(java.io.InputStream) throws java.io.IOException; new: deprecated: public static java.lang.String readLine(java.io.InputStream) throws java.io.IOException; Class changed: org.apache.commons.httpclient.HttpRecoverableException Class descriptor changed: old: public org.apache.commons.httpclient.HttpRecoverableException extends org.apache.commons.httpclient.HttpException new: deprecated: public org.apache.commons.httpclient.HttpRecoverableException extends org.apache.commons.httpclient.HttpException Class changed: org.apache.commons.httpclient.HttpState Methods removed: deprecated: public synchronized org.apache.commons.httpclient.Cookie[] getCookies(java.lang.String, int, java.lang.String, boolean, java.util.Date); deprecated: public synchronized org.apache.commons.httpclient.Credentials getCredentials(java.lang.String); deprecated: public synchronized org.apache.commons.httpclient.HttpConnectionManager getHttpConnectionManager(); deprecated: public synchronized org.apache.commons.httpclient.Credentials getProxyCredentials(java.lang.String); deprecated: public synchronized void setCredentials(java.lang.String, org.apache.commons.httpclient.Credentials); deprecated: public synchronized void setHttpConnectionManager(org.apache.commons.httpclient.HttpConnectionManager); deprecated: public synchronized void setProxyCredentials(java.lang.String, org.apache.commons.httpclient.Credentials); Methods added: public void clear(); public void clearCookies(); public void clearCredentials(); public void clearProxyCredentials(); public synchronized org.apache.commons.httpclient.Credentials getCredentials(org.apache.commons.httpclient.auth.AuthScope); public synchronized org.apache.commons.httpclient.Credentials getProxyCredentials(org.apache.commons.httpclient.auth.AuthScope); public synchronized void setCredentials(org.apache.commons.httpclient.auth.AuthScope, org.apache.commons.httpclient.Credentials); public synchronized void setProxyCredentials(org.apache.commons.httpclient.auth.AuthScope, org.apache.commons.httpclient.Credentials); Fields removed: public final static org.apache.commons.httpclient.auth.HttpAuthRealm DEFAULT_AUTH_REALM; Method changed: old: public int getCookiePolicy(); new: deprecated: public int getCookiePolicy(); Method changed: old: public synchronized org.apache.commons.httpclient.Credentials getCredentials(java.lang.String, java.lang.String); new: deprecated: public synchronized org.apache.commons.httpclient.Credentials getCredentials(java.lang.String, java.lang.String); Method changed: old: public synchronized org.apache.commons.httpclient.Credentials getProxyCredentials(java.lang.String, java.lang.String); new: deprecated: public synchronized org.apache.commons.httpclient.Credentials getProxyCredentials(java.lang.String, java.lang.String); Method changed: old: public boolean isAuthenticationPreemptive(); new: deprecated: public boolean isAuthenticationPreemptive(); Method changed: old: public void setAuthenticationPreemptive(boolean); new: deprecated: public void setAuthenticationPreemptive(boolean); Method changed: old: public void setCookiePolicy(int); new: deprecated: public void setCookiePolicy(int); Method changed: old: public synchronized void setCredentials(java.lang.String, java.lang.String, org.apache.commons.httpclient.Credentials); new: deprecated: public synchronized void setCredentials(java.lang.String, java.lang.String, org.apache.commons.httpclient.Credentials); Method changed: old: public synchronized void setProxyCredentials(java.lang.String, java.lang.String, org.apache.commons.httpclient.Credentials); new: deprecated: public synchronized void setProxyCredentials(java.lang.String, java.lang.String, org.apache.commons.httpclient.Credentials); Class changed: org.apache.commons.httpclient.MethodRetryHandler Class descriptor changed: old: public abstract org.apache.commons.httpclient.MethodRetryHandler extends java.lang.Object new: deprecated: public abstract org.apache.commons.httpclient.MethodRetryHandler extends java.lang.Object Class changed: org.apache.commons.httpclient.MultiThreadedHttpConnectionManager Methods added: public void closeIdleConnections(long); public void deleteClosedConnections(); public org.apache.commons.httpclient.HttpConnection getConnectionWithTimeout(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.ConnectionPoolTimeoutException; public int getConnectionsInPool(); public int getConnectionsInPool(org.apache.commons.httpclient.HostConfiguration); public org.apache.commons.httpclient.params.HttpConnectionManagerParams getParams(); public void setParams(org.apache.commons.httpclient.params.HttpConnectionManagerParams); Method changed: old: public org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.HttpException; new: deprecated: public org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.HttpException; Method changed: old: public int getConnectionsInUse(); new: deprecated: public int getConnectionsInUse(); Method changed: old: public int getConnectionsInUse(org.apache.commons.httpclient.HostConfiguration); new: deprecated: public int getConnectionsInUse(org.apache.commons.httpclient.HostConfiguration); Method changed: old: public int getMaxConnectionsPerHost(); new: deprecated: public int getMaxConnectionsPerHost(); Method changed: old: public int getMaxTotalConnections(); new: deprecated: public int getMaxTotalConnections(); Method changed: old: public boolean isConnectionStaleCheckingEnabled(); new: deprecated: public boolean isConnectionStaleCheckingEnabled(); Method changed: old: public void setConnectionStaleCheckingEnabled(boolean); new: deprecated: public void setConnectionStaleCheckingEnabled(boolean); Method changed: old: public void setMaxConnectionsPerHost(int); new: deprecated: public void setMaxConnectionsPerHost(int); Method changed: old: public void setMaxTotalConnections(int); new: deprecated: public void setMaxTotalConnections(int); Class changed: org.apache.commons.httpclient.NTCredentials Methods added: public boolean equals(java.lang.Object); public int hashCode(); Method changed: old: public NTCredentials(); new: deprecated: public NTCredentials(); Method changed: old: public void setDomain(java.lang.String); new: deprecated: public void setDomain(java.lang.String); Method changed: old: public void setHost(java.lang.String); new: deprecated: public void setHost(java.lang.String); Class changed: org.apache.commons.httpclient.SimpleHttpConnectionManager Methods added: public void closeIdleConnections(long); public org.apache.commons.httpclient.HttpConnection getConnectionWithTimeout(org.apache.commons.httpclient.HostConfiguration, long); public org.apache.commons.httpclient.params.HttpConnectionManagerParams getParams(); public void setParams(org.apache.commons.httpclient.params.HttpConnectionManagerParams); Fields added: protected org.apache.commons.httpclient.HttpConnection httpConnection; Method changed: old: public org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long); new: deprecated: public org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long); Method changed: old: public boolean isConnectionStaleCheckingEnabled(); new: deprecated: public boolean isConnectionStaleCheckingEnabled(); Method changed: old: public void setConnectionStaleCheckingEnabled(boolean); new: deprecated: public void setConnectionStaleCheckingEnabled(boolean); Class changed: org.apache.commons.httpclient.URI Methods removed: deprecated: public URI(java.net.URL) throws org.apache.commons.httpclient.URIException; Methods added: public URI(java.lang.String, boolean) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; public URI(java.lang.String, boolean, java.lang.String) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; public URI(org.apache.commons.httpclient.URI, java.lang.String, boolean) throws org.apache.commons.httpclient.URIException; protected static java.lang.String decode(java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; Method changed: old: public URI(java.lang.String) throws org.apache.commons.httpclient.URIException; new: deprecated: public URI(java.lang.String) throws org.apache.commons.httpclient.URIException; Method changed: old: public URI(java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; new: deprecated: public URI(java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; Method changed: old: public URI(org.apache.commons.httpclient.URI, java.lang.String) throws org.apache.commons.httpclient.URIException; new: deprecated: public URI(org.apache.commons.httpclient.URI, java.lang.String) throws org.apache.commons.httpclient.URIException; Method changed: old: public URI(char[]) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; new: deprecated: public URI(char[]) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; Method changed: old: public URI(char[], java.lang.String) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; new: deprecated: public URI(char[], java.lang.String) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; Class changed: org.apache.commons.httpclient.URIException Class descriptor changed: old: public org.apache.commons.httpclient.URIException extends java.io.IOException new: public org.apache.commons.httpclient.URIException extends org.apache.commons.httpclient.HttpException Method changed: old: public java.lang.String getReason(); new: deprecated: public java.lang.String getReason(); Method changed: old: public void setReason(java.lang.String); new: deprecated: public void setReason(java.lang.String); Method changed: old: public void setReasonCode(int); new: deprecated: public void setReasonCode(int); Class changed: org.apache.commons.httpclient.UsernamePasswordCredentials Methods added: public boolean equals(java.lang.Object); public int hashCode(); Method changed: old: public UsernamePasswordCredentials(); new: deprecated: public UsernamePasswordCredentials(); Method changed: old: public void setPassword(java.lang.String); new: deprecated: public void setPassword(java.lang.String); Method changed: old: public void setUserName(java.lang.String); new: deprecated: public void setUserName(java.lang.String); Class changed: org.apache.commons.httpclient.auth.AuthChallengeParser Methods added: public static java.util.Map parseChallenges(org.apache.commons.httpclient.Header[]) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class changed: org.apache.commons.httpclient.auth.AuthScheme Methods added: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract boolean isComplete(); public abstract boolean isConnectionBased(); public abstract void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public abstract java.lang.String getID(); new: deprecated: public abstract java.lang.String getID(); Class changed: org.apache.commons.httpclient.auth.AuthSchemeBase Methods added: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract boolean isComplete(); public abstract boolean isConnectionBased(); public abstract void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class descriptor changed: old: public abstract org.apache.commons.httpclient.auth.AuthSchemeBase extends java.lang.Object implements org.apache.commons.httpclient.auth.AuthScheme new: deprecated: public abstract org.apache.commons.httpclient.auth.AuthSchemeBase extends java.lang.Object implements org.apache.commons.httpclient.auth.AuthScheme Method changed: old: public AuthSchemeBase(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; new: deprecated: public AuthSchemeBase(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public abstract java.lang.String getID(); new: deprecated: public abstract java.lang.String getID(); Class changed: org.apache.commons.httpclient.auth.AuthenticationException Methods added: public AuthenticationException(java.lang.String, java.lang.Throwable); Class descriptor changed: old: public org.apache.commons.httpclient.auth.AuthenticationException extends org.apache.commons.httpclient.HttpException new: public org.apache.commons.httpclient.auth.AuthenticationException extends org.apache.commons.httpclient.ProtocolException Class changed: org.apache.commons.httpclient.auth.BasicScheme Methods added: public BasicScheme(); public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public static java.lang.String authenticate(org.apache.commons.httpclient.UsernamePasswordCredentials, java.lang.String); public boolean isComplete(); public boolean isConnectionBased(); public void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public BasicScheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; new: deprecated: public BasicScheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static java.lang.String authenticate(org.apache.commons.httpclient.UsernamePasswordCredentials); new: deprecated: public static java.lang.String authenticate(org.apache.commons.httpclient.UsernamePasswordCredentials); Class changed: org.apache.commons.httpclient.auth.DigestScheme Methods removed: public static java.lang.String authenticate(org.apache.commons.httpclient.UsernamePasswordCredentials, java.util.Map) throws org.apache.commons.httpclient.auth.AuthenticationException; public static java.lang.String createDigest(java.lang.String, java.lang.String, java.util.Map) throws org.apache.commons.httpclient.auth.AuthenticationException; public static java.lang.String createDigestHeader(java.lang.String, java.util.Map, java.lang.String); Methods added: public DigestScheme(); public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public boolean isComplete(); public boolean isConnectionBased(); public void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public DigestScheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; new: deprecated: public DigestScheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static java.lang.String createCnonce() throws org.apache.commons.httpclient.auth.AuthenticationException; new: public static java.lang.String createCnonce(); Method changed: old: public java.lang.String getID(); new: deprecated: public java.lang.String getID(); Class changed: org.apache.commons.httpclient.auth.HttpAuthRealm Methods removed: public boolean equals(java.lang.Object); public int hashCode(); public java.lang.String toString(); Class descriptor changed: old: public org.apache.commons.httpclient.auth.HttpAuthRealm extends java.lang.Object new: deprecated: public org.apache.commons.httpclient.auth.HttpAuthRealm extends org.apache.commons.httpclient.auth.AuthScope Class changed: org.apache.commons.httpclient.auth.HttpAuthenticator Class descriptor changed: old: public final org.apache.commons.httpclient.auth.HttpAuthenticator extends java.lang.Object new: deprecated: public final org.apache.commons.httpclient.auth.HttpAuthenticator extends java.lang.Object Method changed: old: public static boolean authenticate(org.apache.commons.httpclient.auth.AuthScheme, org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public static boolean authenticate(org.apache.commons.httpclient.auth.AuthScheme, org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static boolean authenticateDefault(org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public static boolean authenticateDefault(org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static boolean authenticateProxy(org.apache.commons.httpclient.auth.AuthScheme, org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public static boolean authenticateProxy(org.apache.commons.httpclient.auth.AuthScheme, org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static boolean authenticateProxyDefault(org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public static boolean authenticateProxyDefault(org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static org.apache.commons.httpclient.auth.AuthScheme selectAuthScheme(org.apache.commons.httpclient.Header[]) throws org.apache.commons.httpclient.auth.MalformedChallengeException; new: deprecated: public static org.apache.commons.httpclient.auth.AuthScheme selectAuthScheme(org.apache.commons.httpclient.Header[]) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class changed: org.apache.commons.httpclient.auth.MalformedChallengeException Methods added: public MalformedChallengeException(java.lang.String, java.lang.Throwable); Class descriptor changed: old: public org.apache.commons.httpclient.auth.MalformedChallengeException extends org.apache.commons.httpclient.HttpException new: public org.apache.commons.httpclient.auth.MalformedChallengeException extends org.apache.commons.httpclient.ProtocolException Class changed: org.apache.commons.httpclient.auth.NTLMScheme Methods added: public NTLMScheme(); public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; deprecated: public static java.lang.String authenticate(org.apache.commons.httpclient.NTCredentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; public boolean isComplete(); public boolean isConnectionBased(); public void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class descriptor changed: old: public org.apache.commons.httpclient.auth.NTLMScheme extends org.apache.commons.httpclient.auth.AuthSchemeBase new: public org.apache.commons.httpclient.auth.NTLMScheme extends java.lang.Object implements org.apache.commons.httpclient.auth.AuthScheme Method changed: old: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static java.lang.String authenticate(org.apache.commons.httpclient.NTCredentials, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public static java.lang.String authenticate(org.apache.commons.httpclient.NTCredentials, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public java.lang.String getID(); new: deprecated: public java.lang.String getID(); Class changed: org.apache.commons.httpclient.auth.RFC2617Scheme Methods added: public RFC2617Scheme(); deprecated: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract java.lang.String getSchemeName(); public abstract boolean isComplete(); public abstract boolean isConnectionBased(); public void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class descriptor changed: old: public abstract org.apache.commons.httpclient.auth.RFC2617Scheme extends org.apache.commons.httpclient.auth.AuthSchemeBase new: public abstract org.apache.commons.httpclient.auth.RFC2617Scheme extends java.lang.Object implements org.apache.commons.httpclient.auth.AuthScheme Method changed: old: public RFC2617Scheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; new: deprecated: public RFC2617Scheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public java.lang.String getID(); new: deprecated: public java.lang.String getID(); Class changed: org.apache.commons.httpclient.cookie.CookiePolicy Methods added: public static org.apache.commons.httpclient.cookie.CookieSpec getCookieSpec(java.lang.String) throws java.lang.IllegalStateException; public static void registerCookieSpec(java.lang.String, java.lang.Class); public static void unregisterCookieSpec(java.lang.String); Fields added: public final static java.lang.String BROWSER_COMPATIBILITY = compatibility; public final static java.lang.String DEFAULT = default; public final static java.lang.String IGNORE_COOKIES = ignoreCookies; public final static java.lang.String NETSCAPE = netscape; public final static java.lang.String RFC_2109 = rfc2109; Method changed: old: public static org.apache.commons.httpclient.cookie.CookieSpec getCompatibilitySpec(); new: deprecated: public static org.apache.commons.httpclient.cookie.CookieSpec getCompatibilitySpec(); Method changed: old: public static int getDefaultPolicy(); new: deprecated: public static int getDefaultPolicy(); Method changed: old: public static org.apache.commons.httpclient.cookie.CookieSpec getSpecByPolicy(int); new: deprecated: public static org.apache.commons.httpclient.cookie.CookieSpec getSpecByPolicy(int); Method changed: old: public static org.apache.commons.httpclient.cookie.CookieSpec getSpecByVersion(int); new: deprecated: public static org.apache.commons.httpclient.cookie.CookieSpec getSpecByVersion(int); Method changed: old: public static void setDefaultPolicy(int); new: deprecated: public static void setDefaultPolicy(int); Field changed: old: public final static int COMPATIBILITY = 0; new: deprecated: public final static int COMPATIBILITY = 0; Field changed: old: public final static int NETSCAPE_DRAFT = 1; new: deprecated: public final static int NETSCAPE_DRAFT = 1; Field changed: old: public final static int RFC2109 = 2; new: deprecated: public final static int RFC2109 = 2; Class changed: org.apache.commons.httpclient.cookie.CookieSpec Methods added: public abstract boolean domainMatch(java.lang.String, java.lang.String); public abstract java.util.Collection getValidDateFormats(); public abstract boolean pathMatch(java.lang.String, java.lang.String); public abstract void setValidDateFormats(java.util.Collection); Class changed: org.apache.commons.httpclient.cookie.CookieSpecBase Methods added: public boolean domainMatch(java.lang.String, java.lang.String); public java.util.Collection getValidDateFormats(); public boolean pathMatch(java.lang.String, java.lang.String); public void setValidDateFormats(java.util.Collection); Class changed: org.apache.commons.httpclient.cookie.MalformedCookieException Methods added: public MalformedCookieException(java.lang.String, java.lang.Throwable); Class descriptor changed: old: public org.apache.commons.httpclient.cookie.MalformedCookieException extends org.apache.commons.httpclient.HttpException new: public org.apache.commons.httpclient.cookie.MalformedCookieException extends org.apache.commons.httpclient.ProtocolException Class changed: org.apache.commons.httpclient.cookie.NetscapeDraftSpec Methods added: public boolean domainMatch(java.lang.String, java.lang.String); public org.apache.commons.httpclient.Cookie[] parse(java.lang.String, int, java.lang.String, boolean, java.lang.String) throws org.apache.commons.httpclient.cookie.MalformedCookieException; Class changed: org.apache.commons.httpclient.cookie.RFC2109Spec Methods added: public boolean domainMatch(java.lang.String, java.lang.String); Class changed: org.apache.commons.httpclient.methods.EntityEnclosingMethod Methods removed: deprecated: public EntityEnclosingMethod(java.lang.String, java.lang.String); deprecated: public EntityEnclosingMethod(java.lang.String, java.lang.String, java.lang.String); public java.io.InputStream getRequestBody(); public java.lang.String getRequestBodyAsString() throws java.io.IOException; protected int getRequestContentLength(); Methods added: protected void addRequestHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected org.apache.commons.httpclient.methods.RequestEntity generateRequestEntity(); public java.lang.String getRequestCharSet(); protected long getRequestContentLength(); public org.apache.commons.httpclient.methods.RequestEntity getRequestEntity(); public void setContentChunked(boolean); deprecated: public void setRequestContentLength(long); public void setRequestEntity(org.apache.commons.httpclient.methods.RequestEntity); Method changed: old: public void setRequestBody(java.io.InputStream); new: deprecated: public void setRequestBody(java.io.InputStream); Method changed: old: public void setRequestBody(java.lang.String); new: deprecated: public void setRequestBody(java.lang.String); Method changed: old: public void setRequestContentLength(int); new: deprecated: public void setRequestContentLength(int); Field changed: old: public final static int CONTENT_LENGTH_AUTO = -2; new: deprecated: public final static long CONTENT_LENGTH_AUTO = -2; Field changed: old: public final static int CONTENT_LENGTH_CHUNKED = -1; new: deprecated: public final static long CONTENT_LENGTH_CHUNKED = -1; Class changed: org.apache.commons.httpclient.methods.ExpectContinueMethod Methods removed: deprecated: public ExpectContinueMethod(java.lang.String, java.lang.String); deprecated: public ExpectContinueMethod(java.lang.String, java.lang.String, java.lang.String); Class descriptor changed: old: public abstract org.apache.commons.httpclient.methods.ExpectContinueMethod extends org.apache.commons.httpclient.methods.GetMethod new: public abstract org.apache.commons.httpclient.methods.ExpectContinueMethod extends org.apache.commons.httpclient.HttpMethodBase Method changed: old: public boolean getUseExpectHeader(); new: deprecated: public boolean getUseExpectHeader(); Method changed: old: public void setUseExpectHeader(boolean); new: deprecated: public void setUseExpectHeader(boolean); Class changed: org.apache.commons.httpclient.methods.GetMethod Methods removed: deprecated: public GetMethod(java.lang.String, java.io.File); deprecated: public GetMethod(java.lang.String, java.lang.String); deprecated: public GetMethod(java.lang.String, java.lang.String, java.lang.String); deprecated: public java.io.File getFileData(); deprecated: public java.lang.String getTempDir(); deprecated: public java.lang.String getTempFile(); deprecated: public boolean getUseDisk(); protected void readResponseBody(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; deprecated: public void setFileData(java.io.File); deprecated: public void setTempDir(java.lang.String); deprecated: public void setTempFile(java.lang.String); deprecated: public void setUseDisk(boolean); Class changed: org.apache.commons.httpclient.methods.HeadMethod Method changed: old: public int getBodyCheckTimeout(); new: deprecated: public int getBodyCheckTimeout(); Method changed: old: protected void readResponseBody(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException; new: protected void readResponseBody(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws org.apache.commons.httpclient.HttpException, java.io.IOException; Method changed: old: public void setBodyCheckTimeout(int); new: deprecated: public void setBodyCheckTimeout(int); Class changed: org.apache.commons.httpclient.methods.MultipartPostMethod Methods removed: public MultipartPostMethod(java.lang.String, java.lang.String); public MultipartPostMethod(java.lang.String, java.lang.String, java.lang.String); protected int getRequestContentLength(); Methods added: protected void addContentLengthRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected void addContentTypeRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected long getRequestContentLength() throws java.io.IOException; Class descriptor changed: old: public org.apache.commons.httpclient.methods.MultipartPostMethod extends org.apache.commons.httpclient.methods.ExpectContinueMethod new: deprecated: public org.apache.commons.httpclient.methods.MultipartPostMethod extends org.apache.commons.httpclient.methods.ExpectContinueMethod Class changed: org.apache.commons.httpclient.methods.OptionsMethod Method changed: old: public boolean needContentLength(); new: deprecated: public boolean needContentLength(); Class changed: org.apache.commons.httpclient.methods.PostMethod Methods removed: deprecated: public PostMethod(java.lang.String, java.lang.String); deprecated: public PostMethod(java.lang.String, java.lang.String, java.lang.String); protected void addRequestHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected byte[] generateRequestBody(); Methods added: protected org.apache.commons.httpclient.methods.RequestEntity generateRequestEntity(); Class changed: org.apache.commons.httpclient.methods.TraceMethod Method changed: old: public void recycle(); new: deprecated: public void recycle(); Class changed: org.apache.commons.httpclient.methods.multipart.FilePart Fields removed: protected final static byte[] FILE_NAME_BYTES; Class changed: org.apache.commons.httpclient.methods.multipart.Part Methods added: public static long getLengthOfParts(org.apache.commons.httpclient.methods.multipart.Part[], byte[]) throws java.io.IOException; protected byte[] getPartBoundary(); public boolean isRepeatable(); public static void sendParts(java.io.OutputStream, org.apache.commons.httpclient.methods.multipart.Part[], byte[]) throws java.io.IOException; Method changed: old: public static java.lang.String getBoundary(); new: deprecated: public static java.lang.String getBoundary(); Field changed: old: protected final static java.lang.String BOUNDARY = ----------------314159265358979323846; new: deprecated: protected final static java.lang.String BOUNDARY = ----------------314159265358979323846; Field changed: old: protected final static byte[] BOUNDARY_BYTES; new: deprecated: protected final static byte[] BOUNDARY_BYTES; Class changed: org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory Methods added: public java.net.Socket createSocket(java.lang.String, int, java.net.InetAddress, int, org.apache.commons.httpclient.params.HttpConnectionParams) throws java.io.IOException, java.net.UnknownHostException, org.apache.commons.httpclient.ConnectTimeoutException; Class changed: org.apache.commons.httpclient.protocol.Protocol Method changed: old: public Protocol(java.lang.String, org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory, int); new: deprecated: public Protocol(java.lang.String, org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory, int); Class changed: org.apache.commons.httpclient.protocol.ProtocolSocketFactory Methods added: public abstract java.net.Socket createSocket(java.lang.String, int, java.net.InetAddress, int, org.apache.commons.httpclient.params.HttpConnectionParams) throws java.io.IOException, java.net.UnknownHostException, org.apache.commons.httpclient.ConnectTimeoutException; Class changed: org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory Methods added: public java.net.Socket createSocket(java.lang.String, int, java.net.InetAddress, int, org.apache.commons.httpclient.params.HttpConnectionParams) throws java.io.IOException, java.net.UnknownHostException, org.apache.commons.httpclient.ConnectTimeoutException; Class changed: org.apache.commons.httpclient.util.DateParser Methods added: public static java.util.Date parseDate(java.lang.String, java.util.Collection) throws org.apache.commons.httpclient.util.DateParseException; Class descriptor changed: old: public org.apache.commons.httpclient.util.DateParser extends java.lang.Object new: deprecated: public org.apache.commons.httpclient.util.DateParser extends java.lang.Object Class changed: org.apache.commons.httpclient.util.EncodingUtil Methods added: public static byte[] getAsciiBytes(java.lang.String); public static java.lang.String getAsciiString(byte[]); public static java.lang.String getAsciiString(byte[], int, int); public static byte[] getBytes(java.lang.String, java.lang.String); public static java.lang.String getString(byte[], int, int, java.lang.String); public static java.lang.String getString(byte[], java.lang.String); Class changed: org.apache.commons.httpclient.util.URIUtil Methods removed: deprecated: public static java.lang.String toDocumentCharset(java.lang.String) throws org.apache.commons.httpclient.URIException; deprecated: public static java.lang.String toDocumentCharset(java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; deprecated: public static java.lang.String toProtocolCharset(java.lang.String) throws org.apache.commons.httpclient.URIException; deprecated: public static java.lang.String toProtocolCharset(java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; deprecated: public static java.lang.String toUsingCharset(java.lang.String, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; Class changed: org.apache.commons.httpclient.util.URIUtil.Coder Class descriptor changed: old: public org.apache.commons.httpclient.util.URIUtil.Coder extends org.apache.commons.httpclient.URI new: deprecated: public org.apache.commons.httpclient.util.URIUtil.Coder extends org.apache.commons.httpclient.URI Method changed: old: public static java.lang.String decode(char[], java.lang.String) throws org.apache.commons.httpclient.URIException; new: deprecated: public static java.lang.String decode(char[], java.lang.String) throws org.apache.commons.httpclient.URIException; Method changed: old: public static char[] encode(java.lang.String, java.util.BitSet, java.lang.String) throws org.apache.commons.httpclient.URIException; new: deprecated: public static char[] encode(java.lang.String, java.util.BitSet, java.lang.String) throws org.apache.commons.httpclient.URIException; API diff generated by JarDiff http://www.osjava.org/jardiff/ ------------------- Changes since Release Candidate 4: * 37526 - Fixed incorrect processing of HTTP parameters with an empty name Contributed by Oleg Kalnichevski * 37256 - Fixed bug causing MultipartRequestEntity to miscalculate the total content length if any of the parts returns a negative content length value Contributed by Loïc Péron * 37197 - Preemptive auth flag no longer disregarded when tunneling SSL connections via a proxy Contributed by wynand * 37154 - UsernamePasswordCredentials.equals(null) no longer causes NPE Contributed by Oleg Kalnichevski * 37129 - HttpConnection changed to use a protocol socket factory registered for 'http' protocol instead of DefaultProtocolSocketFactory when connecting to a proxy to establish a secure tunnel Contributed by Oleg Kalnichevski Release 3.0 Release Candidate 4 ------------------- Changes since Release Candidate 3: * 36882 - Max connections per host setting did not work Contributed by Oleg Kalnichevski * 36791 - Fixed HttpConnection#isOpen flag concurrency problem Contributed by Jean-Marie White * 36339 - Request is no longer retried if preemptive authentication fails and Basic is the only supported authentication scheme advertised by the target server Contributed by Oleg Kalnichevski * 36372 - nonce-count in digest auth should not be quoted Contributed by Ortwin Glueck * 36369 - Custom Proxy-Connection header no longer gets overwritten Contributed by Oleg Kalnichevski * 36595 - Do not attempt to retry aborted methods Contributed by Oleg Kalnichevski * 36140 - ParameterParser changed to correctly differentiate between empty and null (no value) parameters Contributed by Oleg Kalnichevski * 35085 - HTTP 204 "NO CONTENT" response no longer results in dropped connection. Contributed by Ian Bray * 35944 - Connection always gets released back to the pool even if an unchecked exception is thrown in HttpMethod#releaseConnection method. Contributed by Oleg Kalnichevski * 35642 - Do not retry if host is unreachable. This ensures a connection timeout will be obeyed. Contributed by Ortwin Glueck * 35815 - SimpleHttpConnectionManager now logs warnings when it detects it is being used incorrectly. Contributed by Michael Becke Release 3.0 Release Candidate 3 ------------------- Changes since Release Candidate 2: * 35365 - Added #hashCode and #equals methods for Credentials implementations Contributed by Eric Johnson * 35322 - Stale connection check now correctly works with IBM JSSE/JRE 1.4.x Contributed by Oleg Kalnichevski * 35225 - Fixed a major problem with the browser compatibility policy leaking cookies to 3rd party domains (.mydomain.com -> .notmydomain.com) Contributed by Oleg Kalnichevski * 35328 - DateUtil#formatDate changed to US locale instead of system default Contributed by Yannick * 34960 - DigestScheme changed to take into account charset attribute when available (Known to be used by Microsoft implementation of the Digest auth scheme) Contributed by Oleg Kalnichevski * 35148 - HttpClient now correctly handles relative URIs beginning with a colon. Contributed by Gordon Mohr * 34961 - HttpClient now correctly handles escaped characters in HTTP header elements Contributed by Oleg Kalnichevski * 34780 - HttpClient now always overrides the host of HostConfiguration if an absolute request URI is given Contributed by Oleg Kalnichevski * 34740 - Connection with the proxy is not reopened if an proxy auth failure occurs while SSL tunnel is being established Contributed by Oleg Kalnichevski * 34721 - Virtual host setting is now correctly applied when parsing and matching cookies Contributed by Oleg Kalnichevski * 34583 - DateUtil.formatDate() changed to use GMT instead of the default timezone Contributed by Fred Bierhaus * 34459 - Always use the chunk encoding when request content length cannot be determined (is negative) Contributed by Oleg Kalnichevski * 34427 - Fixed the bug causing an IllegalStateException in AuthState triggered by the combination of preemptive proxy authentication and a cross-site redirect Contributed by Oleg Kalnichevski Release 3.0 Release Candidate 2 ------------------- Changes since Release Candidate 1: * 34255 - Preemptive authentication no longer causes NTLM auth scheme to fail Contributed by Michael Becke * 33720 - Fixed the problem with HttpMethod#getURI applying URL escaped encoding to already encoded URIs Contributed by Oleg Kalnichevski * 34262 - Fixed broken handling of responses that may not include an entity body (status code 204, 304) Contributed by Oleg Kalnichevski * ----- - Fixed broken InputStreamRequestEntity#isRepeatable method Contributed by Matthew-J Watson * 33677 - Fixed the bug preventing the HTTP retry handler from handling ConnectionExceptions Contributed by Oleg Kalnichevski * 33988 - All classes overriding Object#hashCode & Object#equals methods have been reviewed regarding their hashCode/equals contract compliance Contributed by Oleg Kalnichevski * 33947 - Exception in HttpConnection because of unchecked buffer size Contributed by Ortwin Glueck * 33856 - Fixed the problem with the credential-charset parameter not having an effect on the encoding of the NTLM credentials Contributed by Oleg Kalnichevski * 33541 - Fixed the problem with host level parameters having no effect on HTTP CONNECT methods Contributed by Oleg Kalnichevski * 33468 - HttpClient no longer flushes the request line and request headers prior to writing the request body if the 'expect: continue' handshake is not used Contributed by Peter Tolmachov Release 3.0 Release Candidate 1 ------------------- Changes since Beta 1: * 32833 - Cookie with domain .mydomain.com were not sent to host mydomain.com in the browser compatibility mode Contributed by David D. Kilzer * 33021 - Fixed the bug causing the circular redirect if different query parameters are used in the redirect location. Contributed by Ilya Kharmatsky * 32955 - Fixed the bug effectively disabling the stale connection check Contributed by Oliver Koell * 32835 - The two digit year greater than 20 no longer causes the cookie expiry date to be interpreted as a date between 1920 and 1999 Contributed by Oleg Kalnichevski * 32607 - Fixed the problem with ReflectionSocketFactory ignoring the local address of HostConfiguration Contributed by Oleg Kalnichevski * 32409 - HttpState now has new methods for clearing all cookies and credentials. Contributed by Oleg Kalnichevski * 32558 - Fixed retry count bug in DefaultMethodRetryHandler Contributed by Oleg Kalnichevski * 32333 - Connection is now closed upon "Connection: close" request, if the server does not include an explicit connection directive in the response. Contributed by Oleg Kalnichevski * 32765 - Fixed NullPointerException in HostConfiguration.setHost(Sting) Contributed by Stuart Herring * 32742 - Fixed the problem with SO_TIMEOUT parameter having no effect on the method level. Contributed by Ilya Kharmatsky Release 3.0 Beta 1 ------------------- Changes since Alpha 2: * 31929 - Added support for formatting dates. Deprecated DateParser in favor of DateUtil. Contributed by Michael Becke * ----- - HostConfiguration.isHostSet() and Hostconfiguration.isProxySet() have been deprecated. * 31981 - Fixed the bug causing an infinite loop in HttpMethodDirector when using SSL + proxy + host auth + keep alive off Contributed by Oleg Kalnichevski * 31607 - Catch SocketTimeoutException not InterruptedIOException when running in JRE >=1.4 Contributed by Oleg Kalnichevski * 31471 - HostConfiguration refactored Contributed by Oleg Kalnichevski * ----- - ContentLengthInputStream no longer supports mark() & reset() methods. Old broken implementation removed. Contributed by Eric Johnson Release 3.0 Alpha 2 ------------------- Changes since Alpha 1: * 10793 - Configurable default headers Contributed by Oleg Kalnichevski * 30652 - Configurable SO_LINGER Contributed by Oleg Kalnichevski * 31163 - CookieSpec classes made stateful Contributed by Oleg Kalnichevski * 21329 - Added input buffering to improve performance Contributed by Bjarne Rasmussen * 29897 - Connection output buffer is set to a value not greater than 2k Contributed by Oleg Kalnichevski * 29636 - MultiThreadedHttpConnectionManager now support configuring the maximum number of connections on a per host basis. Contributed by Michael Becke * 29874 - Deprecated old HTTP method retry handler based on HttpRecoverableException and replaced it with a new one that acts upon plain IOExceptions Contributed by Oleg Kalnichevski * 29883 - Fixed handling of multi-byte characters in the StringRequestEntity class Contributed by Oleg Kalnichevski * 29383 - Added method to delete closed connections from the connection pool Contributed by Michael Becke * 29549 - Split wire log into header and body parts Contributed by Michael Becke * 29540 - Fixed credentials scope matching algorithm in HttpState#matchCredentials. Contributed by Oleg Kalnichevski * 29439 - Cleaner interface to define authentication scope, handle credentials in HttpState. Contributed by Oleg Kalnichevski * 29377 - Cookies with names containing blanks or starting with $ rejected by RFC2109 spec only. Contributed by Oleg Kalnichevski Release 3.0 Alpha 1 ------------------- Changes on the CVS trunk: * 29265 - HttpConnection.isOpen() no longer logs closed connections as stale. * 28645 - Moved/added content type handling to the RequestEntity. Contributed by Michael Becke , Oleg Kalnichevski * 20288 - Added ability to abort execution of HTTP methods Contributed by Oleg Kalnichevski * 24154 - Socket timeout can be specified at the connection manager, connection or method level Contributed by Oleg Kalnichevski * 16124 - HTTP protocol version can be specified at the client, host or method level Contributed by Oleg Kalnichevski * 28728 - HttpUrl now accepts unescaped passwords Contributed by Michael Becke * 28626 - Fixed ArrayIndexOutOfBoundsException in HttpStatus.getStatusText() Contributed by Oleg Kalnichevski * 26070 - Added support for streaming entities Contributed by Michael Becke * 28566 - CookieSpec interface extended to expose path & domain matching methods; browser compatibility domain matching algorithm modified to mimic the (mis-)behavior of common browsers Contributed by Oleg Kalnichevski * 25372 - Added support for closing idle connections Contributed by Michael Becke , Oleg Kalnichevski * 28322 - Redesign of connect timeout logic; Added support for JDK1.4 connect timeout through reflection Contributed by Oleg Kalnichevski * 28151 - Added stand-alone support for tunneled HTTP proxies via the ProxyClient Contributed by Michael Sample , Michael Becke * 21216 - Fixed the problem of redirect 302 to the same URL causing max redirects exception: circular redirect check added; the circular redirect check is on per default and in lenient mode, is off in strict mode Contributed by Oleg Kalnichevski * 27589 - Added MultiThreadedHttpConnectionManager shutdown() and shutdownAll() Contributed by Michael Becke * 25529 - Redesign of HTTP authentication framework Contributed by Oleg Kalnichevski * Better implementation of ChunkedOutputStream: writes are buffered to an internal buffer (2048 default size); chunks are guaranteed to be at least as large as the buffer size (except for the last chunk) Contributed by Mohammad Rezaei , Goldman, Sachs & Co * HttpMethod#getResponseBody & HttpMethod#getResponseBodyAsString changed to propagate IOException to the caller instead of logging and discarding it Contributed by Oleg Kalnichevski * 10794 - Added interactive authentication support; Authentication realm key is now comprised of host name, port, realm name and authentication type Contributed by Oleg Kalnichevski * 15297 - Added ability to perform alternate authentication Contributed by Oleg Kalnichevski * 16881 - HttpClient made dependent on Commons-codec to perform Base64 and URL encoding/decoding Contributed by Michael Becke , Oleg Kalnichevski * 24560 - Fixed the problem of HttpClient looping endlessly while trying to retrieve status line Contributed by Christian Kohlschuetter * 24671 - Added support for configuring charsets in credentials and HTTP headers Contributed by Michael Becke * Plug-in mechanism for authentication modules Contributed by Oleg Kalnichevski * Added infrastructure to create test cases that involve use of a proxy Contributed by Ortwin Glueck * UserNamePasswordCredentials & NTCredentials made immutable Contributed by Oleg Kalnichevski * 24869 - DigestScheme now only accepts a challenge if all fields required by RFC 2617 are present Contributed by Ortwin Glueck * New framework for server based tests Contributed by Christian Kohlschuetter , Ortwin Glueck * Socket input stream now wrapped with a wrapper class that re-throws certain type of generic IO exceptions as HttpClient specific exceptions. Improved handling of 'used' connections (known to have successfully completed an I/O operation). Contributed by Oleg Kalnichevski * 24012 - Added IgnoreCookiesSpec. Contributed by Michael Becke * 24018 - Cookie and Authorization headers can now be set manually. Contributed by Oleg Kalnichevski * 21151 - Cookie specification plug-in mechanism Contributed by Oleg Kalnichevski * Reworked DigestScheme: the qop Parameter is parsed correctly and not just ignored; missing qop is handled correctly Contributed by Ortwin Glueck * 10790 - Implemented granular non-standards configuration and tracking. Contributed by Oleg Kalnichevski , Michael Becke , Roland Weber , Ortwin Glueck , Adrian Sutton * 15435 - Implemented new preference architecture. Contributed by Oleg Kalnichevski , Michael Becke , Roland Weber , Ortwin Glueck , Adrian Sutton * Deprecated the use of system properties: 'httpclient.useragent', 'httpclient.authentication.preemptive'. * Refactored NameValuePair#equals method. Contributed by Ortwin Glueck * 16729 - Refactored retry/redirect/authentication logic. Contributed by Michael Becke * Added support for disabling HttpConnection.isStale() Contributed by Michael Becke * 10791 - Improved HTTP Version configuration and tracking. Contributed Oleg Kalnichevski , Laura Werner , Michael Becke * 21880 - Content-Length & Transfer-Encoding request headers formerly set by abstract HttpMethodBase class are handled by entity enclosing methods. Contributed by Oleg Kalnichevski * 17947 - HttpMethod#setURI method added. Contributed by Oleg Kalnichevski * 19618 - URI constructors refactored. Contributed by Oleg Kalnichevski * 11240 - Fixed the problem of cookies with ',' in the value string not parsed correctly in some cases Contributed by Oleg Kalnichevski * 21323 - Support for large(long) content added Contributed by Michael Becke * 19868 - Exception handling framework reworked. Contributed by Adrian Sutton , Laura Werner , Oleg Kalnichevski , Michael Becke * 21210 - Header parser completely rewritten. Improved handling of Netscape draft compatible cookies Contributed by Oleg Kalnichevski Release 2.0.2 ------------------- Changes since Release 2.0.1 * ContentLengthInputStream no longer supports mark() & reset() methods. * 21329 - Added input buffering to improve performance Release 2.0.1 ------------------- Changes since Release 2.0 * 30175 - Fixed StringIndexOutOfBoundsException in StatusLine * 29897 - Connection output buffer is set to a value not greater than 2k * 29549 - Split wire log into header and body parts * 29377 - Cookies with names containing blanks or starting with $ rejected by RFC2109 spec only. * 29265 - HttpConnection.isOpen() no longer logs closed connections as stale. * 28728 - HttpUrl now accepts unescaped passwords * 28626 - Fixed ArrayIndexOutOfBoundsException in HttpStatus.getStatusText() * 27589 - Added MultiThreadedHttpConnectionManager shutdown() and shutdownAll(). * HttpMethod#recycle() has been deprecated. Release 2.0 ------------------- Changes since Release Candidate 3: * 26500 - Socket timeout is now correctly set on open connections * 26328 - Fixed getScheme() and getPort() returning wrong defaults for HttpsURL * 26139 - Fixed possible connection leak caused by lack of equals() and hashCode() on protocol socket factories * 26688 - Fixed the problem with HttpURL creating wrong authority String when user info is changed Release 2.0 Release Candidate 3 ------------------- Changes since Release Candidate 2: * HTTP status line parser changed to be more robust when dealing with non-compliant HTTP responses (leading blanks before 'HTTP' signature). * Fixed NPE in HttpMethodBase#responseBodyConsumed(). * 24309 - Changed MultiThreadedHttpConnectionManager to move to a single connection GC thread. Fixed memory and thread leaks. * 24327 - Fixed a bug where HttpClient did not reset the 'force-close connection' flag, when an HTTP method was automatically retried (for instance, when automatically handling an authentication challenge). * 24352 - Fixed the bug causing basic authentication via NLTM Proxy to fail. * 25370 - Connections are now closed and released automatically when an unrecoverable exception occurs in HttpMethodBase.processRequest(). * 23866 - Fixed possible uncaught IllegalArgumentException in Cookie parsing. * 25264 - Added support for cookies with a domain attribute '.domain.com' issued by host 'domain.com' in the browser compatibility mode. Even though the cookie violates RFC 2109 it still gets accepted by mainstream browsers (tested with Mozilla Firebird and IE). * 24869 - Changed DigestScheme to only accept a challenge if all fields required by RFC 2617 are present. * 24671 - Added ISO-8859-1 support for digest authentication passwords, and basic authentication user names and passwords. * Javadoc enhancements. Release 2.0 Release Candidate 2 ------------------- Changes since Release Candidate 1: * Javadoc enhancements. * 23284 - Fixed bug with URI.isIPv4address(). * 22969 - PostMethod#setParameter fixed to correctly overwrite existing parameters. * 22970 - Fixed bug with PostMethod#removeParameter return value. * Improved compliance to RFC 2617 * Added support for digest auth MD5-sess. * 22655 - Added support for stale digest nonce values. * 22968 - HttpConnection.isResponseAvailable() made a little more robust, particularly when used by HeadMethod. * 22941 - Switched the order in which socket streams are closed: output stream closed first, followed by input stream. * Added debugging for connection reclaiming. * Removed JCE initialization code specific to the Sun's implementation. * Fixed problem of Basic, Digest & NTLM authentication schemes under certain circumstances leaking passwords in clear text to the DEBUG log. * Fixed the problem with incorrect selection of the proxy authentication realm. * Changed URI.normalize() to ignore relative path normalization. Release 2.0 Release Candidate 1 ------------------- Changes since Release 2.0 Beta 2: * Option to disable 'stale' connection check that may lead to a slight performance improvement at the cost of reduced reliability * Improved debug logging in multi-threaded connection manager * URI.normalize() no longer has an effect on relative URIs. * 21532 - Removed use of sun.* class in URI.java * 20481 - Changed query param encoding to UTF-8. * 21378 - Multiple transfer encoding headers are now handled properly. Non chunked transfer encodings are now handled correctly. Release 2.0 Beta 2 ------------------- Changes since Release 2.0 Beta 1: * 20240 - Cookies with null path are no longer rejected in the browser compatibility mode. * 20481 - Query parameters set via HttpMethodBase.setQueryString(NameValuePair[]) now correctly use 'application/x-www-form-urlencoded' encoding. * 20481 - POST method correctly applies 'application/x-www-form-urlencoded' encoding. * 20569 - Duplicate connection headers are now handled. * 20646 - Fixed NTLM proxy authentication via SSL. * 20665 - Changed URI to correctly handle path resolution according to http://www.apache.org/~fielding/uri/rev-2002/issues.html. In particular dot-segments are removed when not necessary. * 20938 - Connections are now closed when the request is missing a content length and is not chunked. * 20942 - Requests with DIGEST authentication are now correctly handled when redirected. * 21130 - DEFAULT_MAX_HOST_CONNECTIONS and DEFAULT_MAX_TOTAL_CONNECTIONS are now public in MultiThreadedHttpConnectionManager. * 21201 - URIs are now correctly rebuilt following a call to URI.normalize(). * 21202 - WireLogInputStream.read(byte[]) now logs the correct number of bytes. * Fixed path parsing in RFC2109 cookie spec. * Fixed possible NPE when reading an empty response body. * The various to*Charset() methods of URIUtil have been deprecated. Release 2.0 Beta 1 ------------------- Changes since Release 2.0 Alpha 3: * Changed HttpConnection to use socket timeout instead of busy waiting while expecting input. * Added a getResponseContentLength() method to HttpMethod. * Changed HttpClient to accept correctly encoded URLs instead of attempting to encode them within HttpClient. * 'Expect: 100-continue' logic factored out into an abstract ExpectContinueMethod class * 'Expect: 100-Continue' handshake disabled per default, as it may not work properly with older HTTP/1.0 servers or proxies. * Reengineered authentication code. This includes a fix for HttpClient continually attempting to authenticate to digest realms and provides for better future extensibility. * Authenticator class deprecated * Improved user documentation and example code. * Added ability to differentiate between different hosts using the same realm names. * Added support for specifying a virtual host name to use. * Fixed problem with half-closed connections causing a HttpRecoverableException to be thrown when HttpClient attempts to read from a socket. * Improved reliability with the HEAD method and servers that incorrectly include a response body. * Improved support for connection keep-alive when communicating via a proxy * Added an override of HttpClient.executeMethod that lets the caller specify an HttpState object. * HttpConnectionManager is now a property of the HttpClient class, not of the HttpState class * Added ability to specify the local address that HttpClient should create connections from. Release 2.0 Alpha 3 ------------------- Changes since Release 2.0 Alpha 2: * Abstract EntityEnclosingMethod class has been introduced to encapsulate common behaviour of all entity enclosing methods * "Expect: 100-continue" handshake support added for POST, PUT & multipart POST * Added support for chunked requests for POST and PUT. * Added support for 303 See Other redirections. * Changed input and output streams to use buffering to improve performance. * Improved handling of multivalue headers. Order is now preserved and convenience methods have been added to access each value. * In non-strict mode each cookie sent with the request is put on a separate request header. In strict mode all cookies are crammed into one request header, as before. * ResponseInputStream class deprecated. * RequestOutputStream class deprecated. * Custom character set can be specified for all multipart classes. * Custom content type can be specified for FilePart derived multipart classes. * The useDisk methods in GetMethod class deprecated. Release 2.0 Alpha 2 ------------------ Changes since Release 2.0 Alpha 1: * Mavenized builds. * Digest authentication. NTLM authentication. * Multipart post. * Added a StatusLine class to manage the status line of a http response. * Added ability to cusomize SocketFactory for http and https. New Protocol class to allow for more protocols than just http/s. * Removed the HttpMultiClient, added multi-thread support to HttpClient. * Revamp the streaming policy. Added AutoCloseInputStream, ChunkedInputStream, ChunkedOutputStream, ContentLengthInputStream, ResponseConsumedWatcher * Commons Logging. Dependancy on the commons-logging.jar * Added httpclient.util package. Move Base64 and URIUtil classs into util. * Added a HttpURLConnection wrapper. Allows for wrapping HttpClient into the java standard library. Partial support only. * Added httpclient.cookie package. Complete overhaul of cookie handling. Allows for user specified CookiePolicy and various cookie specification classes. * Removed previously deprecated Cookie.createCookieHeader(String, String,boolean,Cookie[]) method (port number is required for future compatibility). * Also removed Cookie.createCookieHeader(String,String,Cookie[]) method, which should have been deprecated (port number is required for future compatibility) * Renamed HttpMethod.followRedirects to getFollowRedirects, for consistency (and made the corresponding change to HttpMethodBase) commons-httpclient-3.1/RELEASE_NOTES.txt100644 0 0 354536 10661532632 15210 0ustar 0 0 Release 3.1 Final ------------------- New features: ------------------- (1) HTTP state management * RFC 2965 cookie specification support ------------------- Changes since 3.1 RC 1 * [HTTPCLIENT-679] - Fixed RFC3986 compliance problem in URI absolutization code. Contributed by Jeff Dalton * [HTTPCLIENT-676] - Fixed memory leak in MultiThreadedHttpConnectionManager. Contributed by Roland Weber * [HTTPCLIENT-675] - Fixed potential race condition in MultiThreadedHttpConnectionManager. Contributed by Roland Weber * [HTTPCLIENT-665] - Internal collections of HttpState visible to subclasses. Contributed by Roland Weber * [HTTPCLIENT-651] - Improved API Doc regarding response buffering. Contributed by Ortwin Glueck * [HTTPCLIENT-645] - Cookie#compare() changed to do a simple case-sensitive string comparison when comparing path attributes instead of using a static instance of RuleBasedCollator Contributed by Oleg Kalnichevski * [HTTPCLIENT-650] - Wire log for headers written one by one while parsing instead of all at once afterwards, which fails on parse errors. Contributed by Roland Weber API changes since release 3.0.1 ------------------- Class added: public org.apache.commons.httpclient.HttpContentTooLargeException extends org.apache.commons.httpclient.HttpException Class added: public org.apache.commons.httpclient.InvalidRedirectLocationException extends org.apache.commons.httpclient.RedirectException Class added: public org.apache.commons.httpclient.cookie.Cookie2 extends org.apache.commons.httpclient.Cookie Class added: public abstract org.apache.commons.httpclient.cookie.CookieAttributeHandler extends java.lang.Object Class added: public final org.apache.commons.httpclient.cookie.CookieOrigin extends java.lang.Object Class added: public org.apache.commons.httpclient.cookie.CookiePathComparator extends java.lang.Object implements java.util.Comparator Class added: public abstract org.apache.commons.httpclient.cookie.CookieVersionSupport extends java.lang.Object Class added: public org.apache.commons.httpclient.cookie.RFC2965Spec extends org.apache.commons.httpclient.cookie.CookieSpecBase implements org.apache.commons.httpclient.cookie.CookieVersionSupport Class added: public org.apache.commons.httpclient.methods.FileRequestEntity extends java.lang.Object implements org.apache.commons.httpclient.methods.RequestEntity Class changed: org.apache.commons.httpclient.ConnectMethod Methods added: public ConnectMethod(org.apache.commons.httpclient.HostConfiguration); public java.lang.String getPath(); public org.apache.commons.httpclient.URI getURI() throws org.apache.commons.httpclient.URIException; Method changed: old: public ConnectMethod(); new: deprecated: public ConnectMethod(); Class changed: org.apache.commons.httpclient.ContentLengthInputStream Methods added: public int available() throws java.io.IOException; Class changed: org.apache.commons.httpclient.HttpHost Method changed: old: public java.lang.Object clone(); new: public java.lang.Object clone() throws java.lang.CloneNotSupportedException; Class changed: org.apache.commons.httpclient.HttpMethodBase Methods added: public byte[] getResponseBody(int) throws java.io.IOException; public java.lang.String getResponseBodyAsString(int) throws java.io.IOException; protected void processCookieHeaders(org.apache.commons.httpclient.cookie.CookieSpec, org.apache.commons.httpclient.Header[], org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection); Fields added: protected org.apache.commons.httpclient.HttpVersion effectiveVersion; protected org.apache.commons.httpclient.StatusLine statusLine; Class changed: org.apache.commons.httpclient.HttpState Fields added: protected java.util.ArrayList cookies; protected java.util.HashMap credMap; protected java.util.HashMap proxyCred; Class changed: org.apache.commons.httpclient.ProxyHost Method changed: old: public java.lang.Object clone(); new: public java.lang.Object clone() throws java.lang.CloneNotSupportedException; Class changed: org.apache.commons.httpclient.SimpleHttpConnectionManager Methods added: public SimpleHttpConnectionManager(boolean); public void shutdown(); Class changed: org.apache.commons.httpclient.URI Methods removed: protected void readObject(java.io.ObjectInputStream) throws java.lang.ClassNotFoundException, java.io.IOException; protected void writeObject(java.io.ObjectOutputStream) throws java.io.IOException; Method changed: old: public synchronized java.lang.Object clone(); new: public synchronized java.lang.Object clone() throws java.lang.CloneNotSupportedException; Field changed: old: protected static char[] rootPath; new: protected final static char[] rootPath; Class changed: org.apache.commons.httpclient.auth.AuthSchemeBase Methods removed: deprecated: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; deprecated: public abstract java.lang.String getID(); public abstract java.lang.String getParameter(java.lang.String); public abstract java.lang.String getRealm(); public abstract java.lang.String getSchemeName(); public abstract boolean isComplete(); public abstract boolean isConnectionBased(); public abstract void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class changed: org.apache.commons.httpclient.auth.RFC2617Scheme Methods removed: deprecated: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract java.lang.String getSchemeName(); public abstract boolean isComplete(); public abstract boolean isConnectionBased(); Class changed: org.apache.commons.httpclient.cookie.CookiePolicy Methods added: public static java.lang.String[] getRegisteredCookieSpecs(); Fields added: deprecated: public final static int RFC2965 = 3; public final static java.lang.String RFC_2965 = rfc2965; Class changed: org.apache.commons.httpclient.cookie.RFC2109Spec Fields added: public final static java.lang.String SET_COOKIE_KEY = set-cookie; Class changed: org.apache.commons.httpclient.methods.StringRequestEntity Method changed: old: public StringRequestEntity(java.lang.String); new: deprecated: public StringRequestEntity(java.lang.String); Class changed: org.apache.commons.httpclient.params.HttpMethodParams Methods added: public java.lang.String getUriCharset(); public void setUriCharset(java.lang.String); Fields added: public final static java.lang.String HTTP_URI_CHARSET = http.protocol.uri-charset; Class changed: org.apache.commons.httpclient.util.IdleConnectionTimeoutThread Methods added: protected void handleCloseIdleConnections(org.apache.commons.httpclient.HttpConnectionManager); API diff generated by JarDiff http://www.osjava.org/jardiff/ ------------------- Release 3.1 RC 1 ------------------- Changes since Release 3.1 Beta1: * [HTTPCLIENT-641] - Resource Leakage when loading keystore in AuthSSLProtocolSocketFactory. Contributed by Hanson Char * [HTTPCLIENT-634] - Default host config can override scheme of absolute URL. Contributed by John Kristian * [HTTPCLIENT-633] - Changed MultiThreadedHttpConnectionManager's handling of thread interrupts. IllegalThreadStateException is now thrown when waiting threads are interrupted from outside of the connection manager. Contributed by Michael Becke * [HTTPCLIENT-628] - IOException in AutoCloseInputStream.available() Contributed by Roland Weber * [HTTPCLIENT-625] - revised shutdown of MultiThreadedHttpConnectionManager Contributed by Roland Weber * [HTTPCLIENT-622] - Leak in MultiThreadedHttpConnectionManager.ConnectionPool.mapHosts Contributed by Michael Becke and Ortwin Glueck * [HTTPCLIENT-612] - FileRequestEntity now always closes the input file. Contributed by Sebastian Bazley * [HTTPCLIENT-616] - HttpMethodDirector.executeWithRetry method fixed to close the underlying connection if a RuntimeException is thrown Contributed by Jason Bird * [HTTPCLIENT-606] - Added a HTTP method level parameter for URI charset Contributed by Oleg Kalnichevski * [HTTPCLIENT-610] - Added for convenience HttpMethodBase.getResponseBodyAsString(int) Contributed by Ortwin Glueck Release 3.1 Alpha 1 ------------------- Changes since Release 3.0.1: * [HTTPCLIENT-588] - Fixed parsing of relative URIs with internal double-slashes ('//') Contributed by Gordon Mohr * [HTTPCLIENT-587] - Fixed incorrect derelativizing of relative URIs with a scheme Contributed by Gordon Mohr * [HTTPCLIENT-494] - Invalid redirect location now causes a protocol exception Contributed by Oleg Kalnichevski * [HTTPCLIENT-582] - Allow access to registered cookie policies Contributed by Sebastian Bazley * [HTTPCLIENT-189] - Added support for Set-Cookie2 response headers Contributed by Samit Jain * [HTTPCLIENT-66] - Implemented RFC 2965 cookie spec (Cookie2); Added support for port sensitive cookies Contributed by Samit Jain * [HTTPCLIENT-506] - Digest auth scheme now uses correct digest uri in HTTP CONNECT requests Contributed by Oleg Kalnichevski * [HTTPCLIENT-570] - Failed CONNECT no longer leaves connection in an inconsistent state Contributed by Oleg Kalnichevski Release 3.0.1 ------------------- Changes since Release 3.0: * 38636 - Calling HttpState.clearCookies() is now safe from a different thread. Contributed by Peter Dolberg * 38385 - Fixed NPE when creating URI from scheme specific part with null fragment Contributed by Michele Vivoda * 38043 - Digest URI changed to include query parameters Contributed by Oleg Kalnichevski * 38004 - Fixed bug causing cyclic redirects when virtual host is set Contributed by Oleg Kalnichevski * 38139 - Calling deprecated MultiThreadedHttpConnectionManager.setMaxTotalConnections(int) had no effect Contributed by Ortwin Glueck * 37988 - Fixed bug in URI#toString() causing user name / password to stripped from the resultant String Contributed by Oleg Kalnichevski Release 3.0 ------------------- New features: ------------------- (1) Architecture * New preference architecture * Improved exception handling framework * Granular non-standards configuration and tracking * Improved HTTP Version configuration and tracking * Support for streaming entities * Support for tunneled HTTP proxies via the ProxyClient * Ability to abort execution of HTTP methods (2) Connection management * Support for closing idle connections * Support for JDK1.4 connect timeout through reflection * Support for connection manager shutdown (3) Authentication * Improved authentication framework * Plug-in mechanism for authentication modules * Interactive authentication support * Alternate authentication support (4) Cookie management * Cookie specification plug-in mechanism * 'Ignore cookies' cookie policy * Improved Netscape cookie support (5) Redirects * Cross-site redirect support ------------------- API changes since 2.0 Class removed: deprecated: public org.apache.commons.httpclient.Authenticator extends java.lang.Object Class removed: public org.apache.commons.httpclient.HttpConnection.ConnectionTimeoutException extends java.io.IOException Class removed: deprecated: public abstract org.apache.commons.httpclient.HttpUrlMethod extends java.lang.Object implements org.apache.commons.httpclient.HttpMethod Class removed: deprecated: public final org.apache.commons.httpclient.NTLM extends java.lang.Object Class removed: deprecated: public org.apache.commons.httpclient.RequestOutputStream extends java.io.OutputStream Class removed: deprecated: public org.apache.commons.httpclient.ResponseInputStream extends java.io.InputStream Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlDeleteMethod extends org.apache.commons.httpclient.methods.DeleteMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlGetMethod extends org.apache.commons.httpclient.methods.GetMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlHeadMethod extends org.apache.commons.httpclient.methods.HeadMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlOptionsMethod extends org.apache.commons.httpclient.methods.OptionsMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlPostMethod extends org.apache.commons.httpclient.methods.PostMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public org.apache.commons.httpclient.methods.UrlPutMethod extends org.apache.commons.httpclient.methods.PutMethod implements org.apache.commons.httpclient.HttpUrlMethod Class removed: deprecated: public final org.apache.commons.httpclient.util.Base64 extends java.lang.Object Class added: public org.apache.commons.httpclient.CircularRedirectException extends org.apache.commons.httpclient.RedirectException Class added: public org.apache.commons.httpclient.ConnectTimeoutException extends java.io.InterruptedIOException Class added: public org.apache.commons.httpclient.ConnectionPoolTimeoutException extends org.apache.commons.httpclient.ConnectTimeoutException Class added: public org.apache.commons.httpclient.DefaultHttpMethodRetryHandler extends java.lang.Object implements org.apache.commons.httpclient.HttpMethodRetryHandler Class added: public org.apache.commons.httpclient.HttpClientError extends java.lang.Error Class added: public org.apache.commons.httpclient.HttpHost extends java.lang.Object implements java.lang.Cloneable Class added: public abstract org.apache.commons.httpclient.HttpMethodRetryHandler extends java.lang.Object Class added: public org.apache.commons.httpclient.HttpVersion extends java.lang.Object implements java.lang.Comparable Class added: public org.apache.commons.httpclient.NoHttpResponseException extends java.io.IOException Class added: public org.apache.commons.httpclient.ProtocolException extends org.apache.commons.httpclient.HttpException Class added: public org.apache.commons.httpclient.ProxyClient extends java.lang.Object Class added: public org.apache.commons.httpclient.ProxyClient.ConnectResponse extends java.lang.Object Class added: public org.apache.commons.httpclient.ProxyHost extends org.apache.commons.httpclient.HttpHost Class added: public org.apache.commons.httpclient.RedirectException extends org.apache.commons.httpclient.ProtocolException Class added: public org.apache.commons.httpclient.auth.AuthChallengeException extends org.apache.commons.httpclient.auth.AuthenticationException Class added: public final org.apache.commons.httpclient.auth.AuthChallengeProcessor extends java.lang.Object Class added: public abstract org.apache.commons.httpclient.auth.AuthPolicy extends java.lang.Object Class added: public org.apache.commons.httpclient.auth.AuthScope extends java.lang.Object Class added: public org.apache.commons.httpclient.auth.AuthState extends java.lang.Object Class added: public org.apache.commons.httpclient.auth.CredentialsNotAvailableException extends org.apache.commons.httpclient.auth.AuthenticationException Class added: public abstract org.apache.commons.httpclient.auth.CredentialsProvider extends java.lang.Object Class added: public org.apache.commons.httpclient.auth.InvalidCredentialsException extends org.apache.commons.httpclient.auth.AuthenticationException Class added: public org.apache.commons.httpclient.cookie.IgnoreCookiesSpec extends java.lang.Object implements org.apache.commons.httpclient.cookie.CookieSpec Class added: public org.apache.commons.httpclient.methods.ByteArrayRequestEntity extends java.lang.Object implements org.apache.commons.httpclient.methods.RequestEntity Class added: public org.apache.commons.httpclient.methods.InputStreamRequestEntity extends java.lang.Object implements org.apache.commons.httpclient.methods.RequestEntity Class added: public abstract org.apache.commons.httpclient.methods.RequestEntity extends java.lang.Object Class added: public org.apache.commons.httpclient.methods.StringRequestEntity extends java.lang.Object implements org.apache.commons.httpclient.methods.RequestEntity Class added: public org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity extends java.lang.Object implements org.apache.commons.httpclient.methods.RequestEntity Class added: public org.apache.commons.httpclient.params.DefaultHttpParams extends java.lang.Object implements org.apache.commons.httpclient.params.HttpParams, java.io.Serializable, java.lang.Cloneable Class added: public org.apache.commons.httpclient.params.DefaultHttpParamsFactory extends java.lang.Object implements org.apache.commons.httpclient.params.HttpParamsFactory Class added: public org.apache.commons.httpclient.params.HostParams extends org.apache.commons.httpclient.params.DefaultHttpParams Class added: public org.apache.commons.httpclient.params.HttpClientParams extends org.apache.commons.httpclient.params.HttpMethodParams Class added: public org.apache.commons.httpclient.params.HttpConnectionManagerParams extends org.apache.commons.httpclient.params.HttpConnectionParams Class added: public org.apache.commons.httpclient.params.HttpConnectionParams extends org.apache.commons.httpclient.params.DefaultHttpParams Class added: public org.apache.commons.httpclient.params.HttpMethodParams extends org.apache.commons.httpclient.params.DefaultHttpParams Class added: public abstract org.apache.commons.httpclient.params.HttpParams extends java.lang.Object Class added: public abstract org.apache.commons.httpclient.params.HttpParamsFactory extends java.lang.Object Class added: public final org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory extends java.lang.Object Class added: public abstract org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory.SocketTask extends java.lang.Object implements java.lang.Runnable Class added: public final org.apache.commons.httpclient.protocol.ReflectionSocketFactory extends java.lang.Object Class added: public org.apache.commons.httpclient.util.DateUtil extends java.lang.Object Class added: public org.apache.commons.httpclient.util.ExceptionUtil extends java.lang.Object Class added: public org.apache.commons.httpclient.util.IdleConnectionHandler extends java.lang.Object Class added: public org.apache.commons.httpclient.util.IdleConnectionTimeoutThread extends java.lang.Thread Class added: public org.apache.commons.httpclient.util.LangUtils extends java.lang.Object Class added: public org.apache.commons.httpclient.util.ParameterFormatter extends java.lang.Object Class added: public org.apache.commons.httpclient.util.ParameterParser extends java.lang.Object Class changed: org.apache.commons.httpclient.ChunkedInputStream Methods added: public ChunkedInputStream(java.io.InputStream) throws java.io.IOException; Class changed: org.apache.commons.httpclient.ChunkedOutputStream Methods removed: public void print(java.lang.String) throws java.io.IOException; public void println() throws java.io.IOException; public void println(java.lang.String) throws java.io.IOException; Methods added: public ChunkedOutputStream(java.io.OutputStream, int) throws java.io.IOException; public void finish() throws java.io.IOException; protected void flushCache() throws java.io.IOException; protected void flushCacheWithAppend(byte[], int, int) throws java.io.IOException; public void write(byte[]) throws java.io.IOException; Method changed: old: public ChunkedOutputStream(java.io.OutputStream); new: public ChunkedOutputStream(java.io.OutputStream) throws java.io.IOException; Method changed: old: public void write(int) throws java.io.IOException, java.lang.IllegalStateException; new: public void write(int) throws java.io.IOException; Method changed: old: public void writeClosingChunk() throws java.io.IOException; new: protected void writeClosingChunk() throws java.io.IOException; Class changed: org.apache.commons.httpclient.ConnectMethod Methods removed: protected void addAuthorizationRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected void addContentLengthRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; Methods added: public ConnectMethod(); Method changed: old: public ConnectMethod(org.apache.commons.httpclient.HttpMethod); new: deprecated: public ConnectMethod(org.apache.commons.httpclient.HttpMethod); Class changed: org.apache.commons.httpclient.ContentLengthInputStream Methods added: public ContentLengthInputStream(java.io.InputStream, long); Method changed: old: public ContentLengthInputStream(java.io.InputStream, int); new: deprecated: public ContentLengthInputStream(java.io.InputStream, int); Class changed: org.apache.commons.httpclient.Cookie Methods removed: deprecated: public static org.apache.commons.httpclient.Header createCookieHeader(java.lang.String, int, java.lang.String, boolean, java.util.Date, org.apache.commons.httpclient.Cookie[]) throws java.lang.IllegalArgumentException; deprecated: public static org.apache.commons.httpclient.Header createCookieHeader(java.lang.String, int, java.lang.String, boolean, org.apache.commons.httpclient.Cookie[]) throws java.lang.IllegalArgumentException; deprecated: public static org.apache.commons.httpclient.Header createCookieHeader(java.lang.String, java.lang.String, boolean, org.apache.commons.httpclient.Cookie[]) throws java.lang.IllegalArgumentException; deprecated: public static org.apache.commons.httpclient.Header createCookieHeader(java.lang.String, java.lang.String, org.apache.commons.httpclient.Cookie[]); deprecated: public boolean matches(java.lang.String, int, java.lang.String, boolean); deprecated: public boolean matches(java.lang.String, int, java.lang.String, boolean, java.util.Date); deprecated: public static org.apache.commons.httpclient.Cookie[] parse(java.lang.String, int, java.lang.String, org.apache.commons.httpclient.Header) throws org.apache.commons.httpclient.HttpException, java.lang.IllegalArgumentException; deprecated: public static org.apache.commons.httpclient.Cookie[] parse(java.lang.String, int, java.lang.String, boolean, org.apache.commons.httpclient.Header) throws org.apache.commons.httpclient.HttpException; deprecated: public static org.apache.commons.httpclient.Cookie[] parse(java.lang.String, java.lang.String, org.apache.commons.httpclient.Header) throws org.apache.commons.httpclient.HttpException, java.lang.IllegalArgumentException; deprecated: public static org.apache.commons.httpclient.Cookie[] parse(java.lang.String, java.lang.String, boolean, org.apache.commons.httpclient.Header) throws org.apache.commons.httpclient.HttpException, java.lang.IllegalArgumentException; Class changed: org.apache.commons.httpclient.DefaultMethodRetryHandler Class descriptor changed: old: public org.apache.commons.httpclient.DefaultMethodRetryHandler extends java.lang.Object implements org.apache.commons.httpclient.MethodRetryHandler new: deprecated: public org.apache.commons.httpclient.DefaultMethodRetryHandler extends java.lang.Object implements org.apache.commons.httpclient.MethodRetryHandler Class changed: org.apache.commons.httpclient.Header Methods added: public Header(java.lang.String, java.lang.String, boolean); public org.apache.commons.httpclient.HeaderElement[] getElements(); public boolean isAutogenerated(); Method changed: old: public org.apache.commons.httpclient.HeaderElement[] getValues() throws org.apache.commons.httpclient.HttpException; new: deprecated: public org.apache.commons.httpclient.HeaderElement[] getValues() throws org.apache.commons.httpclient.HttpException; Class changed: org.apache.commons.httpclient.HeaderElement Methods removed: protected void setParameters(org.apache.commons.httpclient.NameValuePair[]); Methods added: public HeaderElement(char[]); public HeaderElement(char[], int, int); public final static org.apache.commons.httpclient.HeaderElement[] parseElements(java.lang.String); public final static org.apache.commons.httpclient.HeaderElement[] parseElements(char[]); Method changed: old: public final static org.apache.commons.httpclient.HeaderElement[] parse(java.lang.String) throws org.apache.commons.httpclient.HttpException; new: deprecated: public final static org.apache.commons.httpclient.HeaderElement[] parse(java.lang.String) throws org.apache.commons.httpclient.HttpException; Class changed: org.apache.commons.httpclient.HeaderGroup Methods added: public java.util.Iterator getIterator(); Class changed: org.apache.commons.httpclient.HostConfiguration Methods added: public org.apache.commons.httpclient.params.HostParams getParams(); public synchronized void setHost(org.apache.commons.httpclient.HttpHost); public void setParams(org.apache.commons.httpclient.params.HostParams); public synchronized void setProxyHost(org.apache.commons.httpclient.ProxyHost); Fields added: public final static org.apache.commons.httpclient.HostConfiguration ANY_HOST_CONFIGURATION; Method changed: old: public synchronized java.lang.String getVirtualHost(); new: deprecated: public synchronized java.lang.String getVirtualHost(); Method changed: old: public int hashCode(); new: public synchronized int hashCode(); Method changed: old: public synchronized boolean isHostSet(); new: deprecated: public synchronized boolean isHostSet(); Method changed: old: public synchronized boolean isProxySet(); new: deprecated: public synchronized boolean isProxySet(); Method changed: old: public synchronized void setHost(java.lang.String, java.lang.String, int, org.apache.commons.httpclient.protocol.Protocol); new: deprecated: public synchronized void setHost(java.lang.String, java.lang.String, int, org.apache.commons.httpclient.protocol.Protocol); Class changed: org.apache.commons.httpclient.HttpClient Methods removed: deprecated: public void endSession() throws java.io.IOException; deprecated: public void startSession(java.lang.String, int); deprecated: public void startSession(java.lang.String, int, java.lang.String, int); deprecated: public void startSession(java.lang.String, int, java.lang.String, int, boolean); deprecated: public void startSession(java.lang.String, int, org.apache.commons.httpclient.Credentials); deprecated: public void startSession(java.lang.String, int, org.apache.commons.httpclient.Credentials, boolean); deprecated: public void startSession(java.lang.String, int, boolean); deprecated: public void startSession(java.net.URL) throws java.lang.IllegalArgumentException; deprecated: public void startSession(java.net.URL, org.apache.commons.httpclient.Credentials) throws java.lang.IllegalArgumentException; deprecated: public void startSession(org.apache.commons.httpclient.URI) throws org.apache.commons.httpclient.URIException, java.lang.IllegalStateException; Methods added: public HttpClient(org.apache.commons.httpclient.params.HttpClientParams); public HttpClient(org.apache.commons.httpclient.params.HttpClientParams, org.apache.commons.httpclient.HttpConnectionManager); public org.apache.commons.httpclient.params.HttpClientParams getParams(); public void setParams(org.apache.commons.httpclient.params.HttpClientParams); Method changed: old: public synchronized boolean isStrictMode(); new: deprecated: public synchronized boolean isStrictMode(); Method changed: old: public synchronized void setConnectionTimeout(int); new: deprecated: public synchronized void setConnectionTimeout(int); Method changed: old: public synchronized void setHttpConnectionFactoryTimeout(long); new: deprecated: public synchronized void setHttpConnectionFactoryTimeout(long); Method changed: old: public synchronized void setStrictMode(boolean); new: deprecated: public synchronized void setStrictMode(boolean); Method changed: old: public synchronized void setTimeout(int); new: deprecated: public synchronized void setTimeout(int); Class changed: org.apache.commons.httpclient.HttpConnection Methods removed: deprecated: public HttpConnection(java.lang.String, int, java.lang.String, int, boolean); deprecated: public HttpConnection(java.lang.String, int, boolean); deprecated: public java.io.OutputStream getRequestOutputStream(boolean) throws java.io.IOException, java.lang.IllegalStateException; deprecated: public java.io.InputStream getResponseInputStream(org.apache.commons.httpclient.HttpMethod) throws java.io.IOException, java.lang.IllegalStateException; deprecated: public void setSecure(boolean) throws java.lang.IllegalStateException; Methods added: public HttpConnection(java.lang.String, int, java.lang.String, int, org.apache.commons.httpclient.protocol.Protocol); public boolean closeIfStale() throws java.io.IOException; public org.apache.commons.httpclient.params.HttpConnectionParams getParams(); protected java.net.Socket getSocket(); protected boolean isLocked(); public void print(java.lang.String, java.lang.String) throws java.io.IOException, java.lang.IllegalStateException; public void printLine(java.lang.String, java.lang.String) throws java.io.IOException, java.lang.IllegalStateException; public java.lang.String readLine(java.lang.String) throws java.io.IOException, java.lang.IllegalStateException; protected void setLocked(boolean); public void setParams(org.apache.commons.httpclient.params.HttpConnectionParams); public void setSocketTimeout(int) throws java.net.SocketException, java.lang.IllegalStateException; Method changed: old: public HttpConnection(java.lang.String, int, java.lang.String, java.lang.String, int, org.apache.commons.httpclient.protocol.Protocol); new: deprecated: public HttpConnection(java.lang.String, int, java.lang.String, java.lang.String, int, org.apache.commons.httpclient.protocol.Protocol); Method changed: old: public int getSoTimeout() throws java.net.SocketException; new: deprecated: public int getSoTimeout() throws java.net.SocketException; Method changed: old: public java.lang.String getVirtualHost(); new: deprecated: public java.lang.String getVirtualHost(); Method changed: old: protected boolean isStale(); new: protected boolean isStale() throws java.io.IOException; Method changed: old: public boolean isStaleCheckingEnabled(); new: deprecated: public boolean isStaleCheckingEnabled(); Method changed: old: public void print(java.lang.String) throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: deprecated: public void print(java.lang.String) throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void printLine() throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: public void printLine() throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void printLine(java.lang.String) throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: deprecated: public void printLine(java.lang.String) throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public java.lang.String readLine() throws java.io.IOException, java.lang.IllegalStateException; new: deprecated: public java.lang.String readLine() throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void setConnectionTimeout(int); new: deprecated: public void setConnectionTimeout(int); Method changed: old: public void setSendBufferSize(int) throws java.net.SocketException; new: deprecated: public void setSendBufferSize(int) throws java.net.SocketException; Method changed: old: public void setSoTimeout(int) throws java.net.SocketException, java.lang.IllegalStateException; new: deprecated: public void setSoTimeout(int) throws java.net.SocketException, java.lang.IllegalStateException; Method changed: old: public void setStaleCheckingEnabled(boolean); new: deprecated: public void setStaleCheckingEnabled(boolean); Method changed: old: public void setVirtualHost(java.lang.String) throws java.lang.IllegalStateException; new: deprecated: public void setVirtualHost(java.lang.String) throws java.lang.IllegalStateException; Method changed: old: public void shutdownOutput(); new: deprecated: public void shutdownOutput(); Method changed: old: public void write(byte[]) throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: public void write(byte[]) throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void write(byte[], int, int) throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: public void write(byte[], int, int) throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void writeLine() throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: public void writeLine() throws java.io.IOException, java.lang.IllegalStateException; Method changed: old: public void writeLine(byte[]) throws java.io.IOException, java.lang.IllegalStateException, org.apache.commons.httpclient.HttpRecoverableException; new: public void writeLine(byte[]) throws java.io.IOException, java.lang.IllegalStateException; Class changed: org.apache.commons.httpclient.HttpConnectionManager Methods added: public abstract void closeIdleConnections(long); public abstract org.apache.commons.httpclient.HttpConnection getConnectionWithTimeout(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.ConnectionPoolTimeoutException; public abstract org.apache.commons.httpclient.params.HttpConnectionManagerParams getParams(); public abstract void setParams(org.apache.commons.httpclient.params.HttpConnectionManagerParams); Method changed: old: public abstract org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.HttpException; new: deprecated: public abstract org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.HttpException; Class changed: org.apache.commons.httpclient.HttpConstants Class descriptor changed: old: public org.apache.commons.httpclient.HttpConstants extends java.lang.Object new: deprecated: public org.apache.commons.httpclient.HttpConstants extends java.lang.Object Class changed: org.apache.commons.httpclient.HttpException Methods added: public HttpException(java.lang.String, java.lang.Throwable); public java.lang.Throwable getCause(); deprecated: public java.lang.String getReason(); deprecated: public int getReasonCode(); public void printStackTrace(); public void printStackTrace(java.io.PrintStream); public void printStackTrace(java.io.PrintWriter); deprecated: public void setReason(java.lang.String); deprecated: public void setReasonCode(int); Class descriptor changed: old: public org.apache.commons.httpclient.HttpException extends org.apache.commons.httpclient.URIException new: public org.apache.commons.httpclient.HttpException extends java.io.IOException Class changed: org.apache.commons.httpclient.HttpMethod Methods added: public abstract void abort(); public abstract org.apache.commons.httpclient.auth.AuthState getHostAuthState(); public abstract org.apache.commons.httpclient.params.HttpMethodParams getParams(); public abstract org.apache.commons.httpclient.auth.AuthState getProxyAuthState(); public abstract org.apache.commons.httpclient.Header[] getRequestHeaders(java.lang.String); public abstract org.apache.commons.httpclient.Header[] getResponseHeaders(java.lang.String); public abstract boolean isRequestSent(); public abstract void removeRequestHeader(org.apache.commons.httpclient.Header); public abstract void setParams(org.apache.commons.httpclient.params.HttpMethodParams); public abstract void setURI(org.apache.commons.httpclient.URI) throws org.apache.commons.httpclient.URIException; Method changed: old: public abstract org.apache.commons.httpclient.HostConfiguration getHostConfiguration(); new: deprecated: public abstract org.apache.commons.httpclient.HostConfiguration getHostConfiguration(); Method changed: old: public abstract byte[] getResponseBody(); new: public abstract byte[] getResponseBody() throws java.io.IOException; Method changed: old: public abstract java.lang.String getResponseBodyAsString(); new: public abstract java.lang.String getResponseBodyAsString() throws java.io.IOException; Method changed: old: public abstract boolean isStrictMode(); new: deprecated: public abstract boolean isStrictMode(); Method changed: old: public abstract void setStrictMode(boolean); new: deprecated: public abstract void setStrictMode(boolean); Class changed: org.apache.commons.httpclient.HttpMethodBase Methods removed: protected void addAuthorizationRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected void addContentLengthRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected void addProxyAuthorizationRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected void fakeResponse(org.apache.commons.httpclient.StatusLine, org.apache.commons.httpclient.HeaderGroup, java.io.InputStream); protected int getRequestContentLength(); protected int getResponseContentLength(); Methods added: public void abort(); public org.apache.commons.httpclient.HttpVersion getEffectiveVersion(); public org.apache.commons.httpclient.auth.AuthState getHostAuthState(); public org.apache.commons.httpclient.params.HttpMethodParams getParams(); public org.apache.commons.httpclient.auth.AuthState getProxyAuthState(); public org.apache.commons.httpclient.Header[] getRequestHeaders(java.lang.String); public long getResponseContentLength(); public org.apache.commons.httpclient.Header[] getResponseHeaders(java.lang.String); public boolean isAborted(); public boolean isRequestSent(); public void removeRequestHeader(org.apache.commons.httpclient.Header); public void setParams(org.apache.commons.httpclient.params.HttpMethodParams); public void setURI(org.apache.commons.httpclient.URI) throws org.apache.commons.httpclient.URIException; Fields removed: protected final static org.apache.commons.httpclient.Header USER_AGENT; Method changed: old: public int execute(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws org.apache.commons.httpclient.HttpException, org.apache.commons.httpclient.HttpRecoverableException, java.io.IOException; new: public int execute(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws org.apache.commons.httpclient.HttpException, java.io.IOException; Method changed: old: public java.lang.String getAuthenticationRealm(); new: deprecated: public java.lang.String getAuthenticationRealm(); Method changed: old: protected static java.lang.String getContentCharSet(org.apache.commons.httpclient.Header); new: protected java.lang.String getContentCharSet(org.apache.commons.httpclient.Header); Method changed: old: public org.apache.commons.httpclient.HostConfiguration getHostConfiguration(); new: deprecated: public org.apache.commons.httpclient.HostConfiguration getHostConfiguration(); Method changed: old: public org.apache.commons.httpclient.MethodRetryHandler getMethodRetryHandler(); new: deprecated: public org.apache.commons.httpclient.MethodRetryHandler getMethodRetryHandler(); Method changed: old: public java.lang.String getProxyAuthenticationRealm(); new: deprecated: public java.lang.String getProxyAuthenticationRealm(); Method changed: old: public int getRecoverableExceptionCount(); new: deprecated: public int getRecoverableExceptionCount(); Method changed: old: public byte[] getResponseBody(); new: public byte[] getResponseBody() throws java.io.IOException; Method changed: old: public java.lang.String getResponseBodyAsString(); new: public java.lang.String getResponseBodyAsString() throws java.io.IOException; Method changed: old: public boolean isHttp11(); new: deprecated: public boolean isHttp11(); Method changed: old: public boolean isStrictMode(); new: deprecated: public boolean isStrictMode(); Method changed: old: protected void readResponse(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws org.apache.commons.httpclient.HttpException; new: protected void readResponse(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; Method changed: old: protected void readStatusLine(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpRecoverableException, org.apache.commons.httpclient.HttpException; new: protected void readStatusLine(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; Method changed: old: public void setHostConfiguration(org.apache.commons.httpclient.HostConfiguration); new: deprecated: public void setHostConfiguration(org.apache.commons.httpclient.HostConfiguration); Method changed: old: public void setHttp11(boolean); new: deprecated: public void setHttp11(boolean); Method changed: old: public void setMethodRetryHandler(org.apache.commons.httpclient.MethodRetryHandler); new: deprecated: public void setMethodRetryHandler(org.apache.commons.httpclient.MethodRetryHandler); Method changed: old: public void setStrictMode(boolean); new: deprecated: public void setStrictMode(boolean); Class changed: org.apache.commons.httpclient.HttpParser Methods added: public static org.apache.commons.httpclient.Header[] parseHeaders(java.io.InputStream, java.lang.String) throws java.io.IOException, org.apache.commons.httpclient.HttpException; public static java.lang.String readLine(java.io.InputStream, java.lang.String) throws java.io.IOException; Method changed: old: public static org.apache.commons.httpclient.Header[] parseHeaders(java.io.InputStream) throws java.io.IOException, org.apache.commons.httpclient.HttpException; new: deprecated: public static org.apache.commons.httpclient.Header[] parseHeaders(java.io.InputStream) throws java.io.IOException, org.apache.commons.httpclient.HttpException; Method changed: old: public static java.lang.String readLine(java.io.InputStream) throws java.io.IOException; new: deprecated: public static java.lang.String readLine(java.io.InputStream) throws java.io.IOException; Class changed: org.apache.commons.httpclient.HttpRecoverableException Class descriptor changed: old: public org.apache.commons.httpclient.HttpRecoverableException extends org.apache.commons.httpclient.HttpException new: deprecated: public org.apache.commons.httpclient.HttpRecoverableException extends org.apache.commons.httpclient.HttpException Class changed: org.apache.commons.httpclient.HttpState Methods removed: deprecated: public synchronized org.apache.commons.httpclient.Cookie[] getCookies(java.lang.String, int, java.lang.String, boolean, java.util.Date); deprecated: public synchronized org.apache.commons.httpclient.Credentials getCredentials(java.lang.String); deprecated: public synchronized org.apache.commons.httpclient.HttpConnectionManager getHttpConnectionManager(); deprecated: public synchronized org.apache.commons.httpclient.Credentials getProxyCredentials(java.lang.String); deprecated: public synchronized void setCredentials(java.lang.String, org.apache.commons.httpclient.Credentials); deprecated: public synchronized void setHttpConnectionManager(org.apache.commons.httpclient.HttpConnectionManager); deprecated: public synchronized void setProxyCredentials(java.lang.String, org.apache.commons.httpclient.Credentials); Methods added: public void clear(); public void clearCookies(); public void clearCredentials(); public void clearProxyCredentials(); public synchronized org.apache.commons.httpclient.Credentials getCredentials(org.apache.commons.httpclient.auth.AuthScope); public synchronized org.apache.commons.httpclient.Credentials getProxyCredentials(org.apache.commons.httpclient.auth.AuthScope); public synchronized void setCredentials(org.apache.commons.httpclient.auth.AuthScope, org.apache.commons.httpclient.Credentials); public synchronized void setProxyCredentials(org.apache.commons.httpclient.auth.AuthScope, org.apache.commons.httpclient.Credentials); Fields removed: public final static org.apache.commons.httpclient.auth.HttpAuthRealm DEFAULT_AUTH_REALM; Method changed: old: public int getCookiePolicy(); new: deprecated: public int getCookiePolicy(); Method changed: old: public synchronized org.apache.commons.httpclient.Credentials getCredentials(java.lang.String, java.lang.String); new: deprecated: public synchronized org.apache.commons.httpclient.Credentials getCredentials(java.lang.String, java.lang.String); Method changed: old: public synchronized org.apache.commons.httpclient.Credentials getProxyCredentials(java.lang.String, java.lang.String); new: deprecated: public synchronized org.apache.commons.httpclient.Credentials getProxyCredentials(java.lang.String, java.lang.String); Method changed: old: public boolean isAuthenticationPreemptive(); new: deprecated: public boolean isAuthenticationPreemptive(); Method changed: old: public void setAuthenticationPreemptive(boolean); new: deprecated: public void setAuthenticationPreemptive(boolean); Method changed: old: public void setCookiePolicy(int); new: deprecated: public void setCookiePolicy(int); Method changed: old: public synchronized void setCredentials(java.lang.String, java.lang.String, org.apache.commons.httpclient.Credentials); new: deprecated: public synchronized void setCredentials(java.lang.String, java.lang.String, org.apache.commons.httpclient.Credentials); Method changed: old: public synchronized void setProxyCredentials(java.lang.String, java.lang.String, org.apache.commons.httpclient.Credentials); new: deprecated: public synchronized void setProxyCredentials(java.lang.String, java.lang.String, org.apache.commons.httpclient.Credentials); Class changed: org.apache.commons.httpclient.MethodRetryHandler Class descriptor changed: old: public abstract org.apache.commons.httpclient.MethodRetryHandler extends java.lang.Object new: deprecated: public abstract org.apache.commons.httpclient.MethodRetryHandler extends java.lang.Object Class changed: org.apache.commons.httpclient.MultiThreadedHttpConnectionManager Methods added: public void closeIdleConnections(long); public void deleteClosedConnections(); public org.apache.commons.httpclient.HttpConnection getConnectionWithTimeout(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.ConnectionPoolTimeoutException; public int getConnectionsInPool(); public int getConnectionsInPool(org.apache.commons.httpclient.HostConfiguration); public org.apache.commons.httpclient.params.HttpConnectionManagerParams getParams(); public void setParams(org.apache.commons.httpclient.params.HttpConnectionManagerParams); Method changed: old: public org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.HttpException; new: deprecated: public org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long) throws org.apache.commons.httpclient.HttpException; Method changed: old: public int getConnectionsInUse(); new: deprecated: public int getConnectionsInUse(); Method changed: old: public int getConnectionsInUse(org.apache.commons.httpclient.HostConfiguration); new: deprecated: public int getConnectionsInUse(org.apache.commons.httpclient.HostConfiguration); Method changed: old: public int getMaxConnectionsPerHost(); new: deprecated: public int getMaxConnectionsPerHost(); Method changed: old: public int getMaxTotalConnections(); new: deprecated: public int getMaxTotalConnections(); Method changed: old: public boolean isConnectionStaleCheckingEnabled(); new: deprecated: public boolean isConnectionStaleCheckingEnabled(); Method changed: old: public void setConnectionStaleCheckingEnabled(boolean); new: deprecated: public void setConnectionStaleCheckingEnabled(boolean); Method changed: old: public void setMaxConnectionsPerHost(int); new: deprecated: public void setMaxConnectionsPerHost(int); Method changed: old: public void setMaxTotalConnections(int); new: deprecated: public void setMaxTotalConnections(int); Class changed: org.apache.commons.httpclient.NTCredentials Methods added: public boolean equals(java.lang.Object); public int hashCode(); Method changed: old: public NTCredentials(); new: deprecated: public NTCredentials(); Method changed: old: public void setDomain(java.lang.String); new: deprecated: public void setDomain(java.lang.String); Method changed: old: public void setHost(java.lang.String); new: deprecated: public void setHost(java.lang.String); Class changed: org.apache.commons.httpclient.SimpleHttpConnectionManager Methods added: public void closeIdleConnections(long); public org.apache.commons.httpclient.HttpConnection getConnectionWithTimeout(org.apache.commons.httpclient.HostConfiguration, long); public org.apache.commons.httpclient.params.HttpConnectionManagerParams getParams(); public void setParams(org.apache.commons.httpclient.params.HttpConnectionManagerParams); Fields added: protected org.apache.commons.httpclient.HttpConnection httpConnection; Method changed: old: public org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long); new: deprecated: public org.apache.commons.httpclient.HttpConnection getConnection(org.apache.commons.httpclient.HostConfiguration, long); Method changed: old: public boolean isConnectionStaleCheckingEnabled(); new: deprecated: public boolean isConnectionStaleCheckingEnabled(); Method changed: old: public void setConnectionStaleCheckingEnabled(boolean); new: deprecated: public void setConnectionStaleCheckingEnabled(boolean); Class changed: org.apache.commons.httpclient.URI Methods removed: deprecated: public URI(java.net.URL) throws org.apache.commons.httpclient.URIException; Methods added: public URI(java.lang.String, boolean) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; public URI(java.lang.String, boolean, java.lang.String) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; public URI(org.apache.commons.httpclient.URI, java.lang.String, boolean) throws org.apache.commons.httpclient.URIException; protected static java.lang.String decode(java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; Method changed: old: public URI(java.lang.String) throws org.apache.commons.httpclient.URIException; new: deprecated: public URI(java.lang.String) throws org.apache.commons.httpclient.URIException; Method changed: old: public URI(java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; new: deprecated: public URI(java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; Method changed: old: public URI(org.apache.commons.httpclient.URI, java.lang.String) throws org.apache.commons.httpclient.URIException; new: deprecated: public URI(org.apache.commons.httpclient.URI, java.lang.String) throws org.apache.commons.httpclient.URIException; Method changed: old: public URI(char[]) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; new: deprecated: public URI(char[]) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; Method changed: old: public URI(char[], java.lang.String) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; new: deprecated: public URI(char[], java.lang.String) throws org.apache.commons.httpclient.URIException, java.lang.NullPointerException; Class changed: org.apache.commons.httpclient.URIException Class descriptor changed: old: public org.apache.commons.httpclient.URIException extends java.io.IOException new: public org.apache.commons.httpclient.URIException extends org.apache.commons.httpclient.HttpException Method changed: old: public java.lang.String getReason(); new: deprecated: public java.lang.String getReason(); Method changed: old: public void setReason(java.lang.String); new: deprecated: public void setReason(java.lang.String); Method changed: old: public void setReasonCode(int); new: deprecated: public void setReasonCode(int); Class changed: org.apache.commons.httpclient.UsernamePasswordCredentials Methods added: public boolean equals(java.lang.Object); public int hashCode(); Method changed: old: public UsernamePasswordCredentials(); new: deprecated: public UsernamePasswordCredentials(); Method changed: old: public void setPassword(java.lang.String); new: deprecated: public void setPassword(java.lang.String); Method changed: old: public void setUserName(java.lang.String); new: deprecated: public void setUserName(java.lang.String); Class changed: org.apache.commons.httpclient.auth.AuthChallengeParser Methods added: public static java.util.Map parseChallenges(org.apache.commons.httpclient.Header[]) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class changed: org.apache.commons.httpclient.auth.AuthScheme Methods added: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract boolean isComplete(); public abstract boolean isConnectionBased(); public abstract void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public abstract java.lang.String getID(); new: deprecated: public abstract java.lang.String getID(); Class changed: org.apache.commons.httpclient.auth.AuthSchemeBase Methods added: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract boolean isComplete(); public abstract boolean isConnectionBased(); public abstract void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class descriptor changed: old: public abstract org.apache.commons.httpclient.auth.AuthSchemeBase extends java.lang.Object implements org.apache.commons.httpclient.auth.AuthScheme new: deprecated: public abstract org.apache.commons.httpclient.auth.AuthSchemeBase extends java.lang.Object implements org.apache.commons.httpclient.auth.AuthScheme Method changed: old: public AuthSchemeBase(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; new: deprecated: public AuthSchemeBase(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public abstract java.lang.String getID(); new: deprecated: public abstract java.lang.String getID(); Class changed: org.apache.commons.httpclient.auth.AuthenticationException Methods added: public AuthenticationException(java.lang.String, java.lang.Throwable); Class descriptor changed: old: public org.apache.commons.httpclient.auth.AuthenticationException extends org.apache.commons.httpclient.HttpException new: public org.apache.commons.httpclient.auth.AuthenticationException extends org.apache.commons.httpclient.ProtocolException Class changed: org.apache.commons.httpclient.auth.BasicScheme Methods added: public BasicScheme(); public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public static java.lang.String authenticate(org.apache.commons.httpclient.UsernamePasswordCredentials, java.lang.String); public boolean isComplete(); public boolean isConnectionBased(); public void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public BasicScheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; new: deprecated: public BasicScheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static java.lang.String authenticate(org.apache.commons.httpclient.UsernamePasswordCredentials); new: deprecated: public static java.lang.String authenticate(org.apache.commons.httpclient.UsernamePasswordCredentials); Class changed: org.apache.commons.httpclient.auth.DigestScheme Methods removed: public static java.lang.String authenticate(org.apache.commons.httpclient.UsernamePasswordCredentials, java.util.Map) throws org.apache.commons.httpclient.auth.AuthenticationException; public static java.lang.String createDigest(java.lang.String, java.lang.String, java.util.Map) throws org.apache.commons.httpclient.auth.AuthenticationException; public static java.lang.String createDigestHeader(java.lang.String, java.util.Map, java.lang.String); Methods added: public DigestScheme(); public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public boolean isComplete(); public boolean isConnectionBased(); public void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public DigestScheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; new: deprecated: public DigestScheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static java.lang.String createCnonce() throws org.apache.commons.httpclient.auth.AuthenticationException; new: public static java.lang.String createCnonce(); Method changed: old: public java.lang.String getID(); new: deprecated: public java.lang.String getID(); Class changed: org.apache.commons.httpclient.auth.HttpAuthRealm Methods removed: public boolean equals(java.lang.Object); public int hashCode(); public java.lang.String toString(); Class descriptor changed: old: public org.apache.commons.httpclient.auth.HttpAuthRealm extends java.lang.Object new: deprecated: public org.apache.commons.httpclient.auth.HttpAuthRealm extends org.apache.commons.httpclient.auth.AuthScope Class changed: org.apache.commons.httpclient.auth.HttpAuthenticator Class descriptor changed: old: public final org.apache.commons.httpclient.auth.HttpAuthenticator extends java.lang.Object new: deprecated: public final org.apache.commons.httpclient.auth.HttpAuthenticator extends java.lang.Object Method changed: old: public static boolean authenticate(org.apache.commons.httpclient.auth.AuthScheme, org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public static boolean authenticate(org.apache.commons.httpclient.auth.AuthScheme, org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static boolean authenticateDefault(org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public static boolean authenticateDefault(org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static boolean authenticateProxy(org.apache.commons.httpclient.auth.AuthScheme, org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public static boolean authenticateProxy(org.apache.commons.httpclient.auth.AuthScheme, org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static boolean authenticateProxyDefault(org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public static boolean authenticateProxyDefault(org.apache.commons.httpclient.HttpMethod, org.apache.commons.httpclient.HttpConnection, org.apache.commons.httpclient.HttpState) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static org.apache.commons.httpclient.auth.AuthScheme selectAuthScheme(org.apache.commons.httpclient.Header[]) throws org.apache.commons.httpclient.auth.MalformedChallengeException; new: deprecated: public static org.apache.commons.httpclient.auth.AuthScheme selectAuthScheme(org.apache.commons.httpclient.Header[]) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class changed: org.apache.commons.httpclient.auth.MalformedChallengeException Methods added: public MalformedChallengeException(java.lang.String, java.lang.Throwable); Class descriptor changed: old: public org.apache.commons.httpclient.auth.MalformedChallengeException extends org.apache.commons.httpclient.HttpException new: public org.apache.commons.httpclient.auth.MalformedChallengeException extends org.apache.commons.httpclient.ProtocolException Class changed: org.apache.commons.httpclient.auth.NTLMScheme Methods added: public NTLMScheme(); public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; deprecated: public static java.lang.String authenticate(org.apache.commons.httpclient.NTCredentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; public boolean isComplete(); public boolean isConnectionBased(); public void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class descriptor changed: old: public org.apache.commons.httpclient.auth.NTLMScheme extends org.apache.commons.httpclient.auth.AuthSchemeBase new: public org.apache.commons.httpclient.auth.NTLMScheme extends java.lang.Object implements org.apache.commons.httpclient.auth.AuthScheme Method changed: old: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public static java.lang.String authenticate(org.apache.commons.httpclient.NTCredentials, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; new: deprecated: public static java.lang.String authenticate(org.apache.commons.httpclient.NTCredentials, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; Method changed: old: public java.lang.String getID(); new: deprecated: public java.lang.String getID(); Class changed: org.apache.commons.httpclient.auth.RFC2617Scheme Methods added: public RFC2617Scheme(); deprecated: public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract java.lang.String authenticate(org.apache.commons.httpclient.Credentials, org.apache.commons.httpclient.HttpMethod) throws org.apache.commons.httpclient.auth.AuthenticationException; public abstract java.lang.String getSchemeName(); public abstract boolean isComplete(); public abstract boolean isConnectionBased(); public void processChallenge(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Class descriptor changed: old: public abstract org.apache.commons.httpclient.auth.RFC2617Scheme extends org.apache.commons.httpclient.auth.AuthSchemeBase new: public abstract org.apache.commons.httpclient.auth.RFC2617Scheme extends java.lang.Object implements org.apache.commons.httpclient.auth.AuthScheme Method changed: old: public RFC2617Scheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; new: deprecated: public RFC2617Scheme(java.lang.String) throws org.apache.commons.httpclient.auth.MalformedChallengeException; Method changed: old: public java.lang.String getID(); new: deprecated: public java.lang.String getID(); Class changed: org.apache.commons.httpclient.cookie.CookiePolicy Methods added: public static org.apache.commons.httpclient.cookie.CookieSpec getCookieSpec(java.lang.String) throws java.lang.IllegalStateException; public static void registerCookieSpec(java.lang.String, java.lang.Class); public static void unregisterCookieSpec(java.lang.String); Fields added: public final static java.lang.String BROWSER_COMPATIBILITY = compatibility; public final static java.lang.String DEFAULT = default; public final static java.lang.String IGNORE_COOKIES = ignoreCookies; public final static java.lang.String NETSCAPE = netscape; public final static java.lang.String RFC_2109 = rfc2109; Method changed: old: public static org.apache.commons.httpclient.cookie.CookieSpec getCompatibilitySpec(); new: deprecated: public static org.apache.commons.httpclient.cookie.CookieSpec getCompatibilitySpec(); Method changed: old: public static int getDefaultPolicy(); new: deprecated: public static int getDefaultPolicy(); Method changed: old: public static org.apache.commons.httpclient.cookie.CookieSpec getSpecByPolicy(int); new: deprecated: public static org.apache.commons.httpclient.cookie.CookieSpec getSpecByPolicy(int); Method changed: old: public static org.apache.commons.httpclient.cookie.CookieSpec getSpecByVersion(int); new: deprecated: public static org.apache.commons.httpclient.cookie.CookieSpec getSpecByVersion(int); Method changed: old: public static void setDefaultPolicy(int); new: deprecated: public static void setDefaultPolicy(int); Field changed: old: public final static int COMPATIBILITY = 0; new: deprecated: public final static int COMPATIBILITY = 0; Field changed: old: public final static int NETSCAPE_DRAFT = 1; new: deprecated: public final static int NETSCAPE_DRAFT = 1; Field changed: old: public final static int RFC2109 = 2; new: deprecated: public final static int RFC2109 = 2; Class changed: org.apache.commons.httpclient.cookie.CookieSpec Methods added: public abstract boolean domainMatch(java.lang.String, java.lang.String); public abstract java.util.Collection getValidDateFormats(); public abstract boolean pathMatch(java.lang.String, java.lang.String); public abstract void setValidDateFormats(java.util.Collection); Class changed: org.apache.commons.httpclient.cookie.CookieSpecBase Methods added: public boolean domainMatch(java.lang.String, java.lang.String); public java.util.Collection getValidDateFormats(); public boolean pathMatch(java.lang.String, java.lang.String); public void setValidDateFormats(java.util.Collection); Class changed: org.apache.commons.httpclient.cookie.MalformedCookieException Methods added: public MalformedCookieException(java.lang.String, java.lang.Throwable); Class descriptor changed: old: public org.apache.commons.httpclient.cookie.MalformedCookieException extends org.apache.commons.httpclient.HttpException new: public org.apache.commons.httpclient.cookie.MalformedCookieException extends org.apache.commons.httpclient.ProtocolException Class changed: org.apache.commons.httpclient.cookie.NetscapeDraftSpec Methods added: public boolean domainMatch(java.lang.String, java.lang.String); public org.apache.commons.httpclient.Cookie[] parse(java.lang.String, int, java.lang.String, boolean, java.lang.String) throws org.apache.commons.httpclient.cookie.MalformedCookieException; Class changed: org.apache.commons.httpclient.cookie.RFC2109Spec Methods added: public boolean domainMatch(java.lang.String, java.lang.String); Class changed: org.apache.commons.httpclient.methods.EntityEnclosingMethod Methods removed: deprecated: public EntityEnclosingMethod(java.lang.String, java.lang.String); deprecated: public EntityEnclosingMethod(java.lang.String, java.lang.String, java.lang.String); public java.io.InputStream getRequestBody(); public java.lang.String getRequestBodyAsString() throws java.io.IOException; protected int getRequestContentLength(); Methods added: protected void addRequestHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected org.apache.commons.httpclient.methods.RequestEntity generateRequestEntity(); public java.lang.String getRequestCharSet(); protected long getRequestContentLength(); public org.apache.commons.httpclient.methods.RequestEntity getRequestEntity(); public void setContentChunked(boolean); deprecated: public void setRequestContentLength(long); public void setRequestEntity(org.apache.commons.httpclient.methods.RequestEntity); Method changed: old: public void setRequestBody(java.io.InputStream); new: deprecated: public void setRequestBody(java.io.InputStream); Method changed: old: public void setRequestBody(java.lang.String); new: deprecated: public void setRequestBody(java.lang.String); Method changed: old: public void setRequestContentLength(int); new: deprecated: public void setRequestContentLength(int); Field changed: old: public final static int CONTENT_LENGTH_AUTO = -2; new: deprecated: public final static long CONTENT_LENGTH_AUTO = -2; Field changed: old: public final static int CONTENT_LENGTH_CHUNKED = -1; new: deprecated: public final static long CONTENT_LENGTH_CHUNKED = -1; Class changed: org.apache.commons.httpclient.methods.ExpectContinueMethod Methods removed: deprecated: public ExpectContinueMethod(java.lang.String, java.lang.String); deprecated: public ExpectContinueMethod(java.lang.String, java.lang.String, java.lang.String); Class descriptor changed: old: public abstract org.apache.commons.httpclient.methods.ExpectContinueMethod extends org.apache.commons.httpclient.methods.GetMethod new: public abstract org.apache.commons.httpclient.methods.ExpectContinueMethod extends org.apache.commons.httpclient.HttpMethodBase Method changed: old: public boolean getUseExpectHeader(); new: deprecated: public boolean getUseExpectHeader(); Method changed: old: public void setUseExpectHeader(boolean); new: deprecated: public void setUseExpectHeader(boolean); Class changed: org.apache.commons.httpclient.methods.GetMethod Methods removed: deprecated: public GetMethod(java.lang.String, java.io.File); deprecated: public GetMethod(java.lang.String, java.lang.String); deprecated: public GetMethod(java.lang.String, java.lang.String, java.lang.String); deprecated: public java.io.File getFileData(); deprecated: public java.lang.String getTempDir(); deprecated: public java.lang.String getTempFile(); deprecated: public boolean getUseDisk(); protected void readResponseBody(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; deprecated: public void setFileData(java.io.File); deprecated: public void setTempDir(java.lang.String); deprecated: public void setTempFile(java.lang.String); deprecated: public void setUseDisk(boolean); Class changed: org.apache.commons.httpclient.methods.HeadMethod Method changed: old: public int getBodyCheckTimeout(); new: deprecated: public int getBodyCheckTimeout(); Method changed: old: protected void readResponseBody(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException; new: protected void readResponseBody(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws org.apache.commons.httpclient.HttpException, java.io.IOException; Method changed: old: public void setBodyCheckTimeout(int); new: deprecated: public void setBodyCheckTimeout(int); Class changed: org.apache.commons.httpclient.methods.MultipartPostMethod Methods removed: public MultipartPostMethod(java.lang.String, java.lang.String); public MultipartPostMethod(java.lang.String, java.lang.String, java.lang.String); protected int getRequestContentLength(); Methods added: protected void addContentLengthRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected void addContentTypeRequestHeader(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected long getRequestContentLength() throws java.io.IOException; Class descriptor changed: old: public org.apache.commons.httpclient.methods.MultipartPostMethod extends org.apache.commons.httpclient.methods.ExpectContinueMethod new: deprecated: public org.apache.commons.httpclient.methods.MultipartPostMethod extends org.apache.commons.httpclient.methods.ExpectContinueMethod Class changed: org.apache.commons.httpclient.methods.OptionsMethod Method changed: old: public boolean needContentLength(); new: deprecated: public boolean needContentLength(); Class changed: org.apache.commons.httpclient.methods.PostMethod Methods removed: deprecated: public PostMethod(java.lang.String, java.lang.String); deprecated: public PostMethod(java.lang.String, java.lang.String, java.lang.String); protected void addRequestHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection) throws java.io.IOException, org.apache.commons.httpclient.HttpException; protected byte[] generateRequestBody(); Methods added: protected org.apache.commons.httpclient.methods.RequestEntity generateRequestEntity(); Class changed: org.apache.commons.httpclient.methods.TraceMethod Method changed: old: public void recycle(); new: deprecated: public void recycle(); Class changed: org.apache.commons.httpclient.methods.multipart.FilePart Fields removed: protected final static byte[] FILE_NAME_BYTES; Class changed: org.apache.commons.httpclient.methods.multipart.Part Methods added: public static long getLengthOfParts(org.apache.commons.httpclient.methods.multipart.Part[], byte[]) throws java.io.IOException; protected byte[] getPartBoundary(); public boolean isRepeatable(); public static void sendParts(java.io.OutputStream, org.apache.commons.httpclient.methods.multipart.Part[], byte[]) throws java.io.IOException; Method changed: old: public static java.lang.String getBoundary(); new: deprecated: public static java.lang.String getBoundary(); Field changed: old: protected final static java.lang.String BOUNDARY = ----------------314159265358979323846; new: deprecated: protected final static java.lang.String BOUNDARY = ----------------314159265358979323846; Field changed: old: protected final static byte[] BOUNDARY_BYTES; new: deprecated: protected final static byte[] BOUNDARY_BYTES; Class changed: org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory Methods added: public java.net.Socket createSocket(java.lang.String, int, java.net.InetAddress, int, org.apache.commons.httpclient.params.HttpConnectionParams) throws java.io.IOException, java.net.UnknownHostException, org.apache.commons.httpclient.ConnectTimeoutException; Class changed: org.apache.commons.httpclient.protocol.Protocol Method changed: old: public Protocol(java.lang.String, org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory, int); new: deprecated: public Protocol(java.lang.String, org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory, int); Class changed: org.apache.commons.httpclient.protocol.ProtocolSocketFactory Methods added: public abstract java.net.Socket createSocket(java.lang.String, int, java.net.InetAddress, int, org.apache.commons.httpclient.params.HttpConnectionParams) throws java.io.IOException, java.net.UnknownHostException, org.apache.commons.httpclient.ConnectTimeoutException; Class changed: org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory Methods added: public java.net.Socket createSocket(java.lang.String, int, java.net.InetAddress, int, org.apache.commons.httpclient.params.HttpConnectionParams) throws java.io.IOException, java.net.UnknownHostException, org.apache.commons.httpclient.ConnectTimeoutException; Class changed: org.apache.commons.httpclient.util.DateParser Methods added: public static java.util.Date parseDate(java.lang.String, java.util.Collection) throws org.apache.commons.httpclient.util.DateParseException; Class descriptor changed: old: public org.apache.commons.httpclient.util.DateParser extends java.lang.Object new: deprecated: public org.apache.commons.httpclient.util.DateParser extends java.lang.Object Class changed: org.apache.commons.httpclient.util.EncodingUtil Methods added: public static byte[] getAsciiBytes(java.lang.String); public static java.lang.String getAsciiString(byte[]); public static java.lang.String getAsciiString(byte[], int, int); public static byte[] getBytes(java.lang.String, java.lang.String); public static java.lang.String getString(byte[], int, int, java.lang.String); public static java.lang.String getString(byte[], java.lang.String); Class changed: org.apache.commons.httpclient.util.URIUtil Methods removed: deprecated: public static java.lang.String toDocumentCharset(java.lang.String) throws org.apache.commons.httpclient.URIException; deprecated: public static java.lang.String toDocumentCharset(java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; deprecated: public static java.lang.String toProtocolCharset(java.lang.String) throws org.apache.commons.httpclient.URIException; deprecated: public static java.lang.String toProtocolCharset(java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; deprecated: public static java.lang.String toUsingCharset(java.lang.String, java.lang.String, java.lang.String) throws org.apache.commons.httpclient.URIException; Class changed: org.apache.commons.httpclient.util.URIUtil.Coder Class descriptor changed: old: public org.apache.commons.httpclient.util.URIUtil.Coder extends org.apache.commons.httpclient.URI new: deprecated: public org.apache.commons.httpclient.util.URIUtil.Coder extends org.apache.commons.httpclient.URI Method changed: old: public static java.lang.String decode(char[], java.lang.String) throws org.apache.commons.httpclient.URIException; new: deprecated: public static java.lang.String decode(char[], java.lang.String) throws org.apache.commons.httpclient.URIException; Method changed: old: public static char[] encode(java.lang.String, java.util.BitSet, java.lang.String) throws org.apache.commons.httpclient.URIException; new: deprecated: public static char[] encode(java.lang.String, java.util.BitSet, java.lang.String) throws org.apache.commons.httpclient.URIException; API diff generated by JarDiff http://www.osjava.org/jardiff/ ------------------- Changes since Release Candidate 4: * 37526 - Fixed incorrect processing of HTTP parameters with an empty name Contributed by Oleg Kalnichevski * 37256 - Fixed bug causing MultipartRequestEntity to miscalculate the total content length if any of the parts returns a negative content length value Contributed by Loïc Péron * 37197 - Preemptive auth flag no longer disregarded when tunneling SSL connections via a proxy Contributed by wynand * 37154 - UsernamePasswordCredentials.equals(null) no longer causes NPE Contributed by Oleg Kalnichevski * 37129 - HttpConnection changed to use a protocol socket factory registered for 'http' protocol instead of DefaultProtocolSocketFactory when connecting to a proxy to establish a secure tunnel Contributed by Oleg Kalnichevski Release 3.0 Release Candidate 4 ------------------- Changes since Release Candidate 3: * 36882 - Max connections per host setting did not work Contributed by Oleg Kalnichevski * 36791 - Fixed HttpConnection#isOpen flag concurrency problem Contributed by Jean-Marie White * 36339 - Request is no longer retried if preemptive authentication fails and Basic is the only supported authentication scheme advertised by the target server Contributed by Oleg Kalnichevski * 36372 - nonce-count in digest auth should not be quoted Contributed by Ortwin Glueck * 36369 - Custom Proxy-Connection header no longer gets overwritten Contributed by Oleg Kalnichevski * 36595 - Do not attempt to retry aborted methods Contributed by Oleg Kalnichevski * 36140 - ParameterParser changed to correctly differentiate between empty and null (no value) parameters Contributed by Oleg Kalnichevski * 35085 - HTTP 204 "NO CONTENT" response no longer results in dropped connection. Contributed by Ian Bray * 35944 - Connection always gets released back to the pool even if an unchecked exception is thrown in HttpMethod#releaseConnection method. Contributed by Oleg Kalnichevski * 35642 - Do not retry if host is unreachable. This ensures a connection timeout will be obeyed. Contributed by Ortwin Glueck * 35815 - SimpleHttpConnectionManager now logs warnings when it detects it is being used incorrectly. Contributed by Michael Becke Release 3.0 Release Candidate 3 ------------------- Changes since Release Candidate 2: * 35365 - Added #hashCode and #equals methods for Credentials implementations Contributed by Eric Johnson * 35322 - Stale connection check now correctly works with IBM JSSE/JRE 1.4.x Contributed by Oleg Kalnichevski * 35225 - Fixed a major problem with the browser compatibility policy leaking cookies to 3rd party domains (.mydomain.com -> .notmydomain.com) Contributed by Oleg Kalnichevski * 35328 - DateUtil#formatDate changed to US locale instead of system default Contributed by Yannick * 34960 - DigestScheme changed to take into account charset attribute when available (Known to be used by Microsoft implementation of the Digest auth scheme) Contributed by Oleg Kalnichevski * 35148 - HttpClient now correctly handles relative URIs beginning with a colon. Contributed by Gordon Mohr * 34961 - HttpClient now correctly handles escaped characters in HTTP header elements Contributed by Oleg Kalnichevski * 34780 - HttpClient now always overrides the host of HostConfiguration if an absolute request URI is given Contributed by Oleg Kalnichevski * 34740 - Connection with the proxy is not reopened if an proxy auth failure occurs while SSL tunnel is being established Contributed by Oleg Kalnichevski * 34721 - Virtual host setting is now correctly applied when parsing and matching cookies Contributed by Oleg Kalnichevski * 34583 - DateUtil.formatDate() changed to use GMT instead of the default timezone Contributed by Fred Bierhaus * 34459 - Always use the chunk encoding when request content length cannot be determined (is negative) Contributed by Oleg Kalnichevski * 34427 - Fixed the bug causing an IllegalStateException in AuthState triggered by the combination of preemptive proxy authentication and a cross-site redirect Contributed by Oleg Kalnichevski Release 3.0 Release Candidate 2 ------------------- Changes since Release Candidate 1: * 34255 - Preemptive authentication no longer causes NTLM auth scheme to fail Contributed by Michael Becke * 33720 - Fixed the problem with HttpMethod#getURI applying URL escaped encoding to already encoded URIs Contributed by Oleg Kalnichevski * 34262 - Fixed broken handling of responses that may not include an entity body (status code 204, 304) Contributed by Oleg Kalnichevski * ----- - Fixed broken InputStreamRequestEntity#isRepeatable method Contributed by Matthew-J Watson * 33677 - Fixed the bug preventing the HTTP retry handler from handling ConnectionExceptions Contributed by Oleg Kalnichevski * 33988 - All classes overriding Object#hashCode & Object#equals methods have been reviewed regarding their hashCode/equals contract compliance Contributed by Oleg Kalnichevski * 33947 - Exception in HttpConnection because of unchecked buffer size Contributed by Ortwin Glueck * 33856 - Fixed the problem with the credential-charset parameter not having an effect on the encoding of the NTLM credentials Contributed by Oleg Kalnichevski * 33541 - Fixed the problem with host level parameters having no effect on HTTP CONNECT methods Contributed by Oleg Kalnichevski * 33468 - HttpClient no longer flushes the request line and request headers prior to writing the request body if the 'expect: continue' handshake is not used Contributed by Peter Tolmachov Release 3.0 Release Candidate 1 ------------------- Changes since Beta 1: * 32833 - Cookie with domain .mydomain.com were not sent to host mydomain.com in the browser compatibility mode Contributed by David D. Kilzer * 33021 - Fixed the bug causing the circular redirect if different query parameters are used in the redirect location. Contributed by Ilya Kharmatsky * 32955 - Fixed the bug effectively disabling the stale connection check Contributed by Oliver Koell * 32835 - The two digit year greater than 20 no longer causes the cookie expiry date to be interpreted as a date between 1920 and 1999 Contributed by Oleg Kalnichevski * 32607 - Fixed the problem with ReflectionSocketFactory ignoring the local address of HostConfiguration Contributed by Oleg Kalnichevski * 32409 - HttpState now has new methods for clearing all cookies and credentials. Contributed by Oleg Kalnichevski * 32558 - Fixed retry count bug in DefaultMethodRetryHandler Contributed by Oleg Kalnichevski * 32333 - Connection is now closed upon "Connection: close" request, if the server does not include an explicit connection directive in the response. Contributed by Oleg Kalnichevski * 32765 - Fixed NullPointerException in HostConfiguration.setHost(Sting) Contributed by Stuart Herring * 32742 - Fixed the problem with SO_TIMEOUT parameter having no effect on the method level. Contributed by Ilya Kharmatsky Release 3.0 Beta 1 ------------------- Changes since Alpha 2: * 31929 - Added support for formatting dates. Deprecated DateParser in favor of DateUtil. Contributed by Michael Becke * ----- - HostConfiguration.isHostSet() and Hostconfiguration.isProxySet() have been deprecated. * 31981 - Fixed the bug causing an infinite loop in HttpMethodDirector when using SSL + proxy + host auth + keep alive off Contributed by Oleg Kalnichevski * 31607 - Catch SocketTimeoutException not InterruptedIOException when running in JRE >=1.4 Contributed by Oleg Kalnichevski * 31471 - HostConfiguration refactored Contributed by Oleg Kalnichevski * ----- - ContentLengthInputStream no longer supports mark() & reset() methods. Old broken implementation removed. Contributed by Eric Johnson Release 3.0 Alpha 2 ------------------- Changes since Alpha 1: * 10793 - Configurable default headers Contributed by Oleg Kalnichevski * 30652 - Configurable SO_LINGER Contributed by Oleg Kalnichevski * 31163 - CookieSpec classes made stateful Contributed by Oleg Kalnichevski * 21329 - Added input buffering to improve performance Contributed by Bjarne Rasmussen * 29897 - Connection output buffer is set to a value not greater than 2k Contributed by Oleg Kalnichevski * 29636 - MultiThreadedHttpConnectionManager now support configuring the maximum number of connections on a per host basis. Contributed by Michael Becke * 29874 - Deprecated old HTTP method retry handler based on HttpRecoverableException and replaced it with a new one that acts upon plain IOExceptions Contributed by Oleg Kalnichevski * 29883 - Fixed handling of multi-byte characters in the StringRequestEntity class Contributed by Oleg Kalnichevski * 29383 - Added method to delete closed connections from the connection pool Contributed by Michael Becke * 29549 - Split wire log into header and body parts Contributed by Michael Becke * 29540 - Fixed credentials scope matching algorithm in HttpState#matchCredentials. Contributed by Oleg Kalnichevski * 29439 - Cleaner interface to define authentication scope, handle credentials in HttpState. Contributed by Oleg Kalnichevski * 29377 - Cookies with names containing blanks or starting with $ rejected by RFC2109 spec only. Contributed by Oleg Kalnichevski Release 3.0 Alpha 1 ------------------- Changes on the CVS trunk: * 29265 - HttpConnection.isOpen() no longer logs closed connections as stale. * 28645 - Moved/added content type handling to the RequestEntity. Contributed by Michael Becke , Oleg Kalnichevski * 20288 - Added ability to abort execution of HTTP methods Contributed by Oleg Kalnichevski * 24154 - Socket timeout can be specified at the connection manager, connection or method level Contributed by Oleg Kalnichevski * 16124 - HTTP protocol version can be specified at the client, host or method level Contributed by Oleg Kalnichevski * 28728 - HttpUrl now accepts unescaped passwords Contributed by Michael Becke * 28626 - Fixed ArrayIndexOutOfBoundsException in HttpStatus.getStatusText() Contributed by Oleg Kalnichevski * 26070 - Added support for streaming entities Contributed by Michael Becke * 28566 - CookieSpec interface extended to expose path & domain matching methods; browser compatibility domain matching algorithm modified to mimic the (mis-)behavior of common browsers Contributed by Oleg Kalnichevski * 25372 - Added support for closing idle connections Contributed by Michael Becke , Oleg Kalnichevski * 28322 - Redesign of connect timeout logic; Added support for JDK1.4 connect timeout through reflection Contributed by Oleg Kalnichevski * 28151 - Added stand-alone support for tunneled HTTP proxies via the ProxyClient Contributed by Michael Sample , Michael Becke * 21216 - Fixed the problem of redirect 302 to the same URL causing max redirects exception: circular redirect check added; the circular redirect check is on per default and in lenient mode, is off in strict mode Contributed by Oleg Kalnichevski * 27589 - Added MultiThreadedHttpConnectionManager shutdown() and shutdownAll() Contributed by Michael Becke * 25529 - Redesign of HTTP authentication framework Contributed by Oleg Kalnichevski * Better implementation of ChunkedOutputStream: writes are buffered to an internal buffer (2048 default size); chunks are guaranteed to be at least as large as the buffer size (except for the last chunk) Contributed by Mohammad Rezaei , Goldman, Sachs & Co * HttpMethod#getResponseBody & HttpMethod#getResponseBodyAsString changed to propagate IOException to the caller instead of logging and discarding it Contributed by Oleg Kalnichevski * 10794 - Added interactive authentication support; Authentication realm key is now comprised of host name, port, realm name and authentication type Contributed by Oleg Kalnichevski * 15297 - Added ability to perform alternate authentication Contributed by Oleg Kalnichevski * 16881 - HttpClient made dependent on Commons-codec to perform Base64 and URL encoding/decoding Contributed by Michael Becke , Oleg Kalnichevski * 24560 - Fixed the problem of HttpClient looping endlessly while trying to retrieve status line Contributed by Christian Kohlschuetter * 24671 - Added support for configuring charsets in credentials and HTTP headers Contributed by Michael Becke * Plug-in mechanism for authentication modules Contributed by Oleg Kalnichevski * Added infrastructure to create test cases that involve use of a proxy Contributed by Ortwin Glueck * UserNamePasswordCredentials & NTCredentials made immutable Contributed by Oleg Kalnichevski * 24869 - DigestScheme now only accepts a challenge if all fields required by RFC 2617 are present Contributed by Ortwin Glueck * New framework for server based tests Contributed by Christian Kohlschuetter , Ortwin Glueck * Socket input stream now wrapped with a wrapper class that re-throws certain type of generic IO exceptions as HttpClient specific exceptions. Improved handling of 'used' connections (known to have successfully completed an I/O operation). Contributed by Oleg Kalnichevski * 24012 - Added IgnoreCookiesSpec. Contributed by Michael Becke * 24018 - Cookie and Authorization headers can now be set manually. Contributed by Oleg Kalnichevski * 21151 - Cookie specification plug-in mechanism Contributed by Oleg Kalnichevski * Reworked DigestScheme: the qop Parameter is parsed correctly and not just ignored; missing qop is handled correctly Contributed by Ortwin Glueck * 10790 - Implemented granular non-standards configuration and tracking. Contributed by Oleg Kalnichevski , Michael Becke , Roland Weber , Ortwin Glueck , Adrian Sutton * 15435 - Implemented new preference architecture. Contributed by Oleg Kalnichevski , Michael Becke , Roland Weber , Ortwin Glueck , Adrian Sutton * Deprecated the use of system properties: 'httpclient.useragent', 'httpclient.authentication.preemptive'. * Refactored NameValuePair#equals method. Contributed by Ortwin Glueck * 16729 - Refactored retry/redirect/authentication logic. Contributed by Michael Becke * Added support for disabling HttpConnection.isStale() Contributed by Michael Becke * 10791 - Improved HTTP Version configuration and tracking. Contributed Oleg Kalnichevski , Laura Werner , Michael Becke * 21880 - Content-Length & Transfer-Encoding request headers formerly set by abstract HttpMethodBase class are handled by entity enclosing methods. Contributed by Oleg Kalnichevski * 17947 - HttpMethod#setURI method added. Contributed by Oleg Kalnichevski * 19618 - URI constructors refactored. Contributed by Oleg Kalnichevski * 11240 - Fixed the problem of cookies with ',' in the value string not parsed correctly in some cases Contributed by Oleg Kalnichevski * 21323 - Support for large(long) content added Contributed by Michael Becke * 19868 - Exception handling framework reworked. Contributed by Adrian Sutton , Laura Werner , Oleg Kalnichevski , Michael Becke * 21210 - Header parser completely rewritten. Improved handling of Netscape draft compatible cookies Contributed by Oleg Kalnichevski Release 2.0.2 ------------------- Changes since Release 2.0.1 * ContentLengthInputStream no longer supports mark() & reset() methods. * 21329 - Added input buffering to improve performance Release 2.0.1 ------------------- Changes since Release 2.0 * 30175 - Fixed StringIndexOutOfBoundsException in StatusLine * 29897 - Connection output buffer is set to a value not greater than 2k * 29549 - Split wire log into header and body parts * 29377 - Cookies with names containing blanks or starting with $ rejected by RFC2109 spec only. * 29265 - HttpConnection.isOpen() no longer logs closed connections as stale. * 28728 - HttpUrl now accepts unescaped passwords * 28626 - Fixed ArrayIndexOutOfBoundsException in HttpStatus.getStatusText() * 27589 - Added MultiThreadedHttpConnectionManager shutdown() and shutdownAll(). * HttpMethod#recycle() has been deprecated. Release 2.0 ------------------- Changes since Release Candidate 3: * 26500 - Socket timeout is now correctly set on open connections * 26328 - Fixed getScheme() and getPort() returning wrong defaults for HttpsURL * 26139 - Fixed possible connection leak caused by lack of equals() and hashCode() on protocol socket factories * 26688 - Fixed the problem with HttpURL creating wrong authority String when user info is changed Release 2.0 Release Candidate 3 ------------------- Changes since Release Candidate 2: * HTTP status line parser changed to be more robust when dealing with non-compliant HTTP responses (leading blanks before 'HTTP' signature). * Fixed NPE in HttpMethodBase#responseBodyConsumed(). * 24309 - Changed MultiThreadedHttpConnectionManager to move to a single connection GC thread. Fixed memory and thread leaks. * 24327 - Fixed a bug where HttpClient did not reset the 'force-close connection' flag, when an HTTP method was automatically retried (for instance, when automatically handling an authentication challenge). * 24352 - Fixed the bug causing basic authentication via NLTM Proxy to fail. * 25370 - Connections are now closed and released automatically when an unrecoverable exception occurs in HttpMethodBase.processRequest(). * 23866 - Fixed possible uncaught IllegalArgumentException in Cookie parsing. * 25264 - Added support for cookies with a domain attribute '.domain.com' issued by host 'domain.com' in the browser compatibility mode. Even though the cookie violates RFC 2109 it still gets accepted by mainstream browsers (tested with Mozilla Firebird and IE). * 24869 - Changed DigestScheme to only accept a challenge if all fields required by RFC 2617 are present. * 24671 - Added ISO-8859-1 support for digest authentication passwords, and basic authentication user names and passwords. * Javadoc enhancements. Release 2.0 Release Candidate 2 ------------------- Changes since Release Candidate 1: * Javadoc enhancements. * 23284 - Fixed bug with URI.isIPv4address(). * 22969 - PostMethod#setParameter fixed to correctly overwrite existing parameters. * 22970 - Fixed bug with PostMethod#removeParameter return value. * Improved compliance to RFC 2617 * Added support for digest auth MD5-sess. * 22655 - Added support for stale digest nonce values. * 22968 - HttpConnection.isResponseAvailable() made a little more robust, particularly when used by HeadMethod. * 22941 - Switched the order in which socket streams are closed: output stream closed first, followed by input stream. * Added debugging for connection reclaiming. * Removed JCE initialization code specific to the Sun's implementation. * Fixed problem of Basic, Digest & NTLM authentication schemes under certain circumstances leaking passwords in clear text to the DEBUG log. * Fixed the problem with incorrect selection of the proxy authentication realm. * Changed URI.normalize() to ignore relative path normalization. Release 2.0 Release Candidate 1 ------------------- Changes since Release 2.0 Beta 2: * Option to disable 'stale' connection check that may lead to a slight performance improvement at the cost of reduced reliability * Improved debug logging in multi-threaded connection manager * URI.normalize() no longer has an effect on relative URIs. * 21532 - Removed use of sun.* class in URI.java * 20481 - Changed query param encoding to UTF-8. * 21378 - Multiple transfer encoding headers are now handled properly. Non chunked transfer encodings are now handled correctly. Release 2.0 Beta 2 ------------------- Changes since Release 2.0 Beta 1: * 20240 - Cookies with null path are no longer rejected in the browser compatibility mode. * 20481 - Query parameters set via HttpMethodBase.setQueryString(NameValuePair[]) now correctly use 'application/x-www-form-urlencoded' encoding. * 20481 - POST method correctly applies 'application/x-www-form-urlencoded' encoding. * 20569 - Duplicate connection headers are now handled. * 20646 - Fixed NTLM proxy authentication via SSL. * 20665 - Changed URI to correctly handle path resolution according to http://www.apache.org/~fielding/uri/rev-2002/issues.html. In particular dot-segments are removed when not necessary. * 20938 - Connections are now closed when the request is missing a content length and is not chunked. * 20942 - Requests with DIGEST authentication are now correctly handled when redirected. * 21130 - DEFAULT_MAX_HOST_CONNECTIONS and DEFAULT_MAX_TOTAL_CONNECTIONS are now public in MultiThreadedHttpConnectionManager. * 21201 - URIs are now correctly rebuilt following a call to URI.normalize(). * 21202 - WireLogInputStream.read(byte[]) now logs the correct number of bytes. * Fixed path parsing in RFC2109 cookie spec. * Fixed possible NPE when reading an empty response body. * The various to*Charset() methods of URIUtil have been deprecated. Release 2.0 Beta 1 ------------------- Changes since Release 2.0 Alpha 3: * Changed HttpConnection to use socket timeout instead of busy waiting while expecting input. * Added a getResponseContentLength() method to HttpMethod. * Changed HttpClient to accept correctly encoded URLs instead of attempting to encode them within HttpClient. * 'Expect: 100-continue' logic factored out into an abstract ExpectContinueMethod class * 'Expect: 100-Continue' handshake disabled per default, as it may not work properly with older HTTP/1.0 servers or proxies. * Reengineered authentication code. This includes a fix for HttpClient continually attempting to authenticate to digest realms and provides for better future extensibility. * Authenticator class deprecated * Improved user documentation and example code. * Added ability to differentiate between different hosts using the same realm names. * Added support for specifying a virtual host name to use. * Fixed problem with half-closed connections causing a HttpRecoverableException to be thrown when HttpClient attempts to read from a socket. * Improved reliability with the HEAD method and servers that incorrectly include a response body. * Improved support for connection keep-alive when communicating via a proxy * Added an override of HttpClient.executeMethod that lets the caller specify an HttpState object. * HttpConnectionManager is now a property of the HttpClient class, not of the HttpState class * Added ability to specify the local address that HttpClient should create connections from. Release 2.0 Alpha 3 ------------------- Changes since Release 2.0 Alpha 2: * Abstract EntityEnclosingMethod class has been introduced to encapsulate common behaviour of all entity enclosing methods * "Expect: 100-continue" handshake support added for POST, PUT & multipart POST * Added support for chunked requests for POST and PUT. * Added support for 303 See Other redirections. * Changed input and output streams to use buffering to improve performance. * Improved handling of multivalue headers. Order is now preserved and convenience methods have been added to access each value. * In non-strict mode each cookie sent with the request is put on a separate request header. In strict mode all cookies are crammed into one request header, as before. * ResponseInputStream class deprecated. * RequestOutputStream class deprecated. * Custom character set can be specified for all multipart classes. * Custom content type can be specified for FilePart derived multipart classes. * The useDisk methods in GetMethod class deprecated. Release 2.0 Alpha 2 ------------------ Changes since Release 2.0 Alpha 1: * Mavenized builds. * Digest authentication. NTLM authentication. * Multipart post. * Added a StatusLine class to manage the status line of a http response. * Added ability to cusomize SocketFactory for http and https. New Protocol class to allow for more protocols than just http/s. * Removed the HttpMultiClient, added multi-thread support to HttpClient. * Revamp the streaming policy. Added AutoCloseInputStream, ChunkedInputStream, ChunkedOutputStream, ContentLengthInputStream, ResponseConsumedWatcher * Commons Logging. Dependancy on the commons-logging.jar * Added httpclient.util package. Move Base64 and URIUtil classs into util. * Added a HttpURLConnection wrapper. Allows for wrapping HttpClient into the java standard library. Partial support only. * Added httpclient.cookie package. Complete overhaul of cookie handling. Allows for user specified CookiePolicy and various cookie specification classes. * Removed previously deprecated Cookie.createCookieHeader(String, String,boolean,Cookie[]) method (port number is required for future compatibility). * Also removed Cookie.createCookieHeader(String,String,Cookie[]) method, which should have been deprecated (port number is required for future compatibility) * Renamed HttpMethod.followRedirects to getFollowRedirects, for consistency (and made the corresponding change to HttpMethodBase) commons-httpclient-3.1/build.properties.sample100644 0 0 3201 10661532627 17034 0ustar 0 0 # =================================================================== # Sample build.properties file # # Make a copy this file named "build.properties", # and customize it to your environment and preferences. # # $Id: build.properties.sample 190382 2005-06-13 10:58:56Z oglueck $ # =================================================================== # =================================================================== # Classpath Settings # =================================================================== # The base directory for libraries used by HttpClient lib.dir=./lib # Required compile and runtime dependencies. commons-logging.jar=${lib.dir}/commons-logging.jar commons-codec.jar=${lib.dir}/commons-codec.jar # Required to compile and run the unit tests. junit.jar=${lib.dir}/junit.jar # A JSSE implementation (see http://java.sun.com/products/jsse): # Required to compile, only needed at runtime if you're using HTTPS. # A JCE implementation (see http://java.sun.com/products/jce): # Required to compile, only needed at runtime if you're using NTLM. # Both JSSE and JCE are expected to be present and configured in # the JDK/JRE # =================================================================== # Test Properties - used to configure the test cases # =================================================================== # - indicates which log writer to use (optional) httpclient.test.log=org.apache.commons.logging.impl.SimpleLog #httpclient.test.log=org.apache.commons.logging.impl.Log4JCategoryLog #httpclient.test.log=org.apache.commons.logging.impl.NoOpLog maven.username=yourASFid maven.repo.asf.privatekey=/home/myuser/.ssh/id_dsa commons-httpclient-3.1/build.xml100644 0 0 24202 10661532626 14203 0ustar 0 0 commons-httpclient-3.1/docs/apidocs/allclasses-frame.html100644 0 0 56236 10661532627 21055 0ustar 0 0 All Classes (HttpClient 3.1 API) All Classes
AuthChallengeException
AuthChallengeParser
AuthChallengeProcessor
AuthenticationException
AuthPolicy
AuthScheme
AuthSchemeBase
AuthScope
AuthState
BasicScheme
ByteArrayPartSource
ByteArrayRequestEntity
ChunkedInputStream
ChunkedOutputStream
CircularRedirectException
ConnectionPoolTimeoutException
ConnectMethod
ConnectTimeoutException
ContentLengthInputStream
ControllerThreadSocketFactory
ControllerThreadSocketFactory.SocketTask
Cookie
Cookie2
CookieAttributeHandler
CookieOrigin
CookiePathComparator
CookiePolicy
CookieSpec
CookieSpecBase
CookieVersionSupport
Credentials
CredentialsNotAvailableException
CredentialsProvider
DateParseException
DateParser
DateUtil
DefaultHttpMethodRetryHandler
DefaultHttpParams
DefaultHttpParamsFactory
DefaultMethodRetryHandler
DefaultProtocolSocketFactory
DeleteMethod
DigestScheme
EncodingUtil
EntityEnclosingMethod
ExceptionUtil
ExpectContinueMethod
FilePart
FilePartSource
FileRequestEntity
GetMethod
Header
HeaderElement
HeaderGroup
HeadMethod
HostConfiguration
HostParams
HttpAuthenticator
HttpAuthRealm
HttpClient
HttpClientError
HttpClientParams
HttpConnection
HttpConnectionManager
HttpConnectionManagerParams
HttpConnectionParams
HttpConstants
HttpContentTooLargeException
HttpException
HttpHost
HttpMethod
HttpMethodBase
HttpMethodParams
HttpMethodRetryHandler
HttpParams
HttpParamsFactory
HttpParser
HttpRecoverableException
HttpState
HttpStatus
HttpsURL
HttpURL
HttpURLConnection
HttpVersion
IdleConnectionHandler
IdleConnectionTimeoutThread
IgnoreCookiesSpec
InputStreamRequestEntity
InvalidCredentialsException
InvalidRedirectLocationException
LangUtils
MalformedChallengeException
MalformedCookieException
MethodRetryHandler
MultipartPostMethod
MultipartRequestEntity
MultiThreadedHttpConnectionManager
NameValuePair
NetscapeDraftSpec
NoHttpResponseException
NTCredentials
NTLMScheme
OptionsMethod
ParameterFormatter
ParameterParser
Part
PartBase
PartSource
PostMethod
Protocol
ProtocolException
ProtocolSocketFactory
ProxyClient
ProxyClient.ConnectResponse
ProxyHost
PutMethod
RedirectException
ReflectionSocketFactory
RequestEntity
RFC2109Spec
RFC2617Scheme
RFC2965Spec
SecureProtocolSocketFactory
SimpleHttpConnectionManager
SSLProtocolSocketFactory
StatusLine
StringPart
StringRequestEntity
TimeoutController
TimeoutController.TimeoutException
TraceMethod
URI
URI.DefaultCharsetChanged
URI.LocaleToCharsetMap
URIException
URIUtil
URIUtil.Coder
UsernamePasswordCredentials
commons-httpclient-3.1/docs/apidocs/allclasses-noframe.html100644 0 0 50726 10661532627 21410 0ustar 0 0 All Classes (HttpClient 3.1 API) All Classes
AuthChallengeException
AuthChallengeParser
AuthChallengeProcessor
AuthenticationException
AuthPolicy
AuthScheme
AuthSchemeBase
AuthScope
AuthState
BasicScheme
ByteArrayPartSource
ByteArrayRequestEntity
ChunkedInputStream
ChunkedOutputStream
CircularRedirectException
ConnectionPoolTimeoutException
ConnectMethod
ConnectTimeoutException
ContentLengthInputStream
ControllerThreadSocketFactory
ControllerThreadSocketFactory.SocketTask
Cookie
Cookie2
CookieAttributeHandler
CookieOrigin
CookiePathComparator
CookiePolicy
CookieSpec
CookieSpecBase
CookieVersionSupport
Credentials
CredentialsNotAvailableException
CredentialsProvider
DateParseException
DateParser
DateUtil
DefaultHttpMethodRetryHandler
DefaultHttpParams
DefaultHttpParamsFactory
DefaultMethodRetryHandler
DefaultProtocolSocketFactory
DeleteMethod
DigestScheme
EncodingUtil
EntityEnclosingMethod
ExceptionUtil
ExpectContinueMethod
FilePart
FilePartSource
FileRequestEntity
GetMethod
Header
HeaderElement
HeaderGroup
HeadMethod
HostConfiguration
HostParams
HttpAuthenticator
HttpAuthRealm
HttpClient
HttpClientError
HttpClientParams
HttpConnection
HttpConnectionManager
HttpConnectionManagerParams
HttpConnectionParams
HttpConstants
HttpContentTooLargeException
HttpException
HttpHost
HttpMethod
HttpMethodBase
HttpMethodParams
HttpMethodRetryHandler
HttpParams
HttpParamsFactory
HttpParser
HttpRecoverableException
HttpState
HttpStatus
HttpsURL
HttpURL
HttpURLConnection
HttpVersion
IdleConnectionHandler
IdleConnectionTimeoutThread
IgnoreCookiesSpec
InputStreamRequestEntity
InvalidCredentialsException
InvalidRedirectLocationException
LangUtils
MalformedChallengeException
MalformedCookieException
MethodRetryHandler
MultipartPostMethod
MultipartRequestEntity
MultiThreadedHttpConnectionManager
NameValuePair
NetscapeDraftSpec
NoHttpResponseException
NTCredentials
NTLMScheme
OptionsMethod
ParameterFormatter
ParameterParser
Part
PartBase
PartSource
PostMethod
Protocol
ProtocolException
ProtocolSocketFactory
ProxyClient
ProxyClient.ConnectResponse
ProxyHost
PutMethod
RedirectException
ReflectionSocketFactory
RequestEntity
RFC2109Spec
RFC2617Scheme
RFC2965Spec
SecureProtocolSocketFactory
SimpleHttpConnectionManager
SSLProtocolSocketFactory
StatusLine
StringPart
StringRequestEntity
TimeoutController
TimeoutController.TimeoutException
TraceMethod
URI
URI.DefaultCharsetChanged
URI.LocaleToCharsetMap
URIException
URIUtil
URIUtil.Coder
UsernamePasswordCredentials
commons-httpclient-3.1/docs/apidocs/constant-values.html100644 0 0 300073 10661532627 20774 0ustar 0 0 Constant Field Values (HttpClient 3.1 API)

Constant Field Values


Contents
org.apache.*

org.apache.commons.httpclient.ConnectMethod
public static final String NAME "CONNECT"

org.apache.commons.httpclient.HttpConstants
public static final String DEFAULT_CONTENT_CHARSET "ISO-8859-1"
public static final String HTTP_ELEMENT_CHARSET "US-ASCII"

org.apache.commons.httpclient.HttpState
public static final String PREEMPTIVE_DEFAULT "false"
public static final String PREEMPTIVE_PROPERTY "httpclient.authentication.preemptive"

org.apache.commons.httpclient.HttpStatus
public static final int SC_ACCEPTED 202
public static final int SC_BAD_GATEWAY 502
public static final int SC_BAD_REQUEST 400
public static final int SC_CONFLICT 409
public static final int SC_CONTINUE 100
public static final int SC_CREATED 201
public static final int SC_EXPECTATION_FAILED 417
public static final int SC_FAILED_DEPENDENCY 424
public static final int SC_FORBIDDEN 403
public static final int SC_GATEWAY_TIMEOUT 504
public static final int SC_GONE 410
public static final int SC_HTTP_VERSION_NOT_SUPPORTED 505
public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE 419
public static final int SC_INSUFFICIENT_STORAGE 507
public static final int SC_INTERNAL_SERVER_ERROR 500
public static final int SC_LENGTH_REQUIRED 411
public static final int SC_LOCKED 423
public static final int SC_METHOD_FAILURE 420
public static final int SC_METHOD_NOT_ALLOWED 405
public static final int SC_MOVED_PERMANENTLY 301
public static final int SC_MOVED_TEMPORARILY 302
public static final int SC_MULTI_STATUS 207
public static final int SC_MULTIPLE_CHOICES 300
public static final int SC_NO_CONTENT 204
public static final int SC_NON_AUTHORITATIVE_INFORMATION 203
public static final int SC_NOT_ACCEPTABLE 406
public static final int SC_NOT_FOUND 404
public static final int SC_NOT_IMPLEMENTED 501
public static final int SC_NOT_MODIFIED 304
public static final int SC_OK 200
public static final int SC_PARTIAL_CONTENT 206
public static final int SC_PAYMENT_REQUIRED 402
public static final int SC_PRECONDITION_FAILED 412
public static final int SC_PROCESSING 102
public static final int SC_PROXY_AUTHENTICATION_REQUIRED 407
public static final int SC_REQUEST_TIMEOUT 408
public static final int SC_REQUEST_TOO_LONG 413
public static final int SC_REQUEST_URI_TOO_LONG 414
public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE 416
public static final int SC_RESET_CONTENT 205
public static final int SC_SEE_OTHER 303
public static final int SC_SERVICE_UNAVAILABLE 503
public static final int SC_SWITCHING_PROTOCOLS 101
public static final int SC_TEMPORARY_REDIRECT 307
public static final int SC_UNAUTHORIZED 401
public static final int SC_UNPROCESSABLE_ENTITY 422
public static final int SC_UNSUPPORTED_MEDIA_TYPE 415
public static final int SC_USE_PROXY 305

org.apache.commons.httpclient.HttpsURL
public static final int _default_port 443
public static final int DEFAULT_PORT 443

org.apache.commons.httpclient.HttpURL
public static final int _default_port 80
public static final int DEFAULT_PORT 80

org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
public static final int DEFAULT_MAX_HOST_CONNECTIONS 2
public static final int DEFAULT_MAX_TOTAL_CONNECTIONS 20

org.apache.commons.httpclient.URI.DefaultCharsetChanged
public static final int DOCUMENT_CHARSET 2
public static final int PROTOCOL_CHARSET 1
public static final int UNKNOWN 0

org.apache.commons.httpclient.URIException
public static final int ESCAPING 3
public static final int PARSING 1
public static final int PUNYCODE 4
public static final int UNKNOWN 0
public static final int UNSUPPORTED_ENCODING 2

org.apache.commons.httpclient.auth.AuthPolicy
public static final String AUTH_SCHEME_PRIORITY "http.auth.scheme-priority"
public static final String BASIC "Basic"
public static final String DIGEST "Digest"
public static final String NTLM "NTLM"

org.apache.commons.httpclient.auth.AuthScope
public static final int ANY_PORT -1

org.apache.commons.httpclient.auth.AuthState
public static final String PREEMPTIVE_AUTH_SCHEME "basic"

org.apache.commons.httpclient.auth.CredentialsProvider
public static final String PROVIDER "http.authentication.credential-provider"

org.apache.commons.httpclient.auth.HttpAuthenticator
public static final String PROXY_AUTH "Proxy-Authenticate"
public static final String PROXY_AUTH_RESP "Proxy-Authorization"
public static final String WWW_AUTH "WWW-Authenticate"
public static final String WWW_AUTH_RESP "Authorization"

org.apache.commons.httpclient.cookie.Cookie2
public static final String COMMENT "comment"
public static final String COMMENTURL "commenturl"
public static final String DISCARD "discard"
public static final String DOMAIN "domain"
public static final String MAXAGE "max-age"
public static final String PATH "path"
public static final String PORT "port"
public static final String SECURE "secure"
public static final String VERSION "version"

org.apache.commons.httpclient.cookie.CookiePolicy
public static final String BROWSER_COMPATIBILITY "compatibility"
public static final int COMPATIBILITY 0
public static final String DEFAULT "default"
public static final String IGNORE_COOKIES "ignoreCookies"
public static final String NETSCAPE "netscape"
public static final int NETSCAPE_DRAFT 1
public static final String RFC_2109 "rfc2109"
public static final String RFC_2965 "rfc2965"
public static final int RFC2109 2
public static final int RFC2965 3

org.apache.commons.httpclient.cookie.CookieSpec
public static final String PATH_DELIM "/"

org.apache.commons.httpclient.cookie.RFC2109Spec
public static final String SET_COOKIE_KEY "set-cookie"

org.apache.commons.httpclient.cookie.RFC2965Spec
public static final String SET_COOKIE2_KEY "set-cookie2"

org.apache.commons.httpclient.methods.EntityEnclosingMethod
public static final long CONTENT_LENGTH_AUTO -2L
public static final long CONTENT_LENGTH_CHUNKED -1L

org.apache.commons.httpclient.methods.InputStreamRequestEntity
public static final int CONTENT_LENGTH_AUTO -2

org.apache.commons.httpclient.methods.MultipartPostMethod
public static final String MULTIPART_FORM_CONTENT_TYPE "multipart/form-data"

org.apache.commons.httpclient.methods.PostMethod
public static final String FORM_URL_ENCODED_CONTENT_TYPE "application/x-www-form-urlencoded"

org.apache.commons.httpclient.methods.multipart.FilePart
public static final String DEFAULT_CHARSET "ISO-8859-1"
public static final String DEFAULT_CONTENT_TYPE "application/octet-stream"
public static final String DEFAULT_TRANSFER_ENCODING "binary"
protected static final String FILE_NAME "; filename="

org.apache.commons.httpclient.methods.multipart.Part
protected static final String BOUNDARY "----------------314159265358979323846"
protected static final String CHARSET "; charset="
protected static final String CONTENT_DISPOSITION "Content-Disposition: form-data; name="
protected static final String CONTENT_TRANSFER_ENCODING "Content-Transfer-Encoding: "
protected static final String CONTENT_TYPE "Content-Type: "
protected static final String CRLF "\r\n"
protected static final String EXTRA "--"
protected static final String QUOTE "\""

org.apache.commons.httpclient.methods.multipart.StringPart
public static final String DEFAULT_CHARSET "US-ASCII"
public static final String DEFAULT_CONTENT_TYPE "text/plain"
public static final String DEFAULT_TRANSFER_ENCODING "8bit"

org.apache.commons.httpclient.params.HostParams
public static final String DEFAULT_HEADERS "http.default-headers"

org.apache.commons.httpclient.params.HttpClientParams
public static final String ALLOW_CIRCULAR_REDIRECTS "http.protocol.allow-circular-redirects"
public static final String CONNECTION_MANAGER_CLASS "http.connection-manager.class"
public static final String CONNECTION_MANAGER_TIMEOUT "http.connection-manager.timeout"
public static final String MAX_REDIRECTS "http.protocol.max-redirects"
public static final String PREEMPTIVE_AUTHENTICATION "http.authentication.preemptive"
public static final String REJECT_RELATIVE_REDIRECT "http.protocol.reject-relative-redirect"

org.apache.commons.httpclient.params.HttpConnectionManagerParams
public static final String MAX_HOST_CONNECTIONS "http.connection-manager.max-per-host"
public static final String MAX_TOTAL_CONNECTIONS "http.connection-manager.max-total"

org.apache.commons.httpclient.params.HttpConnectionParams
public static final String CONNECTION_TIMEOUT "http.connection.timeout"
public static final String SO_LINGER "http.socket.linger"
public static final String SO_RCVBUF "http.socket.receivebuffer"
public static final String SO_SNDBUF "http.socket.sendbuffer"
public static final String SO_TIMEOUT "http.socket.timeout"
public static final String STALE_CONNECTION_CHECK "http.connection.stalecheck"
public static final String TCP_NODELAY "http.tcp.nodelay"

org.apache.commons.httpclient.params.HttpMethodParams
public static final String BUFFER_WARN_TRIGGER_LIMIT "http.method.response.buffer.warnlimit"
public static final String COOKIE_POLICY "http.protocol.cookie-policy"
public static final String CREDENTIAL_CHARSET "http.protocol.credential-charset"
public static final String DATE_PATTERNS "http.dateparser.patterns"
public static final String HEAD_BODY_CHECK_TIMEOUT "http.protocol.head-body-timeout"
public static final String HTTP_CONTENT_CHARSET "http.protocol.content-charset"
public static final String HTTP_ELEMENT_CHARSET "http.protocol.element-charset"
public static final String HTTP_URI_CHARSET "http.protocol.uri-charset"
public static final String MULTIPART_BOUNDARY "http.method.multipart.boundary"
public static final String PROTOCOL_VERSION "http.protocol.version"
public static final String REJECT_HEAD_BODY "http.protocol.reject-head-body"
public static final String RETRY_HANDLER "http.method.retry-handler"
public static final String SINGLE_COOKIE_HEADER "http.protocol.single-cookie-header"
public static final String SO_TIMEOUT "http.socket.timeout"
public static final String STATUS_LINE_GARBAGE_LIMIT "http.protocol.status-line-garbage-limit"
public static final String STRICT_TRANSFER_ENCODING "http.protocol.strict-transfer-encoding"
public static final String UNAMBIGUOUS_STATUS_LINE "http.protocol.unambiguous-statusline"
public static final String USE_EXPECT_CONTINUE "http.protocol.expect-continue"
public static final String USER_AGENT "http.useragent"
public static final String VIRTUAL_HOST "http.virtual-host"
public static final String WARN_EXTRA_INPUT "http.protocol.warn-extra-input"

org.apache.commons.httpclient.util.DateParser
public static final String PATTERN_ASCTIME "EEE MMM d HH:mm:ss yyyy"
public static final String PATTERN_RFC1036 "EEEE, dd-MMM-yy HH:mm:ss zzz"
public static final String PATTERN_RFC1123 "EEE, dd MMM yyyy HH:mm:ss zzz"

org.apache.commons.httpclient.util.DateUtil
public static final String PATTERN_ASCTIME "EEE MMM d HH:mm:ss yyyy"
public static final String PATTERN_RFC1036 "EEEE, dd-MMM-yy HH:mm:ss zzz"
public static final String PATTERN_RFC1123 "EEE, dd MMM yyyy HH:mm:ss zzz"

org.apache.commons.httpclient.util.LangUtils
public static final int HASH_OFFSET 37
public static final int HASH_SEED 17



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/deprecated-list.html100644 0 0 226721 10661532627 20726 0ustar 0 0 Deprecated List (HttpClient 3.1 API)

Deprecated API


Contents
Deprecated Interfaces
org.apache.commons.httpclient.MethodRetryHandler
          use HttpMethodRetryHandler 
 

Deprecated Classes
org.apache.commons.httpclient.auth.AuthSchemeBase
          No longer used 
org.apache.commons.httpclient.util.DateParser
          Use DateUtil 
org.apache.commons.httpclient.DefaultMethodRetryHandler
          use DefaultHttpMethodRetryHandler 
org.apache.commons.httpclient.auth.HttpAuthenticator
          no longer used 
org.apache.commons.httpclient.auth.HttpAuthRealm
          no longer used 
org.apache.commons.httpclient.HttpConstants
          use EncodingUtil class 
org.apache.commons.httpclient.methods.MultipartPostMethod
          Use MultipartRequestEntity in conjunction with PostMethod instead. 
org.apache.commons.httpclient.util.URIUtil.Coder
          use org.apache.commons.codec.net.URLCodec 
 

Deprecated Exceptions
org.apache.commons.httpclient.HttpRecoverableException
          no longer used 
 

Deprecated Fields
org.apache.commons.httpclient.HttpsURL._default_port
          Use HttpsURL.DEFAULT_PORT instead. This one doesn't conform to the project naming conventions. 
org.apache.commons.httpclient.HttpURL._default_port
          Use HttpURL.DEFAULT_PORT instead. This one doesn't conform to the project naming conventions. 
org.apache.commons.httpclient.HttpsURL._default_scheme
          Use HttpsURL.DEFAULT_SCHEME instead. This one doesn't conform to the project naming conventions. 
org.apache.commons.httpclient.HttpURL._default_scheme
          Use HttpURL.DEFAULT_SCHEME instead. This one doesn't conform to the project naming conventions. 
org.apache.commons.httpclient.methods.multipart.Part.BOUNDARY
          use HttpMethodParams.MULTIPART_BOUNDARY 
org.apache.commons.httpclient.methods.multipart.Part.BOUNDARY_BYTES
            
org.apache.commons.httpclient.cookie.CookiePolicy.COMPATIBILITY
          Use CookiePolicy.BROWSER_COMPATIBILITY 
org.apache.commons.httpclient.methods.EntityEnclosingMethod.CONTENT_LENGTH_AUTO
          Use InputStreamRequestEntity.CONTENT_LENGTH_AUTO. 
org.apache.commons.httpclient.methods.EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED
          Use EntityEnclosingMethod.setContentChunked(boolean). 
org.apache.commons.httpclient.cookie.CookiePolicy.NETSCAPE_DRAFT
          Use CookiePolicy.NETSCAPE 
org.apache.commons.httpclient.HttpState.PREEMPTIVE_DEFAULT
          This field and feature will be removed following HttpClient 3.0. 
org.apache.commons.httpclient.HttpState.PREEMPTIVE_PROPERTY
          This field and feature will be removed following HttpClient 3.0. 
org.apache.commons.httpclient.cookie.CookiePolicy.RFC2109
          Use CookiePolicy.RFC_2109 
org.apache.commons.httpclient.cookie.CookiePolicy.RFC2965
          Use CookiePolicy.RFC_2965 
 

Deprecated Methods
org.apache.commons.httpclient.auth.HttpAuthenticator.authenticate(AuthScheme, HttpMethod, HttpConnection, HttpState)
          use AuthScheme 
org.apache.commons.httpclient.auth.NTLMScheme.authenticate(Credentials, String, String)
          Use NTLMScheme.authenticate(Credentials, HttpMethod) 
org.apache.commons.httpclient.auth.DigestScheme.authenticate(Credentials, String, String)
          Use DigestScheme.authenticate(Credentials, HttpMethod) 
org.apache.commons.httpclient.auth.BasicScheme.authenticate(Credentials, String, String)
          Use BasicScheme.authenticate(Credentials, HttpMethod) 
org.apache.commons.httpclient.auth.AuthScheme.authenticate(Credentials, String, String)
          Use AuthScheme.authenticate(Credentials, HttpMethod) Produces an authorization string for the given set of Credentials, method name and URI using the given authentication scheme in response to the actual authorization challenge. 
org.apache.commons.httpclient.auth.NTLMScheme.authenticate(NTCredentials, String)
          Use non-static NTLMScheme.authenticate(Credentials, HttpMethod) 
org.apache.commons.httpclient.auth.NTLMScheme.authenticate(NTCredentials, String, String)
          Use non-static NTLMScheme.authenticate(Credentials, HttpMethod) 
org.apache.commons.httpclient.auth.BasicScheme.authenticate(UsernamePasswordCredentials)
          Use BasicScheme.authenticate(UsernamePasswordCredentials, String) Returns a basic Authorization header value for the given UsernamePasswordCredentials. 
org.apache.commons.httpclient.auth.HttpAuthenticator.authenticateDefault(HttpMethod, HttpConnection, HttpState)
          use AuthScheme 
org.apache.commons.httpclient.auth.HttpAuthenticator.authenticateProxy(AuthScheme, HttpMethod, HttpConnection, HttpState)
          use AuthScheme 
org.apache.commons.httpclient.auth.HttpAuthenticator.authenticateProxyDefault(HttpMethod, HttpConnection, HttpState)
          use AuthScheme 
org.apache.commons.httpclient.util.URIUtil.Coder.decode(char[], String)
          use org.apache.commons.codec.net.URLCodec 
org.apache.commons.httpclient.util.URIUtil.Coder.encode(String, BitSet, String)
          use org.apache.commons.codec.net.URLCodec 
org.apache.commons.httpclient.HttpMethodBase.getAuthenticationRealm()
          use #getHostAuthState() 
org.apache.commons.httpclient.methods.HeadMethod.getBodyCheckTimeout()
          Use HttpMethodParams 
org.apache.commons.httpclient.methods.multipart.Part.getBoundary()
          uses a constant string. Rather use Part.getPartBoundary() 
org.apache.commons.httpclient.cookie.CookiePolicy.getCompatibilitySpec()
          Use CookiePolicy.getCookieSpec(String) 
org.apache.commons.httpclient.SimpleHttpConnectionManager.getConnection(HostConfiguration, long)
          Use #getConnectionWithTimeout(HostConfiguration, long) 
org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.getConnection(HostConfiguration, long)
          Use #getConnectionWithTimeout(HostConfiguration, long) 
org.apache.commons.httpclient.HttpConnectionManager.getConnection(HostConfiguration, long)
          Use #getConnectionWithTimeout(HostConfiguration, long) 
org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.getConnectionsInUse()
          Use MultiThreadedHttpConnectionManager.getConnectionsInPool() 
org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.getConnectionsInUse(HostConfiguration)
          Use MultiThreadedHttpConnectionManager.getConnectionsInPool(HostConfiguration) 
org.apache.commons.httpclient.HttpState.getCookiePolicy()
          Use HttpMethodParams.getCookiePolicy(), HttpMethod.getParams(). 
org.apache.commons.httpclient.HttpState.getCookies(String, int, String, boolean)
          use CookieSpec#match(String, int, String, boolean, Cookie) 
org.apache.commons.httpclient.HttpState.getCredentials(String, String)
          use #getCredentials(AuthScope) 
org.apache.commons.httpclient.cookie.CookiePolicy.getDefaultPolicy()
          Use CookiePolicy.getDefaultSpec() 
org.apache.commons.httpclient.HttpClient.getHost()
          use #getHostConfiguration() 
org.apache.commons.httpclient.HttpMethodBase.getHostConfiguration()
          no longer applicable 
org.apache.commons.httpclient.HttpMethod.getHostConfiguration()
          no longer applicable 
org.apache.commons.httpclient.auth.NTLMScheme.getID()
          no longer used 
org.apache.commons.httpclient.auth.DigestScheme.getID()
          no longer used 
org.apache.commons.httpclient.auth.RFC2617Scheme.getID()
          no longer used 
org.apache.commons.httpclient.auth.AuthScheme.getID()
          no longer used 
org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.getMaxConnectionsPerHost()
          Use HttpConnectionManagerParams.getDefaultMaxConnectionsPerHost(), HttpConnectionManager.getParams(). 
org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.getMaxTotalConnections()
          Use HttpConnectionManagerParams.getMaxTotalConnections(), HttpConnectionManager.getParams(). 
org.apache.commons.httpclient.HttpMethodBase.getMethodRetryHandler()
          use HttpMethodParams 
org.apache.commons.httpclient.HttpClient.getPort()
          use #getHostConfiguration() 
org.apache.commons.httpclient.HttpMethodBase.getProxyAuthenticationRealm()
          use #getProxyAuthState() 
org.apache.commons.httpclient.HttpState.getProxyCredentials(String, String)
          use #getProxyCredentials(AuthScope) 
org.apache.commons.httpclient.HttpException.getReason()
          HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release. 
org.apache.commons.httpclient.URIException.getReason()
          You should instead call Throwable.getMessage(). 
org.apache.commons.httpclient.HttpException.getReasonCode()
          HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release. 
org.apache.commons.httpclient.HttpMethodBase.getRecoverableExceptionCount()
          no longer used Returns the number of "recoverable" exceptions thrown and handled, to allow for monitoring the quality of the connection. 
org.apache.commons.httpclient.HttpConnection.getSoTimeout()
          Use HttpConnectionParams.getSoTimeout(), HttpConnection.getParams(). 
org.apache.commons.httpclient.cookie.CookiePolicy.getSpecByPolicy(int)
          Use CookiePolicy.getCookieSpec(String) 
org.apache.commons.httpclient.cookie.CookiePolicy.getSpecByVersion(int)
          Use CookiePolicy.getCookieSpec(String) 
org.apache.commons.httpclient.methods.ExpectContinueMethod.getUseExpectHeader()
          Use HttpMethodParams 
org.apache.commons.httpclient.Header.getValues()
          Use #getElements 
org.apache.commons.httpclient.HttpConnection.getVirtualHost()
          no longer applicable 
org.apache.commons.httpclient.HostConfiguration.getVirtualHost()
          use HostParams 
org.apache.commons.httpclient.HttpState.isAuthenticationPreemptive()
          Use HttpClientParams.isAuthenticationPreemptive(), HttpClient.getParams(). 
org.apache.commons.httpclient.SimpleHttpConnectionManager.isConnectionStaleCheckingEnabled()
          Use HttpConnectionParams.isStaleCheckingEnabled(), HttpConnectionManager.getParams(). 
org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.isConnectionStaleCheckingEnabled()
          Use HttpConnectionParams.isStaleCheckingEnabled(), HttpConnectionManager.getParams(). 
org.apache.commons.httpclient.HostConfiguration.isHostSet()
          no longer used 
org.apache.commons.httpclient.HttpMethodBase.isHttp11()
          Use HttpMethodParams.getVersion() 
org.apache.commons.httpclient.HostConfiguration.isProxySet()
          no longer used 
org.apache.commons.httpclient.HttpConnection.isStaleCheckingEnabled()
          Use HttpConnectionParams.isStaleCheckingEnabled(), HttpConnection.getParams(). 
org.apache.commons.httpclient.HttpClient.isStrictMode()
          Use DefaultHttpParams.getParameter(String) to exercise a more granular control over HTTP protocol strictness. 
org.apache.commons.httpclient.HttpMethodBase.isStrictMode()
          Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness. 
org.apache.commons.httpclient.HttpMethod.isStrictMode()
          Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness. 
org.apache.commons.httpclient.methods.OptionsMethod.needContentLength()
          only entity enclosing methods set content length header 
org.apache.commons.httpclient.HeaderElement.parse(String)
          Use #parseElements(String). 
org.apache.commons.httpclient.HttpParser.parseHeaders(InputStream)
          use #parseHeaders(InputStream, String) 
org.apache.commons.httpclient.HttpConnection.print(String)
          Use HttpConnection.print(String, String) Writes the specified String (as bytes) to the output stream. 
org.apache.commons.httpclient.HttpConnection.printLine(String)
          Use HttpConnection.printLine(String, String) Writes the specified String (as bytes), followed by "\r\n".getBytes() to the output stream. 
org.apache.commons.httpclient.HttpConnection.readLine()
          use #readLine(String) 
org.apache.commons.httpclient.HttpParser.readLine(InputStream)
          use #readLine(InputStream, String) 
org.apache.commons.httpclient.HttpMethodBase.recycle()
          no longer supported and will be removed in the future version of HttpClient 
org.apache.commons.httpclient.HttpMethod.recycle()
          no longer supported and will be removed in the future version of HttpClient 
org.apache.commons.httpclient.methods.TraceMethod.recycle()
          no longer supported and will be removed in the future version of HttpClient 
org.apache.commons.httpclient.methods.MultipartPostMethod.recycle()
          no longer supported and will be removed in the future version of HttpClient 
org.apache.commons.httpclient.methods.HeadMethod.recycle()
          no longer supported and will be removed in the future version of HttpClient 
org.apache.commons.httpclient.methods.GetMethod.recycle()
          no longer supported and will be removed in the future version of HttpClient 
org.apache.commons.httpclient.methods.EntityEnclosingMethod.recycle()
          no longer supported and will be removed in the future version of HttpClient 
org.apache.commons.httpclient.auth.HttpAuthenticator.selectAuthScheme(Header[])
          Use AuthChallengeParser.parseChallenges(Header[]) and AuthPolicy.getAuthScheme(String) 
org.apache.commons.httpclient.HttpState.setAuthenticationPreemptive(boolean)
          Use HttpClientParams.setAuthenticationPreemptive(boolean), HttpClient.getParams(). 
org.apache.commons.httpclient.methods.HeadMethod.setBodyCheckTimeout(int)
          Use HttpMethodParams 
org.apache.commons.httpclient.SimpleHttpConnectionManager.setConnectionStaleCheckingEnabled(boolean)
          Use HttpConnectionParams.setStaleCheckingEnabled(boolean), HttpConnectionManager.getParams(). 
org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.setConnectionStaleCheckingEnabled(boolean)
          Use HttpConnectionParams.setStaleCheckingEnabled(boolean), HttpConnectionManager.getParams(). 
org.apache.commons.httpclient.HttpClient.setConnectionTimeout(int)
          Use HttpConnectionParams.setConnectionTimeout(int), HttpConnectionManager.getParams(). 
org.apache.commons.httpclient.HttpConnection.setConnectionTimeout(int)
          Use HttpConnectionParams.setConnectionTimeout(int), HttpConnection.getParams(). 
org.apache.commons.httpclient.HttpState.setCookiePolicy(int)
          Use HttpMethodParams.setCookiePolicy(String), HttpMethod.getParams(). 
org.apache.commons.httpclient.HttpState.setCredentials(String, String, Credentials)
          use #setCredentials(AuthScope, Credentials) 
org.apache.commons.httpclient.cookie.CookiePolicy.setDefaultPolicy(int)
          Use CookiePolicy.registerCookieSpec(String, Class) 
org.apache.commons.httpclient.NTCredentials.setDomain(String)
          Do not use. The NTCredentials objects should be immutable 
org.apache.commons.httpclient.NTCredentials.setHost(String)
          Do not use. The NTCredentials objects should be immutable 
org.apache.commons.httpclient.HostConfiguration.setHost(String, String, int, Protocol)
          #setHost(String, int, Protocol) 
org.apache.commons.httpclient.HttpMethodBase.setHostConfiguration(HostConfiguration)
          no longer applicable 
org.apache.commons.httpclient.HttpMethodBase.setHttp11(boolean)
          Use HttpMethodParams.setVersion(HttpVersion) 
org.apache.commons.httpclient.HttpClient.setHttpConnectionFactoryTimeout(long)
          Use HttpClientParams.setConnectionManagerTimeout(long), HttpClient.getParams() 
org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.setMaxConnectionsPerHost(int)
          Use HttpConnectionManagerParams.setDefaultMaxConnectionsPerHost(int), HttpConnectionManager.getParams(). 
org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.setMaxTotalConnections(int)
          Use HttpConnectionManagerParams.setMaxTotalConnections(int), HttpConnectionManager.getParams(). 
org.apache.commons.httpclient.HttpMethodBase.setMethodRetryHandler(MethodRetryHandler)
          use HttpMethodParams 
org.apache.commons.httpclient.UsernamePasswordCredentials.setPassword(String)
          Do not use. The UsernamePasswordCredentials objects should be immutable 
org.apache.commons.httpclient.HttpState.setProxyCredentials(String, String, Credentials)
          use #setProxyCredentials(AuthScope, Credentials) 
org.apache.commons.httpclient.HttpException.setReason(String)
          HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release. 
org.apache.commons.httpclient.URIException.setReason(String)
          Callers should instead set this via a parameter to the constructor. 
org.apache.commons.httpclient.HttpException.setReasonCode(int)
          HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release. 
org.apache.commons.httpclient.URIException.setReasonCode(int)
          Callers should set the reason code as a parameter to the constructor. 
org.apache.commons.httpclient.methods.EntityEnclosingMethod.setRequestBody(InputStream)
          use EntityEnclosingMethod.setRequestEntity(RequestEntity) 
org.apache.commons.httpclient.methods.EntityEnclosingMethod.setRequestBody(String)
          use EntityEnclosingMethod.setRequestEntity(RequestEntity) 
org.apache.commons.httpclient.methods.EntityEnclosingMethod.setRequestContentLength(int)
          Use EntityEnclosingMethod.setContentChunked(boolean) or EntityEnclosingMethod.setRequestEntity(RequestEntity) 
org.apache.commons.httpclient.methods.EntityEnclosingMethod.setRequestContentLength(long)
          Use EntityEnclosingMethod.setContentChunked(boolean) or EntityEnclosingMethod.setRequestEntity(RequestEntity) 
org.apache.commons.httpclient.HttpConnection.setSendBufferSize(int)
          Use HttpConnectionParams.setSendBufferSize(int), HttpConnection.getParams(). 
org.apache.commons.httpclient.HttpConnection.setSoTimeout(int)
          Use HttpConnectionParams.setSoTimeout(int), HttpConnection.getParams(). 
org.apache.commons.httpclient.HttpConnection.setStaleCheckingEnabled(boolean)
          Use HttpConnectionParams.setStaleCheckingEnabled(boolean), HttpConnection.getParams(). 
org.apache.commons.httpclient.HttpClient.setStrictMode(boolean)
          Use DefaultHttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness. 
org.apache.commons.httpclient.HttpMethodBase.setStrictMode(boolean)
          Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness. 
org.apache.commons.httpclient.HttpMethod.setStrictMode(boolean)
          Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness. 
org.apache.commons.httpclient.HttpClient.setTimeout(int)
          Use HttpConnectionParams.setSoTimeout(int), HttpConnectionManager.getParams(). 
org.apache.commons.httpclient.methods.ExpectContinueMethod.setUseExpectHeader(boolean)
          Use HttpMethodParams 
org.apache.commons.httpclient.UsernamePasswordCredentials.setUserName(String)
          Do not use. The UsernamePasswordCredentials objects should be immutable 
org.apache.commons.httpclient.HttpConnection.setVirtualHost(String)
          no longer applicable 
org.apache.commons.httpclient.HttpConnection.shutdownOutput()
          unused 
 

Deprecated Constructors
org.apache.commons.httpclient.auth.AuthSchemeBase(String)
          Use parameterless constructor and AuthScheme.processChallenge(String) method 
org.apache.commons.httpclient.auth.BasicScheme(String)
          Use parameterless constructor and AuthScheme.processChallenge(String) method 
org.apache.commons.httpclient.ConnectMethod()
          use #ConnectMethod(HttpHost); Create a connect method. 
org.apache.commons.httpclient.ConnectMethod(HttpMethod)
          the wrapped method is no longer used Create a connect method wrapping the existing method 
org.apache.commons.httpclient.ContentLengthInputStream(InputStream, int)
          use ContentLengthInputStream.ContentLengthInputStream(InputStream, long) Creates a new length limited stream 
org.apache.commons.httpclient.auth.DigestScheme(String)
          Use parameterless constructor and AuthScheme.processChallenge(String) method 
org.apache.commons.httpclient.HttpConnection(String, int, String, String, int, Protocol)
          use #HttpConnection(String, int, String, int, Protocol) 
org.apache.commons.httpclient.NTCredentials()
          Do not use. Null user name, domain & host no longer allowed 
org.apache.commons.httpclient.protocol.Protocol(String, SecureProtocolSocketFactory, int)
          Use the constructor that uses ProtocolSocketFactory, this version of the constructor is only kept for backwards API compatibility. 
org.apache.commons.httpclient.auth.RFC2617Scheme(String)
          Use parameterless constructor and AuthScheme.processChallenge(String) method 
org.apache.commons.httpclient.methods.StringRequestEntity(String)
          use StringRequestEntity.StringRequestEntity(String, String, String) instead 
org.apache.commons.httpclient.URI(char[])
          Use #URI(String, boolean) 
org.apache.commons.httpclient.URI(char[], String)
          Use #URI(String, boolean, String) 
org.apache.commons.httpclient.URI(String)
          Use #URI(String, boolean) 
org.apache.commons.httpclient.URI(String, String)
          Use #URI(String, boolean, String) 
org.apache.commons.httpclient.URI(URI, String)
          Use #URI(URI, String, boolean) 
org.apache.commons.httpclient.UsernamePasswordCredentials()
          Do not use. Null user name no longer allowed 
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/help-doc.html100644 0 0 23065 10661532627 17324 0ustar 0 0 API Help (HttpClient 3.1 API)

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.

Overview

The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.

Package

Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:

  • Interfaces (italic)
  • Classes
  • Enums
  • Exceptions
  • Errors
  • Annotation Types

Class/Interface

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:

  • Class inheritance diagram
  • Direct Subclasses
  • All Known Subinterfaces
  • All Known Implementing Classes
  • Class/interface declaration
  • Class/interface description

  • Nested Class Summary
  • Field Summary
  • Constructor Summary
  • Method Summary

  • Field Detail
  • Constructor Detail
  • Method Detail
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

Annotation Type

Each annotation type has its own separate page with the following sections:

  • Annotation Type declaration
  • Annotation Type description
  • Required Element Summary
  • Optional Element Summary
  • Element Detail

Enum

Each enum has its own separate page with the following sections:

  • Enum declaration
  • Enum description
  • Enum Constant Summary
  • Enum Constant Detail

Use

Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class or package. Given a class or interface A, its Use page includes subclasses of A, fields declared as A, methods that return A, and methods and constructors with parameters of type A. You can access this page by first going to the package, class or interface, then clicking on the "Use" link in the navigation bar.

Tree (Class Hierarchy)

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
  • When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
  • When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.

Deprecated API

The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.

Index

The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.

Prev/Next

These links take you to the next or previous class, interface, package, or related page.

Frames/No Frames

These links show and hide the HTML frames. All pages are available with or without frames.

Serialized Form

Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class description.

Constant Field Values

The Constant Field Values page lists the static final fields and their values.

This help file applies to API documentation generated using the standard doclet.



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/index-all.html100644 0 0 2702216 10661532627 17552 0ustar 0 0 Index (HttpClient 3.1 API)
A B C D E F G H I L M N O P Q R S T U V W _

A

abort() - Method in interface org.apache.commons.httpclient.HttpMethod
Aborts the execution of the HTTP method.
abort() - Method in class org.apache.commons.httpclient.HttpMethodBase
Aborts the execution of this method.
abs_path - Static variable in class org.apache.commons.httpclient.URI
URI absolute path.
absoluteURI - Static variable in class org.apache.commons.httpclient.URI
BitSet for absoluteURI.
add(HttpConnection) - Method in class org.apache.commons.httpclient.util.IdleConnectionHandler
Registers the given connection with this handler.
addConnectionManager(HttpConnectionManager) - Method in class org.apache.commons.httpclient.util.IdleConnectionTimeoutThread
Adds a connection manager to be handled by this class.
addContentLengthRequestHeader(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Generates Content-Length or Transfer-Encoding: Chunked request header, as long as no Content-Length request header already exists.
addContentLengthRequestHeader(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Adds a Content-Length request header, as long as no Content-Length request header already exists.
addContentTypeRequestHeader(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Adds a Content-Type request header.
addCookie(Cookie) - Method in class org.apache.commons.httpclient.HttpState
Adds an HTTP cookie, replacing any existing equivalent cookies.
addCookieRequestHeader(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.ConnectMethod
This method does nothing.
addCookieRequestHeader(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Generates Cookie request headers for those cookies that match the given host, port and path.
addCookies(Cookie[]) - Method in class org.apache.commons.httpclient.HttpState
Adds an array of HTTP cookies.
addHeader(Header) - Method in class org.apache.commons.httpclient.HeaderGroup
Adds the given header to the group.
addHostRequestHeader(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Generates Host request header, as long as no Host request header already exists.
addParameter(String, String) - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Adds a text field part
addParameter(String, File) - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Adds a binary file part
addParameter(String, String, File) - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Adds a binary file part with the given file name
addParameter(String, String) - Method in class org.apache.commons.httpclient.methods.PostMethod
Adds a new parameter to be used in the POST request body.
addParameter(NameValuePair) - Method in class org.apache.commons.httpclient.methods.PostMethod
Adds a new parameter to be used in the POST request body.
addParameters(NameValuePair[]) - Method in class org.apache.commons.httpclient.methods.PostMethod
Adds an array of parameters to be used in the POST request body.
addPart(Part) - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Adds a part.
addProxyConnectionHeader(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Generates Proxy-Connection: Keep-Alive request header when communicating via a proxy server.
addRequestHeader(String, String) - Method in interface org.apache.commons.httpclient.HttpMethod
Adds the specified request header, not overwriting any previous value.
addRequestHeader(Header) - Method in interface org.apache.commons.httpclient.HttpMethod
Adds the specified request header, not overwriting any previous value.
addRequestHeader(Header) - Method in class org.apache.commons.httpclient.HttpMethodBase
Adds the specified request header, NOT overwriting any previous value.
addRequestHeader(String, String) - Method in class org.apache.commons.httpclient.HttpMethodBase
Adds the specified request header, NOT overwriting any previous value.
addRequestHeaders(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.ConnectMethod
Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
addRequestHeaders(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Generates all the required request headers to be submitted via the given connection.
addRequestHeaders(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
addRequestHeaders(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.methods.ExpectContinueMethod
Sets the Expect header if it has not already been set, in addition to the "standard" set of headers.
addRequestHeaders(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
addResponseFooter(Header) - Method in interface org.apache.commons.httpclient.HttpMethod
Add a footer to this method's response.
addResponseFooter(Header) - Method in class org.apache.commons.httpclient.HttpMethodBase
Use this method internally to add footers.
addUserAgentRequestHeader(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Generates default User-Agent request header, as long as no User-Agent request header already exists.
ALLOW_CIRCULAR_REDIRECTS - Static variable in class org.apache.commons.httpclient.params.HttpClientParams
Defines whether circular redirects (redirects to the same location) should be allowed.
allowed_abs_path - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for the abs_path.
allowed_authority - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for the authority component.
allowed_fragment - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for the fragment component.
allowed_host - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for the host component.
allowed_IPv6reference - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for the IPv6reference component.
allowed_opaque_part - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for the opaque_part.
allowed_query - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for the query component.
allowed_reg_name - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for the reg_name.
allowed_rel_path - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for the rel_path.
allowed_userinfo - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for the userinfo component.
allowed_within_authority - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for the authority component.
allowed_within_path - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed within the path.
allowed_within_query - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed within the query component.
allowed_within_userinfo - Static variable in class org.apache.commons.httpclient.URI
Those characters that are allowed for within the userinfo component.
alpha - Static variable in class org.apache.commons.httpclient.URI
BitSet for alpha.
alphanum - Static variable in class org.apache.commons.httpclient.URI
BitSet for alphanum (join of alpha & digit).
ANY - Static variable in class org.apache.commons.httpclient.auth.AuthScope
Default scope matching any host, port, realm and authentication scheme.
ANY_HOST - Static variable in class org.apache.commons.httpclient.auth.AuthScope
The null value represents any host.
ANY_HOST_CONFIGURATION - Static variable in class org.apache.commons.httpclient.HostConfiguration
A value to represent any host configuration, instead of using something like null.
ANY_PORT - Static variable in class org.apache.commons.httpclient.auth.AuthScope
The -1 value represents any port.
ANY_REALM - Static variable in class org.apache.commons.httpclient.auth.AuthScope
The null value represents any realm.
ANY_SCHEME - Static variable in class org.apache.commons.httpclient.auth.AuthScope
The null value represents any authentication scheme.
assertNotOpen() - Method in class org.apache.commons.httpclient.HttpConnection
Throws an IllegalStateException if the connection is already open.
assertOpen() - Method in class org.apache.commons.httpclient.HttpConnection
Throws an IllegalStateException if the connection is not open.
AUTH_SCHEME_PRIORITY - Static variable in class org.apache.commons.httpclient.auth.AuthPolicy
The key used to look up the list of IDs of supported authentication schemes in their order of preference.
AuthChallengeException - Exception in org.apache.commons.httpclient.auth
Signals a failure processing authentication challenge
AuthChallengeException() - Constructor for exception org.apache.commons.httpclient.auth.AuthChallengeException
Creates a new AuthChallengeException with a null detail message.
AuthChallengeException(String) - Constructor for exception org.apache.commons.httpclient.auth.AuthChallengeException
Creates a new AuthChallengeException with the specified message.
AuthChallengeException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.auth.AuthChallengeException
Creates a new AuthChallengeException with the specified detail message and cause.
AuthChallengeParser - Class in org.apache.commons.httpclient.auth
This class provides utility methods for parsing HTTP www and proxy authentication challenges.
AuthChallengeParser() - Constructor for class org.apache.commons.httpclient.auth.AuthChallengeParser
 
AuthChallengeProcessor - Class in org.apache.commons.httpclient.auth
This class provides utility methods for processing HTTP www and proxy authentication challenges.
AuthChallengeProcessor(HttpParams) - Constructor for class org.apache.commons.httpclient.auth.AuthChallengeProcessor
Creates an authentication challenge processor with the given HTTP parameters
authenticate(Credentials, String, String) - Method in interface org.apache.commons.httpclient.auth.AuthScheme
Deprecated. Use AuthScheme.authenticate(Credentials, HttpMethod) Produces an authorization string for the given set of Credentials, method name and URI using the given authentication scheme in response to the actual authorization challenge.
authenticate(Credentials, HttpMethod) - Method in interface org.apache.commons.httpclient.auth.AuthScheme
Produces an authorization string for the given set of Credentials.
authenticate(Credentials, String, String) - Method in class org.apache.commons.httpclient.auth.BasicScheme
Deprecated. Use BasicScheme.authenticate(Credentials, HttpMethod)
authenticate(Credentials, HttpMethod) - Method in class org.apache.commons.httpclient.auth.BasicScheme
Produces basic authorization string for the given set of Credentials.
authenticate(UsernamePasswordCredentials) - Static method in class org.apache.commons.httpclient.auth.BasicScheme
Deprecated. Use BasicScheme.authenticate(UsernamePasswordCredentials, String) Returns a basic Authorization header value for the given UsernamePasswordCredentials.
authenticate(UsernamePasswordCredentials, String) - Static method in class org.apache.commons.httpclient.auth.BasicScheme
Returns a basic Authorization header value for the given UsernamePasswordCredentials and charset.
authenticate(Credentials, String, String) - Method in class org.apache.commons.httpclient.auth.DigestScheme
Deprecated. Use DigestScheme.authenticate(Credentials, HttpMethod)
authenticate(Credentials, HttpMethod) - Method in class org.apache.commons.httpclient.auth.DigestScheme
Produces a digest authorization string for the given set of Credentials, method name and URI.
authenticate(AuthScheme, HttpMethod, HttpConnection, HttpState) - Static method in class org.apache.commons.httpclient.auth.HttpAuthenticator
Deprecated. use AuthScheme
authenticate(NTCredentials, String) - Static method in class org.apache.commons.httpclient.auth.NTLMScheme
Deprecated. Use non-static NTLMScheme.authenticate(Credentials, HttpMethod)
authenticate(NTCredentials, String, String) - Static method in class org.apache.commons.httpclient.auth.NTLMScheme
Deprecated. Use non-static NTLMScheme.authenticate(Credentials, HttpMethod)
authenticate(Credentials, String, String) - Method in class org.apache.commons.httpclient.auth.NTLMScheme
Deprecated. Use NTLMScheme.authenticate(Credentials, HttpMethod)
authenticate(Credentials, HttpMethod) - Method in class org.apache.commons.httpclient.auth.NTLMScheme
Produces NTLM authorization string for the given set of Credentials.
authenticateDefault(HttpMethod, HttpConnection, HttpState) - Static method in class org.apache.commons.httpclient.auth.HttpAuthenticator
Deprecated. use AuthScheme
authenticateProxy(AuthScheme, HttpMethod, HttpConnection, HttpState) - Static method in class org.apache.commons.httpclient.auth.HttpAuthenticator
Deprecated. use AuthScheme
authenticateProxyDefault(HttpMethod, HttpConnection, HttpState) - Static method in class org.apache.commons.httpclient.auth.HttpAuthenticator
Deprecated. use AuthScheme
AuthenticationException - Exception in org.apache.commons.httpclient.auth
Signals a failure in authentication process
AuthenticationException() - Constructor for exception org.apache.commons.httpclient.auth.AuthenticationException
Creates a new AuthenticationException with a null detail message.
AuthenticationException(String) - Constructor for exception org.apache.commons.httpclient.auth.AuthenticationException
Creates a new AuthenticationException with the specified message.
AuthenticationException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.auth.AuthenticationException
Creates a new AuthenticationException with the specified detail message and cause.
authority - Static variable in class org.apache.commons.httpclient.URI
BitSet for authority.
AuthPolicy - Class in org.apache.commons.httpclient.auth
Authentication policy class.
AuthPolicy() - Constructor for class org.apache.commons.httpclient.auth.AuthPolicy
 
AuthScheme - Interface in org.apache.commons.httpclient.auth
This interface represents an abstract challenge-response oriented authentication scheme.
AuthSchemeBase - Class in org.apache.commons.httpclient.auth
Deprecated. No longer used
AuthSchemeBase(String) - Constructor for class org.apache.commons.httpclient.auth.AuthSchemeBase
Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
AuthScope - Class in org.apache.commons.httpclient.auth
The class represents an authentication scope consisting of a host name, a port number, a realm name and an authentication scheme name which Credentials apply to.
AuthScope(String, int, String, String) - Constructor for class org.apache.commons.httpclient.auth.AuthScope
Creates a new credentials scope for the given host, port, realm, and authentication scheme.
AuthScope(String, int, String) - Constructor for class org.apache.commons.httpclient.auth.AuthScope
Creates a new credentials scope for the given host, port, realm, and any authentication scheme.
AuthScope(String, int) - Constructor for class org.apache.commons.httpclient.auth.AuthScope
Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.
AuthScope(AuthScope) - Constructor for class org.apache.commons.httpclient.auth.AuthScope
Creates a copy of the given credentials scope.
AuthState - Class in org.apache.commons.httpclient.auth
This class provides detailed information about the state of the authentication process.
AuthState() - Constructor for class org.apache.commons.httpclient.auth.AuthState
Default constructor.
available() - Method in class org.apache.commons.httpclient.ContentLengthInputStream
 

B

BASIC - Static variable in class org.apache.commons.httpclient.auth.AuthPolicy
Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported)
BasicScheme - Class in org.apache.commons.httpclient.auth
Basic authentication scheme as defined in RFC 2617.
BasicScheme() - Constructor for class org.apache.commons.httpclient.auth.BasicScheme
Default constructor for the basic authetication scheme.
BasicScheme(String) - Constructor for class org.apache.commons.httpclient.auth.BasicScheme
Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
BOUNDARY - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Deprecated. use HttpMethodParams.MULTIPART_BOUNDARY
BOUNDARY_BYTES - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Deprecated.  
BROWSER_COMPATIBILITY - Static variable in class org.apache.commons.httpclient.cookie.CookiePolicy
The policy that provides high degree of compatibilty with common cookie management of popular HTTP agents.
BUFFER_WARN_TRIGGER_LIMIT - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Sets the maximum buffered response size (in bytes) that triggers no warning.
ByteArrayPartSource - Class in org.apache.commons.httpclient.methods.multipart
A PartSource that reads from a byte array.
ByteArrayPartSource(String, byte[]) - Constructor for class org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource
Constructor for ByteArrayPartSource.
ByteArrayRequestEntity - Class in org.apache.commons.httpclient.methods
A RequestEntity that contains an array of bytes.
ByteArrayRequestEntity(byte[]) - Constructor for class org.apache.commons.httpclient.methods.ByteArrayRequestEntity
Creates a new entity with the given content.
ByteArrayRequestEntity(byte[], String) - Constructor for class org.apache.commons.httpclient.methods.ByteArrayRequestEntity
Creates a new entity with the given content and content type.

C

CHARSET - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Content charset
CHARSET_BYTES - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Content charset as a byte array
checkNotUsed() - Method in class org.apache.commons.httpclient.HttpMethodBase
Throws an IllegalStateException if the HTTP method has been already executed, but not recycled.
checkUsed() - Method in class org.apache.commons.httpclient.HttpMethodBase
Throws an IllegalStateException if the HTTP method has not been executed since last recycle.
checkValid() - Method in class org.apache.commons.httpclient.HttpsURL
Verify the valid class use for construction.
checkValid() - Method in class org.apache.commons.httpclient.HttpURL
Verify the valid class use for construction.
ChunkedInputStream - Class in org.apache.commons.httpclient
Transparently coalesces chunks of a HTTP stream that uses Transfer-Encoding chunked.
ChunkedInputStream(InputStream, HttpMethod) - Constructor for class org.apache.commons.httpclient.ChunkedInputStream
ChunkedInputStream constructor that associates the chunked input stream with a HTTP method.
ChunkedInputStream(InputStream) - Constructor for class org.apache.commons.httpclient.ChunkedInputStream
ChunkedInputStream constructor
ChunkedOutputStream - Class in org.apache.commons.httpclient
Implements HTTP chunking support.
ChunkedOutputStream(OutputStream, int) - Constructor for class org.apache.commons.httpclient.ChunkedOutputStream
Wraps a stream and chunks the output.
ChunkedOutputStream(OutputStream) - Constructor for class org.apache.commons.httpclient.ChunkedOutputStream
Wraps a stream and chunks the output.
CircularRedirectException - Exception in org.apache.commons.httpclient
Signals a circular redirect
CircularRedirectException() - Constructor for exception org.apache.commons.httpclient.CircularRedirectException
Creates a new CircularRedirectException with a null detail message.
CircularRedirectException(String) - Constructor for exception org.apache.commons.httpclient.CircularRedirectException
Creates a new CircularRedirectException with the specified detail message.
CircularRedirectException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.CircularRedirectException
Creates a new CircularRedirectException with the specified detail message and cause.
clear() - Method in class org.apache.commons.httpclient.HeaderGroup
Removes any contained headers.
clear() - Method in class org.apache.commons.httpclient.HttpState
Clears the state information (all cookies, credentials and proxy credentials).
clear() - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
Removes all parameters from this collection.
clearCookies() - Method in class org.apache.commons.httpclient.HttpState
Clears all cookies.
clearCredentials() - Method in class org.apache.commons.httpclient.HttpState
Clears all credentials.
clearProxyCredentials() - Method in class org.apache.commons.httpclient.HttpState
Clears all proxy credentials.
clearRequestBody() - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Clears the request body.
clearRequestBody() - Method in class org.apache.commons.httpclient.methods.PostMethod
Clears request body.
clone() - Method in class org.apache.commons.httpclient.HostConfiguration
 
clone() - Method in class org.apache.commons.httpclient.HttpHost
 
clone() - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
Clones this collection of parameters.
clone() - Method in class org.apache.commons.httpclient.ProxyHost
 
clone() - Method in class org.apache.commons.httpclient.URI
Create and return a copy of this object, the URI-reference containing the userinfo component.
close() - Method in class org.apache.commons.httpclient.ChunkedInputStream
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.
close() - Method in class org.apache.commons.httpclient.ChunkedOutputStream
Finishes writing to the underlying stream, but does NOT close the underlying stream.
close() - Method in class org.apache.commons.httpclient.ContentLengthInputStream
Reads until the end of the known length of content.
close() - Method in class org.apache.commons.httpclient.HttpConnection
Closes the socket and streams.
closeIdleConnections(long) - Method in interface org.apache.commons.httpclient.HttpConnectionManager
Closes connections that have been idle for at least the given amount of time.
closeIdleConnections(long) - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
 
closeIdleConnections(long) - Method in class org.apache.commons.httpclient.SimpleHttpConnectionManager
 
closeIdleConnections(long) - Method in class org.apache.commons.httpclient.util.IdleConnectionHandler
Closes connections that have been idle for at least the given amount of time.
closeIfStale() - Method in class org.apache.commons.httpclient.HttpConnection
Closes the connection if stale.
closeSocketAndStreams() - Method in class org.apache.commons.httpclient.HttpConnection
Closes everything out.
COMMENT - Static variable in class org.apache.commons.httpclient.cookie.Cookie2
 
COMMENTURL - Static variable in class org.apache.commons.httpclient.cookie.Cookie2
 
compare(Object, Object) - Method in class org.apache.commons.httpclient.Cookie
Compares two cookies to determine order for cookie header.
compare(Object, Object) - Method in class org.apache.commons.httpclient.cookie.CookiePathComparator
 
compareTo(HttpVersion) - Method in class org.apache.commons.httpclient.HttpVersion
Compares this HTTP protocol version with another one.
compareTo(Object) - Method in class org.apache.commons.httpclient.HttpVersion
 
compareTo(Object) - Method in class org.apache.commons.httpclient.URI
Compare this URI to another object.
COMPATIBILITY - Static variable in class org.apache.commons.httpclient.cookie.CookiePolicy
Deprecated. Use CookiePolicy.BROWSER_COMPATIBILITY
connect() - Method in class org.apache.commons.httpclient.ProxyClient
Creates a socket that is connected, via the HTTP CONNECT method, to a proxy.
connect() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not available: the data must have already been retrieved.
CONNECTION_MANAGER_CLASS - Static variable in class org.apache.commons.httpclient.params.HttpClientParams
Defines the default HTTP connection manager class.
CONNECTION_MANAGER_TIMEOUT - Static variable in class org.apache.commons.httpclient.params.HttpClientParams
Sets the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.
CONNECTION_TIMEOUT - Static variable in class org.apache.commons.httpclient.params.HttpConnectionParams
Determines the timeout until a connection is etablished.
ConnectionPoolTimeoutException - Exception in org.apache.commons.httpclient
A timeout while connecting waiting for an available connection from an HttpConnectionManager.
ConnectionPoolTimeoutException() - Constructor for exception org.apache.commons.httpclient.ConnectionPoolTimeoutException
Creates a ConnectTimeoutException with a null detail message.
ConnectionPoolTimeoutException(String) - Constructor for exception org.apache.commons.httpclient.ConnectionPoolTimeoutException
Creates a ConnectTimeoutException with the specified detail message.
ConnectionPoolTimeoutException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.ConnectionPoolTimeoutException
Creates a new ConnectTimeoutException with the specified detail message and cause.
ConnectMethod - Class in org.apache.commons.httpclient
Establishes a tunneled HTTP connection via the CONNECT method.
ConnectMethod() - Constructor for class org.apache.commons.httpclient.ConnectMethod
Deprecated. use #ConnectMethod(HttpHost); Create a connect method.
ConnectMethod(HttpMethod) - Constructor for class org.apache.commons.httpclient.ConnectMethod
Deprecated. the wrapped method is no longer used Create a connect method wrapping the existing method
ConnectMethod(HostConfiguration) - Constructor for class org.apache.commons.httpclient.ConnectMethod
Create a connect method.
ConnectTimeoutException - Exception in org.apache.commons.httpclient
A timeout while connecting to an HTTP server or waiting for an available connection from an HttpConnectionManager.
ConnectTimeoutException() - Constructor for exception org.apache.commons.httpclient.ConnectTimeoutException
Creates a ConnectTimeoutException with a null detail message.
ConnectTimeoutException(String) - Constructor for exception org.apache.commons.httpclient.ConnectTimeoutException
Creates a ConnectTimeoutException with the specified detail message.
ConnectTimeoutException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.ConnectTimeoutException
Creates a new ConnectTimeoutException with the specified detail message and cause.
containsHeader(String) - Method in class org.apache.commons.httpclient.HeaderGroup
Tests if headers with the given name are contained within this group.
CONTENT_DISPOSITION - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Content dispostion characters
CONTENT_DISPOSITION_BYTES - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Content dispostion as a byte array
CONTENT_LENGTH_AUTO - Static variable in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Deprecated. Use InputStreamRequestEntity.CONTENT_LENGTH_AUTO.
CONTENT_LENGTH_AUTO - Static variable in class org.apache.commons.httpclient.methods.InputStreamRequestEntity
The content length will be calculated automatically.
CONTENT_LENGTH_CHUNKED - Static variable in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Deprecated. Use EntityEnclosingMethod.setContentChunked(boolean).
CONTENT_TRANSFER_ENCODING - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Content type header
CONTENT_TRANSFER_ENCODING_BYTES - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Content type header as a byte array
CONTENT_TYPE - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Content type header
CONTENT_TYPE_BYTES - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Content type header as a byte array
ContentLengthInputStream - Class in org.apache.commons.httpclient
Cuts the wrapped InputStream off after a specified number of bytes.
ContentLengthInputStream(InputStream, int) - Constructor for class org.apache.commons.httpclient.ContentLengthInputStream
Deprecated. use ContentLengthInputStream.ContentLengthInputStream(InputStream, long) Creates a new length limited stream
ContentLengthInputStream(InputStream, long) - Constructor for class org.apache.commons.httpclient.ContentLengthInputStream
Creates a new length limited stream
control - Static variable in class org.apache.commons.httpclient.URI
BitSet for control.
ControllerThreadSocketFactory - Class in org.apache.commons.httpclient.protocol
This helper class is intedned to help work around the limitation of older Java versions (older than 1.4) that prevents from specifying a connection timeout when creating a socket.
ControllerThreadSocketFactory.SocketTask - Class in org.apache.commons.httpclient.protocol
Helper class for wrapping socket based tasks.
ControllerThreadSocketFactory.SocketTask() - Constructor for class org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory.SocketTask
 
Cookie - Class in org.apache.commons.httpclient
HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.
Cookie() - Constructor for class org.apache.commons.httpclient.Cookie
Default constructor.
Cookie(String, String, String) - Constructor for class org.apache.commons.httpclient.Cookie
Creates a cookie with the given name, value and domain attribute.
Cookie(String, String, String, String, Date, boolean) - Constructor for class org.apache.commons.httpclient.Cookie
Creates a cookie with the given name, value, domain attribute, path attribute, expiration attribute, and secure attribute
Cookie(String, String, String, String, int, boolean) - Constructor for class org.apache.commons.httpclient.Cookie
Creates a cookie with the given name, value, domain attribute, path attribute, maximum age attribute, and secure attribute
Cookie2 - Class in org.apache.commons.httpclient.cookie
Cookie class for RFC2965Spec cookie specification.
Cookie2() - Constructor for class org.apache.commons.httpclient.cookie.Cookie2
Default constructor.
Cookie2(String, String, String) - Constructor for class org.apache.commons.httpclient.cookie.Cookie2
Creates a cookie with the given name, value and domain attribute.
Cookie2(String, String, String, String, Date, boolean) - Constructor for class org.apache.commons.httpclient.cookie.Cookie2
Creates a cookie with the given name, value, domain attribute, path attribute, expiration attribute, and secure attribute
Cookie2(String, String, String, String, Date, boolean, int[]) - Constructor for class org.apache.commons.httpclient.cookie.Cookie2
Creates a cookie with the given name, value, domain attribute, path attribute, expiration attribute, secure attribute, and ports attribute.
COOKIE_POLICY - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines cookie policy to be used for cookie management.
CookieAttributeHandler - Interface in org.apache.commons.httpclient.cookie
Ths interface represents a cookie attribute handler responsible for parsing, validating, and matching a specific cookie attribute, such as path, domain, port, etc.
CookieOrigin - Class in org.apache.commons.httpclient.cookie
CookieOrigin class incapsulates details of an origin server that are relevant when parsing, validating or matching HTTP cookies.
CookieOrigin(String, int, String, boolean) - Constructor for class org.apache.commons.httpclient.cookie.CookieOrigin
 
CookiePathComparator - Class in org.apache.commons.httpclient.cookie
This cookie comparator ensures that multiple cookies satisfying a common criteria are ordered in the Cookie header such that those with more specific Path attributes precede those with less specific.
CookiePathComparator() - Constructor for class org.apache.commons.httpclient.cookie.CookiePathComparator
 
CookiePolicy - Class in org.apache.commons.httpclient.cookie
Cookie management policy class.
CookiePolicy() - Constructor for class org.apache.commons.httpclient.cookie.CookiePolicy
 
cookies - Variable in class org.apache.commons.httpclient.HttpState
Array of cookies that this HTTP state contains.
CookieSpec - Interface in org.apache.commons.httpclient.cookie
Defines the cookie management specification.
CookieSpecBase - Class in org.apache.commons.httpclient.cookie
Cookie management functions shared by all specification.
CookieSpecBase() - Constructor for class org.apache.commons.httpclient.cookie.CookieSpecBase
Default constructor
CookieVersionSupport - Interface in org.apache.commons.httpclient.cookie
Defines cookie specification specific capabilities
createCnonce() - Static method in class org.apache.commons.httpclient.auth.DigestScheme
Creates a random cnonce value based on the current time.
createInputStream() - Method in class org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource
 
createInputStream() - Method in class org.apache.commons.httpclient.methods.multipart.FilePartSource
Return a new FileInputStream for the current filename.
createInputStream() - Method in interface org.apache.commons.httpclient.methods.multipart.PartSource
Gets a new InputStream for reading this source.
createParams() - Method in class org.apache.commons.httpclient.params.DefaultHttpParamsFactory
 
createSocket(ProtocolSocketFactory, String, int, InetAddress, int, int) - Static method in class org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory
This method spawns a controller thread overseeing the process of socket initialisation.
createSocket(ControllerThreadSocketFactory.SocketTask, int) - Static method in class org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory
 
createSocket(String, int, InetAddress, int) - Method in class org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory
 
createSocket(String, int, InetAddress, int, HttpConnectionParams) - Method in class org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory
Attempts to get a new socket connection to the given host within the given time limit.
createSocket(String, int) - Method in class org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory
 
createSocket(String, int, InetAddress, int) - Method in interface org.apache.commons.httpclient.protocol.ProtocolSocketFactory
Gets a new socket connection to the given host.
createSocket(String, int, InetAddress, int, HttpConnectionParams) - Method in interface org.apache.commons.httpclient.protocol.ProtocolSocketFactory
Gets a new socket connection to the given host.
createSocket(String, int) - Method in interface org.apache.commons.httpclient.protocol.ProtocolSocketFactory
Gets a new socket connection to the given host.
createSocket(String, String, int, InetAddress, int, int) - Static method in class org.apache.commons.httpclient.protocol.ReflectionSocketFactory
This method attempts to execute Socket method available since Java 1.4 using reflection.
createSocket(Socket, String, int, boolean) - Method in interface org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory
Returns a socket connected to the given host that is layered over an existing socket.
createSocket(String, int, InetAddress, int) - Method in class org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory
 
createSocket(String, int, InetAddress, int, HttpConnectionParams) - Method in class org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory
Attempts to get a new socket connection to the given host within the given time limit.
createSocket(String, int) - Method in class org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory
 
createSocket(Socket, String, int, boolean) - Method in class org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory
 
CREDENTIAL_CHARSET - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines the charset to be used when encoding Credentials.
Credentials - Interface in org.apache.commons.httpclient
Authentication credentials.
CredentialsNotAvailableException - Exception in org.apache.commons.httpclient.auth
Authentication credentials required to respond to a authentication challenge are not available
CredentialsNotAvailableException() - Constructor for exception org.apache.commons.httpclient.auth.CredentialsNotAvailableException
Creates a new CredentialsNotAvailableException with a null detail message.
CredentialsNotAvailableException(String) - Constructor for exception org.apache.commons.httpclient.auth.CredentialsNotAvailableException
Creates a new CredentialsNotAvailableException with the specified message.
CredentialsNotAvailableException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.auth.CredentialsNotAvailableException
Creates a new CredentialsNotAvailableException with the specified detail message and cause.
CredentialsProvider - Interface in org.apache.commons.httpclient.auth
Credentials provider interface can be used to provide HTTP method with a means to request authentication credentials if no credentials have been given or given credentials are incorrect.
credMap - Variable in class org.apache.commons.httpclient.HttpState
Map of credentials by realm that this HTTP state contains.
CRLF - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Carriage return/linefeed
CRLF_BYTES - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Carriage return/linefeed as a byte array

D

DATE_PATTERNS - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
The key used to look up the date patterns used for parsing.
DateParseException - Exception in org.apache.commons.httpclient.util
An exception to indicate an error parsing a date string.
DateParseException() - Constructor for exception org.apache.commons.httpclient.util.DateParseException
 
DateParseException(String) - Constructor for exception org.apache.commons.httpclient.util.DateParseException
 
DateParser - Class in org.apache.commons.httpclient.util
Deprecated. Use DateUtil
DateUtil - Class in org.apache.commons.httpclient.util
A utility class for parsing and formatting HTTP dates as used in cookies and other headers.
decode(char[], String) - Static method in class org.apache.commons.httpclient.URI
Decodes URI encoded string.
decode(String, String) - Static method in class org.apache.commons.httpclient.URI
Decodes URI encoded string.
decode(char[], String) - Static method in class org.apache.commons.httpclient.util.URIUtil.Coder
Deprecated. use org.apache.commons.codec.net.URLCodec
decode(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Unescape and decode a given string regarded as an escaped string with the default protocol charset.
decode(String, String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Unescape and decode a given string regarded as an escaped string.
DEFAULT - Static variable in class org.apache.commons.httpclient.cookie.CookiePolicy
The default cookie policy.
DEFAULT_CHARSET - Static variable in class org.apache.commons.httpclient.methods.multipart.FilePart
Default charset of file attachments.
DEFAULT_CHARSET - Static variable in class org.apache.commons.httpclient.methods.multipart.StringPart
Default charset of string parameters
DEFAULT_CONTENT_CHARSET - Static variable in class org.apache.commons.httpclient.HttpConstants
Deprecated. Default content encoding chatset
DEFAULT_CONTENT_TYPE - Static variable in class org.apache.commons.httpclient.methods.multipart.FilePart
Default content encoding of file attachments.
DEFAULT_CONTENT_TYPE - Static variable in class org.apache.commons.httpclient.methods.multipart.StringPart
Default content encoding of string parameters.
DEFAULT_HEADERS - Static variable in class org.apache.commons.httpclient.params.HostParams
Defines the request headers to be sent per default with each request.
DEFAULT_MAX_HOST_CONNECTIONS - Static variable in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
The default maximum number of connections allowed per host
DEFAULT_MAX_TOTAL_CONNECTIONS - Static variable in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
The default maximum number of connections allowed overall
DEFAULT_PORT - Static variable in class org.apache.commons.httpclient.HttpsURL
Default port for HTTPS URL.
DEFAULT_PORT - Static variable in class org.apache.commons.httpclient.HttpURL
Default port for HTTP URL.
DEFAULT_SCHEME - Static variable in class org.apache.commons.httpclient.HttpsURL
Default scheme for HTTPS URL.
DEFAULT_SCHEME - Static variable in class org.apache.commons.httpclient.HttpURL
Default scheme for HTTP URL.
DEFAULT_TRANSFER_ENCODING - Static variable in class org.apache.commons.httpclient.methods.multipart.FilePart
Default transfer encoding of file attachments.
DEFAULT_TRANSFER_ENCODING - Static variable in class org.apache.commons.httpclient.methods.multipart.StringPart
Default transfer encoding of string parameters
defaultDocumentCharset - Static variable in class org.apache.commons.httpclient.URI
The default charset of the document.
defaultDocumentCharsetByLocale - Static variable in class org.apache.commons.httpclient.URI
 
defaultDocumentCharsetByPlatform - Static variable in class org.apache.commons.httpclient.URI
 
DefaultHttpMethodRetryHandler - Class in org.apache.commons.httpclient
The default HttpMethodRetryHandler used by HttpMethods.
DefaultHttpMethodRetryHandler(int, boolean) - Constructor for class org.apache.commons.httpclient.DefaultHttpMethodRetryHandler
Creates a new DefaultHttpMethodRetryHandler.
DefaultHttpMethodRetryHandler() - Constructor for class org.apache.commons.httpclient.DefaultHttpMethodRetryHandler
Creates a new DefaultHttpMethodRetryHandler that retries up to 3 times but does not retry methods that have successfully sent their requests.
DefaultHttpParams - Class in org.apache.commons.httpclient.params
This class represents a collection of HTTP protocol parameters.
DefaultHttpParams(HttpParams) - Constructor for class org.apache.commons.httpclient.params.DefaultHttpParams
Creates a new collection of parameters with the given parent.
DefaultHttpParams() - Constructor for class org.apache.commons.httpclient.params.DefaultHttpParams
Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent.
DefaultHttpParamsFactory - Class in org.apache.commons.httpclient.params
 
DefaultHttpParamsFactory() - Constructor for class org.apache.commons.httpclient.params.DefaultHttpParamsFactory
 
DefaultMethodRetryHandler - Class in org.apache.commons.httpclient
Deprecated. use DefaultHttpMethodRetryHandler
DefaultMethodRetryHandler() - Constructor for class org.apache.commons.httpclient.DefaultMethodRetryHandler
Deprecated.  
defaultProtocolCharset - Static variable in class org.apache.commons.httpclient.URI
The default charset of the protocol.
DefaultProtocolSocketFactory - Class in org.apache.commons.httpclient.protocol
The default class for creating protocol sockets.
DefaultProtocolSocketFactory() - Constructor for class org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory
Constructor for DefaultProtocolSocketFactory.
deleteClosedConnections() - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Deletes all closed connections.
DeleteMethod - Class in org.apache.commons.httpclient.methods
Implements the HTTP DELETE method.
DeleteMethod() - Constructor for class org.apache.commons.httpclient.methods.DeleteMethod
No-arg constructor.
DeleteMethod(String) - Constructor for class org.apache.commons.httpclient.methods.DeleteMethod
Constructor specifying a URI.
delims - Static variable in class org.apache.commons.httpclient.URI
BitSet for delims.
DIGEST - Static variable in class org.apache.commons.httpclient.auth.AuthPolicy
Digest authentication scheme as defined in RFC2617.
DigestScheme - Class in org.apache.commons.httpclient.auth
Digest authentication scheme as defined in RFC 2617.
DigestScheme() - Constructor for class org.apache.commons.httpclient.auth.DigestScheme
Default constructor for the digest authetication scheme.
DigestScheme(String) - Constructor for class org.apache.commons.httpclient.auth.DigestScheme
Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
digit - Static variable in class org.apache.commons.httpclient.URI
BitSet for digit.
disallowed_opaque_part - Static variable in class org.apache.commons.httpclient.URI
Disallowed opaque_part before escaping.
disallowed_rel_path - Static variable in class org.apache.commons.httpclient.URI
Disallowed rel_path before escaping.
DISCARD - Static variable in class org.apache.commons.httpclient.cookie.Cookie2
 
disconnect() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
DOCUMENT_CHARSET - Static variable in exception org.apache.commons.httpclient.URI.DefaultCharsetChanged
Document charset changed.
doit() - Method in class org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory.SocketTask
Perform the logic.
DOMAIN - Static variable in class org.apache.commons.httpclient.cookie.Cookie2
 
domainlabel - Static variable in class org.apache.commons.httpclient.URI
BitSet for domainlabel.
domainMatch(String, String) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Performs domain-match as defined by the cookie specification.
domainMatch(String, String) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Performs domain-match as implemented in common browsers.
domainMatch(String, String) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
 
domainMatch(String, String) - Method in class org.apache.commons.httpclient.cookie.NetscapeDraftSpec
Performs domain-match as described in the Netscape draft.
domainMatch(String, String) - Method in class org.apache.commons.httpclient.cookie.RFC2109Spec
Performs domain-match as defined by the RFC2109.
domainMatch(String, String) - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
Performs domain-match as defined by the RFC2965.

E

effectiveVersion - Variable in class org.apache.commons.httpclient.HttpMethodBase
HTTP protocol version used for execution of this method.
empty - Static variable in class org.apache.commons.httpclient.util.URIUtil
 
encode(String, BitSet, String) - Static method in class org.apache.commons.httpclient.URI
Encodes URI string.
encode(String, BitSet, String) - Static method in class org.apache.commons.httpclient.util.URIUtil.Coder
Deprecated. use org.apache.commons.codec.net.URLCodec
encode(String, BitSet) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a given string with allowed characters not to be escaped and the default protocol charset.
encode(String, BitSet, String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a given string with allowed characters not to be escaped and a given charset.
encodeAll(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Get the all escaped and encoded string with the default protocl charset.
encodeAll(String, String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Get the all escaped and encoded string with a given charset.
encodePath(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as the path component of an URI with the default protocol charset.
encodePath(String, String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as the path component of an URI with a given charset.
encodePathQuery(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as the path and query components of an URI with the default protocol charset.
encodePathQuery(String, String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as the path and query components of an URI with a given charset.
encodeQuery(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as the query component of an URI with the default protocol charset.
encodeQuery(String, String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as the query component of an URI with a given charset.
encodeWithinAuthority(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as within the authority component of an URI with the default protocol charset.
encodeWithinAuthority(String, String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as within the authority component of an URI with a given charset.
encodeWithinPath(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as within the path component of an URI with the default protocol charset.
encodeWithinPath(String, String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as within the path component of an URI with a given charset.
encodeWithinQuery(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as within the query component of an URI with the default protocol charset.
encodeWithinQuery(String, String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Escape and encode a string regarded as within the query component of an URI with a given charset.
EncodingUtil - Class in org.apache.commons.httpclient.util
The home for utility methods that handle various encoding tasks.
EntityEnclosingMethod - Class in org.apache.commons.httpclient.methods
This abstract class serves as a foundation for all HTTP methods that can enclose an entity within requests
EntityEnclosingMethod() - Constructor for class org.apache.commons.httpclient.methods.EntityEnclosingMethod
No-arg constructor.
EntityEnclosingMethod(String) - Constructor for class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Constructor specifying a URI.
equals(Object) - Method in class org.apache.commons.httpclient.auth.AuthSchemeBase
Deprecated.  
equals(Object) - Method in class org.apache.commons.httpclient.auth.AuthScope
 
equals(Object) - Method in class org.apache.commons.httpclient.Cookie
Two cookies are equal if the name, path and domain match.
equals(Object) - Method in class org.apache.commons.httpclient.HostConfiguration
 
equals(Object) - Method in class org.apache.commons.httpclient.HttpHost
 
equals(Object) - Method in class org.apache.commons.httpclient.HttpVersion
 
equals(HttpVersion) - Method in class org.apache.commons.httpclient.HttpVersion
Test if the HTTP protocol version is equal to the given number.
equals(Object) - Method in class org.apache.commons.httpclient.NameValuePair
 
equals(Object) - Method in class org.apache.commons.httpclient.NTCredentials
Performs a case-sensitive check to see if the components of the credentials are the same.
equals(Object) - Method in class org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory
All instances of DefaultProtocolSocketFactory are the same.
equals(Object) - Method in class org.apache.commons.httpclient.protocol.Protocol
Return true if the specified object equals this object.
equals(Object) - Method in class org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory
All instances of SSLProtocolSocketFactory are the same.
equals(char[], char[]) - Method in class org.apache.commons.httpclient.URI
Test if the first array is equal to the second array.
equals(Object) - Method in class org.apache.commons.httpclient.URI
Test an object if this URI is equal to another.
equals(Object) - Method in class org.apache.commons.httpclient.UsernamePasswordCredentials
These credentials are assumed equal if the username and password are the same.
equals(Object, Object) - Static method in class org.apache.commons.httpclient.util.LangUtils
 
escaped - Static variable in class org.apache.commons.httpclient.URI
BitSet for escaped.
ESCAPING - Static variable in exception org.apache.commons.httpclient.URIException
The URI escape encoding and decoding error.
ExceptionUtil - Class in org.apache.commons.httpclient.util
The home for utility methods that handle various exception-related tasks.
ExceptionUtil() - Constructor for class org.apache.commons.httpclient.util.ExceptionUtil
 
execute(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.ConnectMethod
Execute this method and create a tunneled HttpConnection.
execute(HttpState, HttpConnection) - Method in interface org.apache.commons.httpclient.HttpMethod
Executes this method using the specified HttpConnection and HttpState.
execute(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Executes this method using the specified HttpConnection and HttpState.
execute(Thread, long) - Static method in class org.apache.commons.httpclient.util.TimeoutController
Executes task.
execute(Runnable, long) - Static method in class org.apache.commons.httpclient.util.TimeoutController
Executes task in a new deamon Thread and waits for the timeout.
executeMethod(HttpMethod) - Method in class org.apache.commons.httpclient.HttpClient
Executes the given HTTP method.
executeMethod(HostConfiguration, HttpMethod) - Method in class org.apache.commons.httpclient.HttpClient
Executes the given HTTP method using custom host configuration.
executeMethod(HostConfiguration, HttpMethod, HttpState) - Method in class org.apache.commons.httpclient.HttpClient
Executes the given HTTP method using the given custom host configuration with the given custom HTTP state.
ExpectContinueMethod - Class in org.apache.commons.httpclient.methods
This abstract class serves as a foundation for all HTTP methods that support 'Expect: 100-continue' handshake.
ExpectContinueMethod() - Constructor for class org.apache.commons.httpclient.methods.ExpectContinueMethod
No-arg constructor.
ExpectContinueMethod(String) - Constructor for class org.apache.commons.httpclient.methods.ExpectContinueMethod
Constructor specifying a URI.
EXTRA - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Extra characters
EXTRA_BYTES - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Extra characters as a byte array
extractParams(String) - Static method in class org.apache.commons.httpclient.auth.AuthChallengeParser
Extracts a map of challenge parameters from an authentication challenge.
extractScheme(String) - Static method in class org.apache.commons.httpclient.auth.AuthChallengeParser
Extracts authentication scheme from the given authentication challenge.

F

FILE_NAME - Static variable in class org.apache.commons.httpclient.methods.multipart.FilePart
Attachment's file name
FilePart - Class in org.apache.commons.httpclient.methods.multipart
This class implements a part of a Multipart post object that consists of a file.
FilePart(String, PartSource, String, String) - Constructor for class org.apache.commons.httpclient.methods.multipart.FilePart
FilePart Constructor.
FilePart(String, PartSource) - Constructor for class org.apache.commons.httpclient.methods.multipart.FilePart
FilePart Constructor.
FilePart(String, File) - Constructor for class org.apache.commons.httpclient.methods.multipart.FilePart
FilePart Constructor.
FilePart(String, File, String, String) - Constructor for class org.apache.commons.httpclient.methods.multipart.FilePart
FilePart Constructor.
FilePart(String, String, File) - Constructor for class org.apache.commons.httpclient.methods.multipart.FilePart
FilePart Constructor.
FilePart(String, String, File, String, String) - Constructor for class org.apache.commons.httpclient.methods.multipart.FilePart
FilePart Constructor.
FilePartSource - Class in org.apache.commons.httpclient.methods.multipart
A PartSource that reads from a File.
FilePartSource(File) - Constructor for class org.apache.commons.httpclient.methods.multipart.FilePartSource
Constructor for FilePartSource.
FilePartSource(String, File) - Constructor for class org.apache.commons.httpclient.methods.multipart.FilePartSource
Constructor for FilePartSource.
FileRequestEntity - Class in org.apache.commons.httpclient.methods
A RequestEntity that represents a File.
FileRequestEntity(File, String) - Constructor for class org.apache.commons.httpclient.methods.FileRequestEntity
 
findAttribHandler(String) - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
Finds an attribute handler CookieAttributeHandler for the given attribute.
finish() - Method in class org.apache.commons.httpclient.ChunkedOutputStream
Must be called to ensure the internal cache is flushed and the closing chunk is written.
flush() - Method in class org.apache.commons.httpclient.ChunkedOutputStream
Flushes the underlying stream, but leaves the internal buffer alone.
flushCache() - Method in class org.apache.commons.httpclient.ChunkedOutputStream
Writes the cache out onto the underlying stream
flushCacheWithAppend(byte[], int, int) - Method in class org.apache.commons.httpclient.ChunkedOutputStream
Writes the cache and bufferToAppend to the underlying stream as one large chunk
flushRequestOutputStream() - Method in class org.apache.commons.httpclient.HttpConnection
Flushes the output request stream.
FORM_URL_ENCODED_CONTENT_TYPE - Static variable in class org.apache.commons.httpclient.methods.PostMethod
The Content-Type for www-form-urlencoded.
format(StringBuffer, NameValuePair) - Method in class org.apache.commons.httpclient.util.ParameterFormatter
Produces textual representaion of the attribute/value pair using formatting rules defined in RFC 2616
format(NameValuePair) - Method in class org.apache.commons.httpclient.util.ParameterFormatter
Produces textual representaion of the attribute/value pair using formatting rules defined in RFC 2616
formatCookie(Cookie) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Create a "Cookie" header value for an array of cookies.
formatCookie(Cookie) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Return a string suitable for sending in a "Cookie" header
formatCookie(Cookie) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
 
formatCookie(Cookie) - Method in class org.apache.commons.httpclient.cookie.RFC2109Spec
Return a string suitable for sending in a "Cookie" header as defined in RFC 2109
formatCookie(Cookie) - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
Return a string suitable for sending in a "Cookie" header as defined in RFC 2965
formatCookieHeader(Cookie[]) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Create a "Cookie" Header for an array of Cookies.
formatCookieHeader(Cookie) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Create a "Cookie" Header for single Cookie.
formatCookieHeader(Cookie[]) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Create a "Cookie" Header containing all Cookies in cookies.
formatCookieHeader(Cookie) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Create a "Cookie" Header containing the Cookie.
formatCookieHeader(Cookie) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
 
formatCookieHeader(Cookie[]) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
 
formatCookies(Cookie[]) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Create a "Cookie" header value for an array of cookies.
formatCookies(Cookie[]) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Create a "Cookie" header value containing all Cookies in cookies suitable for sending in a "Cookie" header
formatCookies(Cookie[]) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
 
formatCookies(Cookie[]) - Method in class org.apache.commons.httpclient.cookie.RFC2109Spec
Create a RFC 2109 compliant "Cookie" header value containing all Cookies in cookies suitable for sending in a "Cookie" header
formatCookies(Cookie[]) - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
Create a RFC 2965 compliant "Cookie" header value containing all Cookies suitable for sending in a "Cookie" header
formatDate(Date) - Static method in class org.apache.commons.httpclient.util.DateUtil
Formats the given date according to the RFC 1123 pattern.
formatDate(Date, String) - Static method in class org.apache.commons.httpclient.util.DateUtil
Formats the given date according to the specified pattern.
formatValue(StringBuffer, String, boolean) - Static method in class org.apache.commons.httpclient.util.ParameterFormatter
Formats the given parameter value using formatting rules defined in RFC 2616
formUrlEncode(NameValuePair[], String) - Static method in class org.apache.commons.httpclient.util.EncodingUtil
Form-urlencoding routine.
fragment - Static variable in class org.apache.commons.httpclient.URI
BitSet for fragment (alias for uric).

G

generateRequestBody() - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Generates the request body.
generateRequestEntity() - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
 
generateRequestEntity() - Method in class org.apache.commons.httpclient.methods.PostMethod
Generates a request entity from the post parameters, if present.
generateRequestLine(HttpConnection, String, String, String, String) - Static method in class org.apache.commons.httpclient.HttpMethodBase
Generates HTTP request line according to the specified attributes.
getAboveHierPath() - Method in class org.apache.commons.httpclient.URI
Get the level above the this hierarchy level.
getAllHeaders() - Method in class org.apache.commons.httpclient.HeaderGroup
Gets all of the headers contained within this group.
getAllowedMethods() - Method in class org.apache.commons.httpclient.methods.OptionsMethod
Get a list of allowed methods.
getAllowUserInteraction() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
getAsciiBytes(String) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the specified string to byte array of ASCII characters.
getAsciiBytes(String) - Static method in class org.apache.commons.httpclient.util.EncodingUtil
Converts the specified string to byte array of ASCII characters.
getAsciiString(byte[], int, int) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the byte array of ASCII characters to a string.
getAsciiString(byte[]) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the byte array of ASCII characters to a string.
getAsciiString(byte[], int, int) - Static method in class org.apache.commons.httpclient.util.EncodingUtil
Converts the byte array of ASCII characters to a string.
getAsciiString(byte[]) - Static method in class org.apache.commons.httpclient.util.EncodingUtil
Converts the byte array of ASCII characters to a string.
getAttribHandler(String) - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
Gets attribute handler CookieAttributeHandler for the given attribute.
getAttribHandlerIterator() - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
 
getAuthenticationRealm() - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. use #getHostAuthState()
getAuthority() - Method in class org.apache.commons.httpclient.URI
Get the authority.
getAuthScheme(String) - Static method in class org.apache.commons.httpclient.auth.AuthPolicy
Gets the authentication scheme with the given ID.
getAuthScheme() - Method in class org.apache.commons.httpclient.auth.AuthState
Returns the authentication scheme.
getBodyCheckTimeout() - Method in class org.apache.commons.httpclient.methods.HeadMethod
Deprecated. Use HttpMethodParams
getBooleanParameter(String, boolean) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
getBooleanParameter(String, boolean) - Method in interface org.apache.commons.httpclient.params.HttpParams
Returns a Boolean parameter value with the given name.
getBoundary() - Static method in class org.apache.commons.httpclient.methods.multipart.Part
Deprecated. uses a constant string. Rather use Part.getPartBoundary()
getBytes(String) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the specified string to a byte array of HTTP element characters.
getBytes(String, String) - Static method in class org.apache.commons.httpclient.util.EncodingUtil
Converts the specified string to a byte array.
getCause() - Method in exception org.apache.commons.httpclient.HttpException
Return the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable.
getCharSet() - Method in class org.apache.commons.httpclient.methods.multipart.Part
Return the character encoding of this part.
getCharSet() - Method in class org.apache.commons.httpclient.methods.multipart.PartBase
Return the character encoding of this part.
getCharset() - Method in class org.apache.commons.httpclient.methods.StringRequestEntity
 
getCharset(Locale) - Static method in class org.apache.commons.httpclient.URI.LocaleToCharsetMap
Get the preferred charset for the given locale.
getComment() - Method in class org.apache.commons.httpclient.Cookie
Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.
getCommentURL() - Method in class org.apache.commons.httpclient.cookie.Cookie2
If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL.
getCompatibilitySpec() - Static method in class org.apache.commons.httpclient.cookie.CookiePolicy
Deprecated. Use CookiePolicy.getCookieSpec(String)
getCondensedHeader(String) - Method in class org.apache.commons.httpclient.HeaderGroup
Gets a header representing all of the header values with the given name.
getConnection(HostConfiguration) - Method in interface org.apache.commons.httpclient.HttpConnectionManager
Gets an HttpConnection for a given host configuration.
getConnection(HostConfiguration, long) - Method in interface org.apache.commons.httpclient.HttpConnectionManager
Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
getConnection(HostConfiguration) - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
 
getConnection(HostConfiguration, long) - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
getConnection(HostConfiguration) - Method in class org.apache.commons.httpclient.SimpleHttpConnectionManager
 
getConnection(HostConfiguration, long) - Method in class org.apache.commons.httpclient.SimpleHttpConnectionManager
Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
getConnectionManagerClass() - Method in class org.apache.commons.httpclient.params.HttpClientParams
Returns the default HTTP connection manager class.
getConnectionManagerTimeout() - Method in class org.apache.commons.httpclient.params.HttpClientParams
Returns the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.
getConnectionsInPool(HostConfiguration) - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Gets the total number of pooled connections for the given host configuration.
getConnectionsInPool() - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Gets the total number of pooled connections.
getConnectionsInUse(HostConfiguration) - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Deprecated. Use MultiThreadedHttpConnectionManager.getConnectionsInPool(HostConfiguration)
getConnectionsInUse() - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Deprecated. Use MultiThreadedHttpConnectionManager.getConnectionsInPool()
getConnectionTimeout() - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Returns the timeout until a connection is etablished.
getConnectionWithTimeout(HostConfiguration, long) - Method in interface org.apache.commons.httpclient.HttpConnectionManager
Gets an HttpConnection for a given host configuration.
getConnectionWithTimeout(HostConfiguration, long) - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Gets a connection or waits if one is not available.
getConnectionWithTimeout(HostConfiguration, long) - Method in class org.apache.commons.httpclient.SimpleHttpConnectionManager
This method always returns the same connection object.
getConnectMethod() - Method in class org.apache.commons.httpclient.ProxyClient.ConnectResponse
Gets the method that was used to execute the connect.
getContent() - Method in class org.apache.commons.httpclient.methods.ByteArrayRequestEntity
 
getContent() - Method in class org.apache.commons.httpclient.methods.InputStreamRequestEntity
 
getContent() - Method in class org.apache.commons.httpclient.methods.StringRequestEntity
 
getContent() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
getContent(Class[]) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
getContentBytes(String, String) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the specified string to a byte array of HTTP content charachetrs This method is to be used when encoding content of HTTP request/response If the specified charset is not supported, default HTTP content encoding (ISO-8859-1) is applied
getContentBytes(String) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the specified string to a byte array of HTTP content characters using default HTTP content encoding (ISO-8859-1) This method is to be used when encoding content of HTTP request/response
getContentCharSet(Header) - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the character set from the Content-Type header.
getContentCharset() - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Returns the default charset to be used for writing content body, when no charset explicitly specified.
getContentLength() - Method in class org.apache.commons.httpclient.methods.ByteArrayRequestEntity
 
getContentLength() - Method in class org.apache.commons.httpclient.methods.FileRequestEntity
 
getContentLength() - Method in class org.apache.commons.httpclient.methods.InputStreamRequestEntity
Gets the content length.
getContentLength() - Method in class org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity
 
getContentLength() - Method in interface org.apache.commons.httpclient.methods.RequestEntity
Gets the request entity's length.
getContentLength() - Method in class org.apache.commons.httpclient.methods.StringRequestEntity
 
getContentString(byte[], int, int, String) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the byte array of HTTP content characters to a string This method is to be used when decoding content of HTTP request/response If the specified charset is not supported, default HTTP content encoding (ISO-8859-1) is applied
getContentString(byte[], String) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the byte array of HTTP content characters to a string This method is to be used when decoding content of HTTP request/response If the specified charset is not supported, default HTTP content encoding (ISO-8859-1) is applied
getContentString(byte[], int, int) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the byte array of HTTP content characters to a string using default HTTP content encoding (ISO-8859-1) This method is to be used when decoding content of HTTP request/response
getContentString(byte[]) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the byte array of HTTP content characters to a string using default HTTP content encoding (ISO-8859-1) This method is to be used when decoding content of HTTP request/response
getContentType() - Method in class org.apache.commons.httpclient.methods.ByteArrayRequestEntity
 
getContentType() - Method in class org.apache.commons.httpclient.methods.FileRequestEntity
 
getContentType() - Method in class org.apache.commons.httpclient.methods.InputStreamRequestEntity
 
getContentType() - Method in class org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity
 
getContentType() - Method in class org.apache.commons.httpclient.methods.multipart.Part
Returns the content type of this part.
getContentType() - Method in class org.apache.commons.httpclient.methods.multipart.PartBase
Returns the content type of this part.
getContentType() - Method in interface org.apache.commons.httpclient.methods.RequestEntity
Gets the entity's content type.
getContentType() - Method in class org.apache.commons.httpclient.methods.StringRequestEntity
 
getCookiePolicy() - Method in class org.apache.commons.httpclient.HttpState
Deprecated. Use HttpMethodParams.getCookiePolicy(), HttpMethod.getParams().
getCookiePolicy() - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Returns cookie policy to be used by the HTTP methods this collection of parameters applies to.
getCookies() - Method in class org.apache.commons.httpclient.HttpState
Returns an array of cookies that this HTTP state currently contains.
getCookies(String, int, String, boolean) - Method in class org.apache.commons.httpclient.HttpState
Deprecated. use CookieSpec#match(String, int, String, boolean, Cookie)
getCookieSpec(String) - Static method in class org.apache.commons.httpclient.cookie.CookiePolicy
Gets the cookie specification with the given ID.
getCredentialCharset() - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Returns the charset to be used for Credentials.
getCredentials(AuthScheme, String, int, boolean) - Method in interface org.apache.commons.httpclient.auth.CredentialsProvider
Requests additional authentication credentials.
getCredentials(String, String) - Method in class org.apache.commons.httpclient.HttpState
Deprecated. use #getCredentials(AuthScope)
getCredentials(AuthScope) - Method in class org.apache.commons.httpclient.HttpState
Get the credentials for the given authentication scope.
getCurrentHierPath() - Method in class org.apache.commons.httpclient.URI
Get the current hierarchy level.
getDefaultAuthPrefs() - Static method in class org.apache.commons.httpclient.auth.AuthPolicy
Returns a list containing all registered authentication schemes in their default order.
getDefaultDocumentCharset() - Static method in class org.apache.commons.httpclient.URI
Get the recommended default charset of the document.
getDefaultDocumentCharsetByLocale() - Static method in class org.apache.commons.httpclient.URI
Get the default charset of the document by locale.
getDefaultDocumentCharsetByPlatform() - Static method in class org.apache.commons.httpclient.URI
Get the default charset of the document by platform.
getDefaultMaxConnectionsPerHost() - Method in class org.apache.commons.httpclient.params.HttpConnectionManagerParams
Gets the default maximum number of connections allowed for a given host config.
getDefaultParams() - Static method in class org.apache.commons.httpclient.params.DefaultHttpParams
Gets the default HttpParams to be used.
getDefaultParams() - Method in class org.apache.commons.httpclient.params.DefaultHttpParamsFactory
 
getDefaultParams() - Method in interface org.apache.commons.httpclient.params.HttpParamsFactory
Gets the default parameters.
getDefaultPolicy() - Static method in class org.apache.commons.httpclient.cookie.CookiePolicy
Deprecated. Use CookiePolicy.getDefaultSpec()
getDefaultPort() - Method in class org.apache.commons.httpclient.protocol.Protocol
Returns the defaultPort.
getDefaultProtocolCharset() - Static method in class org.apache.commons.httpclient.URI
Get the default charset of the protocol.
getDefaults() - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
getDefaults() - Method in interface org.apache.commons.httpclient.params.HttpParams
Returns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself
getDefaultSpec() - Static method in class org.apache.commons.httpclient.cookie.CookiePolicy
Returns cookie specification registered as CookiePolicy.DEFAULT.
getDefaultUseCaches() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not available: the data must have already been retrieved.
getDoAuthentication() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns true if the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.), false otherwise
getDoAuthentication() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns true if the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.), false otherwise
getDoInput() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
getDomain() - Method in class org.apache.commons.httpclient.Cookie
Returns domain attribute of the cookie.
getDomain() - Method in class org.apache.commons.httpclient.NTCredentials
Retrieves the name to authenticate with.
getDoOutput() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
getDoubleParameter(String, double) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
getDoubleParameter(String, double) - Method in interface org.apache.commons.httpclient.params.HttpParams
Returns a Double parameter value with the given name.
getEffectiveVersion() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the HTTP version used with this method (may be null if undefined, that is, the method has not been executed)
getElements() - Method in class org.apache.commons.httpclient.Header
Returns an array of HeaderElements constructed from my value.
getErrorStream() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
getEscapedAboveHierPath() - Method in class org.apache.commons.httpclient.URI
Get the level above the this hierarchy level.
getEscapedAuthority() - Method in class org.apache.commons.httpclient.URI
Get the escaped authority.
getEscapedCurrentHierPath() - Method in class org.apache.commons.httpclient.URI
Get the escaped current hierarchy level.
getEscapedFragment() - Method in class org.apache.commons.httpclient.URI
Get the escaped fragment.
getEscapedName() - Method in class org.apache.commons.httpclient.URI
Get the escaped basename of the path.
getEscapedPassword() - Method in class org.apache.commons.httpclient.HttpURL
Get the escaped password.
getEscapedPath() - Method in class org.apache.commons.httpclient.URI
Get the escaped path.
getEscapedPathQuery() - Method in class org.apache.commons.httpclient.URI
Get the escaped query.
getEscapedQuery() - Method in class org.apache.commons.httpclient.URI
Get the escaped query.
getEscapedURI() - Method in class org.apache.commons.httpclient.URI
It can be gotten the URI character sequence.
getEscapedURIReference() - Method in class org.apache.commons.httpclient.URI
Get the escaped URI reference string.
getEscapedUser() - Method in class org.apache.commons.httpclient.HttpURL
Get the escaped user
getEscapedUserinfo() - Method in class org.apache.commons.httpclient.URI
Get the escaped userinfo.
getExpiryDate() - Method in class org.apache.commons.httpclient.Cookie
Returns the expiration Date of the cookie, or null if none exists.
getFileName() - Method in class org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource
 
getFileName() - Method in class org.apache.commons.httpclient.methods.multipart.FilePartSource
Return the current filename
getFileName() - Method in interface org.apache.commons.httpclient.methods.multipart.PartSource
Gets the name of the file this source represents.
getFirstHeader(String) - Method in class org.apache.commons.httpclient.HeaderGroup
Gets the first header with the given name.
getFollowRedirects() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns true if the HTTP method should automatically follow HTTP redirects (status code 302, etc.), false otherwise.
getFollowRedirects() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns true if the HTTP method should automatically follow HTTP redirects (status code 302, etc.), false otherwise.
getFollowRedirects() - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Entity enclosing requests cannot be redirected without user intervention according to RFC 2616.
getFragment() - Method in class org.apache.commons.httpclient.URI
Get the fragment.
getFromPath(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Get the path of an URI and its rest part.
getHeaderField(String) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Return the header field
getHeaderField(int) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Return the header field at the specified position
getHeaderFieldKey(int) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Return the header field key
getHeaders(String) - Method in class org.apache.commons.httpclient.HeaderGroup
Gets all of the headers with the given name.
getHost() - Method in class org.apache.commons.httpclient.auth.AuthScope
 
getHost() - Method in class org.apache.commons.httpclient.cookie.CookieOrigin
 
getHost() - Method in class org.apache.commons.httpclient.HostConfiguration
Returns the host.
getHost() - Method in class org.apache.commons.httpclient.HttpClient
Deprecated. use #getHostConfiguration()
getHost() - Method in class org.apache.commons.httpclient.HttpConnection
Returns the host.
getHost() - Method in class org.apache.commons.httpclient.NTCredentials
Retrieves the host name of the computer originating the request.
getHost() - Method in class org.apache.commons.httpclient.URI
Get the host.
getHostAuthState() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the target host authentication state
getHostAuthState() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the target host authentication state
getHostConfiguration() - Method in class org.apache.commons.httpclient.HttpClient
Returns the host configuration associated with the HttpClient.
getHostConfiguration() - Method in interface org.apache.commons.httpclient.HttpMethod
Deprecated. no longer applicable
getHostConfiguration() - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. no longer applicable
getHostConfiguration() - Method in class org.apache.commons.httpclient.ProxyClient
Returns the host configuration associated with the ProxyClient.
getHostName() - Method in class org.apache.commons.httpclient.HttpHost
Returns the host name (IP or DNS name).
getHostURL() - Method in class org.apache.commons.httpclient.HostConfiguration
Return the host url.
getHttpConnectionManager() - Method in class org.apache.commons.httpclient.HttpClient
Returns the HTTP connection manager associated with the HttpClient.
getHttpConnectionManager() - Method in class org.apache.commons.httpclient.HttpConnection
Returns the httpConnectionManager.
getHttpElementCharset() - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Returns the charset to be used for writing HTTP headers.
getHttpVersion() - Method in class org.apache.commons.httpclient.StatusLine
 
getID() - Method in interface org.apache.commons.httpclient.auth.AuthScheme
Deprecated. no longer used
getID() - Method in class org.apache.commons.httpclient.auth.DigestScheme
Deprecated. no longer used
getID() - Method in class org.apache.commons.httpclient.auth.NTLMScheme
Deprecated. no longer used
getID() - Method in class org.apache.commons.httpclient.auth.RFC2617Scheme
Deprecated. no longer used
getIfModifiedSince() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
getInputStream() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Gets an input stream for the HttpMethod response body.
getInstanceFollowRedirects() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
getIntParameter(String, int) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
getIntParameter(String, int) - Method in interface org.apache.commons.httpclient.params.HttpParams
Returns an Integer parameter value with the given name.
getIterator() - Method in class org.apache.commons.httpclient.HeaderGroup
Returns an iterator over this group of headers.
getLastHeader(String) - Method in class org.apache.commons.httpclient.HeaderGroup
Gets the last header with the given name.
getLastResponseInputStream() - Method in class org.apache.commons.httpclient.HttpConnection
Returns the stream used to read the last response's body.
getLength() - Method in class org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource
 
getLength() - Method in class org.apache.commons.httpclient.methods.multipart.FilePartSource
Return the length of the file
getLength() - Method in interface org.apache.commons.httpclient.methods.multipart.PartSource
Gets the number of bytes contained in this source.
getLengthOfParts(Part[]) - Static method in class org.apache.commons.httpclient.methods.multipart.Part
Return the total sum of all parts and that of the last boundary
getLengthOfParts(Part[], byte[]) - Static method in class org.apache.commons.httpclient.methods.multipart.Part
Gets the length of the multipart message including the given parts.
getLinger() - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Returns linger-on-close timeout.
getLocalAddress() - Method in class org.apache.commons.httpclient.HostConfiguration
Return the local address to be used when creating connections.
getLocalAddress() - Method in class org.apache.commons.httpclient.HttpConnection
Return the local address used when creating the connection.
getLocation() - Method in exception org.apache.commons.httpclient.InvalidRedirectLocationException
 
getLongParameter(String, long) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
getLongParameter(String, long) - Method in interface org.apache.commons.httpclient.params.HttpParams
Returns a Long parameter value with the given name.
getMajor() - Method in class org.apache.commons.httpclient.HttpVersion
Returns the major version number of the HTTP protocol.
getMaxConnectionsPerHost() - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Deprecated. Use HttpConnectionManagerParams.getDefaultMaxConnectionsPerHost(), HttpConnectionManager.getParams().
getMaxConnectionsPerHost(HostConfiguration) - Method in class org.apache.commons.httpclient.params.HttpConnectionManagerParams
Gets the maximum number of connections to be used for a particular host config.
getMaxLength() - Method in exception org.apache.commons.httpclient.HttpContentTooLargeException
 
getMaxTotalConnections() - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Deprecated. Use HttpConnectionManagerParams.getMaxTotalConnections(), HttpConnectionManager.getParams().
getMaxTotalConnections() - Method in class org.apache.commons.httpclient.params.HttpConnectionManagerParams
Gets the maximum number of connections allowed.
GetMethod - Class in org.apache.commons.httpclient.methods
Implements the HTTP GET method.
GetMethod() - Constructor for class org.apache.commons.httpclient.methods.GetMethod
No-arg constructor.
GetMethod(String) - Constructor for class org.apache.commons.httpclient.methods.GetMethod
Constructor specifying a URI.
getMethodRetryHandler() - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. use HttpMethodParams
getMinor() - Method in class org.apache.commons.httpclient.HttpVersion
Returns the minor version number of the HTTP protocol.
getMultipartBoundary() - Method in class org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity
Returns the MIME boundary string that is used to demarcate boundaries of this part.
getName() - Method in class org.apache.commons.httpclient.ConnectMethod
Provide the name of this method.
getName() - Method in interface org.apache.commons.httpclient.HttpMethod
Obtains the name of the HTTP method as used in the HTTP request line, for example "GET" or "POST".
getName() - Method in class org.apache.commons.httpclient.HttpMethodBase
Obtains the name of the HTTP method as used in the HTTP request line, for example "GET" or "POST".
getName() - Method in class org.apache.commons.httpclient.methods.DeleteMethod
Returns "DELETE".
getName() - Method in class org.apache.commons.httpclient.methods.GetMethod
Returns "GET".
getName() - Method in class org.apache.commons.httpclient.methods.HeadMethod
Returns "HEAD".
getName() - Method in class org.apache.commons.httpclient.methods.multipart.Part
Return the name of this part.
getName() - Method in class org.apache.commons.httpclient.methods.multipart.PartBase
Returns the name.
getName() - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Returns "POST".
getName() - Method in class org.apache.commons.httpclient.methods.OptionsMethod
Get the name.
getName() - Method in class org.apache.commons.httpclient.methods.PostMethod
Returns "POST".
getName() - Method in class org.apache.commons.httpclient.methods.PutMethod
Return "PUT".
getName() - Method in class org.apache.commons.httpclient.methods.TraceMethod
Returns "TRACE".
getName() - Method in class org.apache.commons.httpclient.NameValuePair
Return the name.
getName() - Method in class org.apache.commons.httpclient.URI
Get the basename of the path.
getName(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Get the basename of an URI.
getOutputStream() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
 
getParameter(String) - Method in interface org.apache.commons.httpclient.auth.AuthScheme
Returns authentication parameter with the given name, if available.
getParameter(String) - Method in class org.apache.commons.httpclient.auth.NTLMScheme
Returns the authentication parameter with the given name, if available.
getParameter(String) - Method in class org.apache.commons.httpclient.auth.RFC2617Scheme
Returns authentication parameter with the given name, if available.
getParameter(String) - Method in class org.apache.commons.httpclient.methods.PostMethod
Gets the parameter of the specified name.
getParameter(String) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
getParameter(String) - Method in interface org.apache.commons.httpclient.params.HttpParams
Returns a parameter value with the given name.
getParameterByName(String) - Method in class org.apache.commons.httpclient.HeaderElement
Returns parameter with the given name, if found.
getParameters() - Method in class org.apache.commons.httpclient.auth.RFC2617Scheme
Returns authentication parameters map.
getParameters() - Method in class org.apache.commons.httpclient.HeaderElement
Get parameters, if any.
getParameters() - Method in class org.apache.commons.httpclient.methods.PostMethod
Gets the parameters currently added to the PostMethod.
getParams() - Method in class org.apache.commons.httpclient.HostConfiguration
Returns HTTP protocol parameters associated with this host.
getParams() - Method in class org.apache.commons.httpclient.HttpClient
Returns HTTP protocol parameters associated with this HttpClient.
getParams() - Method in class org.apache.commons.httpclient.HttpConnection
Returns HTTP protocol parameters associated with this method.
getParams() - Method in interface org.apache.commons.httpclient.HttpConnectionManager
Returns parameters associated with this connection manager.
getParams() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns HTTP protocol parameters associated with this method.
getParams() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns HTTP protocol parameters associated with this method.
getParams() - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Returns parameters associated with this connection manager.
getParams() - Method in class org.apache.commons.httpclient.ProxyClient
Returns HTTP protocol parameters associated with this ProxyClient.
getParams() - Method in class org.apache.commons.httpclient.SimpleHttpConnectionManager
Returns parameters associated with this connection manager.
getPartBoundary() - Method in class org.apache.commons.httpclient.methods.multipart.Part
Gets the part boundary to be used.
getParts() - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Returns all parts.
getPassword() - Method in class org.apache.commons.httpclient.HttpURL
Get the password.
getPassword() - Method in class org.apache.commons.httpclient.UsernamePasswordCredentials
Password property getter.
getPath() - Method in class org.apache.commons.httpclient.ConnectMethod
 
getPath() - Method in class org.apache.commons.httpclient.cookie.CookieOrigin
 
getPath() - Method in class org.apache.commons.httpclient.Cookie
Returns the path attribute of the cookie
getPath() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the path of the HTTP method.
getPath() - Method in class org.apache.commons.httpclient.HttpMethodBase
Gets the path of this HTTP method.
getPath() - Method in class org.apache.commons.httpclient.URI
Get the path.
getPath(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Get the path of an URI.
getPathQuery() - Method in class org.apache.commons.httpclient.URI
Get the path and query.
getPathQuery(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Get the path and query of an URI.
getPermission() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
getPort() - Method in class org.apache.commons.httpclient.auth.AuthScope
 
getPort() - Method in class org.apache.commons.httpclient.cookie.CookieOrigin
 
getPort() - Method in class org.apache.commons.httpclient.HostConfiguration
Returns the port.
getPort() - Method in class org.apache.commons.httpclient.HttpClient
Deprecated. use #getHostConfiguration()
getPort() - Method in class org.apache.commons.httpclient.HttpConnection
Returns the port of the host.
getPort() - Method in class org.apache.commons.httpclient.HttpHost
Returns the port.
getPort() - Method in class org.apache.commons.httpclient.HttpsURL
Get the port number.
getPort() - Method in class org.apache.commons.httpclient.HttpURL
Get the port number.
getPort() - Method in class org.apache.commons.httpclient.URI
Get the port.
getPorts() - Method in class org.apache.commons.httpclient.cookie.Cookie2
Get the Port attribute.
getProtocol() - Method in class org.apache.commons.httpclient.HostConfiguration
Returns the protocol.
getProtocol() - Method in class org.apache.commons.httpclient.HttpConnection
Returns the protocol used to establish the connection.
getProtocol() - Method in class org.apache.commons.httpclient.HttpHost
Returns the protocol.
getProtocol(String) - Static method in class org.apache.commons.httpclient.protocol.Protocol
Gets the protocol with the given ID.
getProtocolCharset() - Method in class org.apache.commons.httpclient.URI
Get the protocol charset used by this current URI instance.
getProxyAuthenticationRealm() - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. use #getProxyAuthState()
getProxyAuthState() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the proxy authentication state
getProxyAuthState() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the proxy authentication state
getProxyCredentials(String, String) - Method in class org.apache.commons.httpclient.HttpState
Deprecated. use #getProxyCredentials(AuthScope)
getProxyCredentials(AuthScope) - Method in class org.apache.commons.httpclient.HttpState
Get the proxy credentials for the given authentication scope.
getProxyHost() - Method in class org.apache.commons.httpclient.HostConfiguration
Returns the proxyHost.
getProxyHost() - Method in class org.apache.commons.httpclient.HttpConnection
Returns the proxy host.
getProxyPort() - Method in class org.apache.commons.httpclient.HostConfiguration
Returns the proxyPort.
getProxyPort() - Method in class org.apache.commons.httpclient.HttpConnection
Returns the port of the proxy host.
getQuery() - Method in class org.apache.commons.httpclient.URI
Get the query.
getQuery(String) - Static method in class org.apache.commons.httpclient.util.URIUtil
Get the query of an URI.
getQueryString() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the query string of this HTTP method.
getQueryString() - Method in class org.apache.commons.httpclient.HttpMethodBase
Gets the query string of this HTTP method.
getRawAboveHierPath() - Method in class org.apache.commons.httpclient.HttpURL
Get the level above the this hierarchy level.
getRawAboveHierPath() - Method in class org.apache.commons.httpclient.URI
Get the level above the this hierarchy level.
getRawAuthority() - Method in class org.apache.commons.httpclient.URI
Get the raw-escaped authority.
getRawCurrentHierPath() - Method in class org.apache.commons.httpclient.HttpURL
Get the raw-escaped current hierarchy level.
getRawCurrentHierPath(char[]) - Method in class org.apache.commons.httpclient.URI
Get the raw-escaped current hierarchy level in the given path.
getRawCurrentHierPath() - Method in class org.apache.commons.httpclient.URI
Get the raw-escaped current hierarchy level.
getRawFragment() - Method in class org.apache.commons.httpclient.URI
Get the raw-escaped fragment.
getRawHost() - Method in class org.apache.commons.httpclient.URI
Get the host.
getRawName() - Method in class org.apache.commons.httpclient.URI
Get the raw-escaped basename of the path.
getRawPassword() - Method in class org.apache.commons.httpclient.HttpURL
Get the raw-escaped password.
getRawPath() - Method in class org.apache.commons.httpclient.HttpURL
Get the raw escaped path.
getRawPath() - Method in class org.apache.commons.httpclient.URI
Get the raw-escaped path.
getRawPathQuery() - Method in class org.apache.commons.httpclient.URI
Get the raw-escaped path and query.
getRawQuery() - Method in class org.apache.commons.httpclient.URI
Get the raw-escaped query.
getRawScheme() - Method in class org.apache.commons.httpclient.HttpsURL
Get the scheme.
getRawScheme() - Method in class org.apache.commons.httpclient.HttpURL
Get the scheme.
getRawScheme() - Method in class org.apache.commons.httpclient.URI
Get the scheme.
getRawURI() - Method in class org.apache.commons.httpclient.URI
It can be gotten the URI character sequence.
getRawURIReference() - Method in class org.apache.commons.httpclient.URI
Get the URI reference character sequence.
getRawUser() - Method in class org.apache.commons.httpclient.HttpURL
Get the raw-escaped user.
getRawUserinfo() - Method in class org.apache.commons.httpclient.URI
Get the raw-escaped userinfo.
getRealm() - Method in interface org.apache.commons.httpclient.auth.AuthScheme
Returns authentication realm.
getRealm() - Method in class org.apache.commons.httpclient.auth.AuthScope
 
getRealm() - Method in class org.apache.commons.httpclient.auth.AuthState
Returns the authentication realm.
getRealm() - Method in class org.apache.commons.httpclient.auth.NTLMScheme
The concept of an authentication realm is not supported by the NTLM authentication scheme.
getRealm() - Method in class org.apache.commons.httpclient.auth.RFC2617Scheme
Returns authentication realm.
getReason() - Method in exception org.apache.commons.httpclient.HttpException
Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.
getReason() - Method in exception org.apache.commons.httpclient.URI.DefaultCharsetChanged
Get the reason message.
getReason() - Method in exception org.apache.commons.httpclient.URIException
Deprecated. You should instead call Throwable.getMessage().
getReasonCode() - Method in exception org.apache.commons.httpclient.HttpException
Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.
getReasonCode() - Method in exception org.apache.commons.httpclient.URI.DefaultCharsetChanged
Get the reason code.
getReasonCode() - Method in exception org.apache.commons.httpclient.URIException
Get the reason code.
getReasonPhrase() - Method in class org.apache.commons.httpclient.StatusLine
 
getReceiveBufferSize() - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Returns a hint the size of the underlying buffers used by the platform for incoming network I/O.
getRecoverableExceptionCount() - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. no longer used Returns the number of "recoverable" exceptions thrown and handled, to allow for monitoring the quality of the connection.
getRegisteredCookieSpecs() - Static method in class org.apache.commons.httpclient.cookie.CookiePolicy
Obtains the currently registered cookie policy names.
getRequestCharSet() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the character encoding of the request from the Content-Type header.
getRequestCharSet() - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Returns the request's charset.
getRequestContentLength() - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Returns the length of the request body.
getRequestContentLength() - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Return the length of the request body.
getRequestEntity() - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
 
getRequestHeader(String) - Method in interface org.apache.commons.httpclient.HttpMethod
Gets the request header with the given name.
getRequestHeader(String) - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the specified request header.
getRequestHeaderGroup() - Method in class org.apache.commons.httpclient.HttpMethodBase
Gets the header group storing the request headers.
getRequestHeaders() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the current request headers for this HTTP method.
getRequestHeaders(String) - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the request headers with the given name.
getRequestHeaders() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns an array of the requests headers that the HTTP method currently has
getRequestHeaders(String) - Method in class org.apache.commons.httpclient.HttpMethodBase
 
getRequestMethod() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Return the request method.
getRequestOutputStream() - Method in class org.apache.commons.httpclient.HttpConnection
Returns an OutputStream suitable for writing the request.
getRequestProperty(String) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
getResponseBody() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the response body of the HTTP method, if any, as an array of bytes.
getResponseBody() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the response body of the HTTP method, if any, as an array of bytes.
getResponseBody(int) - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the response body of the HTTP method, if any, as an array of bytes.
getResponseBodyAsStream() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the response body of the HTTP method, if any, as an InputStream.
getResponseBodyAsStream() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the response body of the HTTP method, if any, as an InputStream.
getResponseBodyAsString() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the response body of the HTTP method, if any, as a String.
getResponseBodyAsString() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the response body of the HTTP method, if any, as a String.
getResponseBodyAsString(int) - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the response body of the HTTP method, if any, as a String.
getResponseCharSet() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the character encoding of the response from the Content-Type header.
getResponseCode() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Return the response code.
getResponseContentLength() - Method in class org.apache.commons.httpclient.HttpMethodBase
Return the length (in bytes) of the response body, as specified in a Content-Length header.
getResponseFooter(String) - Method in interface org.apache.commons.httpclient.HttpMethod
Return the specified response footer.
getResponseFooter(String) - Method in class org.apache.commons.httpclient.HttpMethodBase
Gets the response footer associated with the given name.
getResponseFooters() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the response footers from the most recent execution of this request.
getResponseFooters() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns an array of the response footers that the HTTP method currently has in the order in which they were read.
getResponseHeader(String) - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the specified response header.
getResponseHeader(String) - Method in class org.apache.commons.httpclient.HttpMethodBase
Gets the response header associated with the given name.
getResponseHeaderGroup() - Method in class org.apache.commons.httpclient.HttpMethodBase
Gets the header group storing the response headers.
getResponseHeaders() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the response headers from the most recent execution of this request.
getResponseHeaders(String) - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the response headers with the given name.
getResponseHeaders(String) - Method in class org.apache.commons.httpclient.HttpMethodBase
 
getResponseHeaders() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns an array of the response headers that the HTTP method currently has in the order in which they were read.
getResponseInputStream() - Method in class org.apache.commons.httpclient.HttpConnection
Return a InputStream suitable for reading the response.
getResponseMessage() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Return the response message
getResponseStream() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns a stream from which the body of the current response may be read.
getResponseTrailerHeaderGroup() - Method in class org.apache.commons.httpclient.HttpMethodBase
Gets the header group storing the response trailer headers as per RFC 2616 section 3.6.1.
getRetryCount() - Method in class org.apache.commons.httpclient.DefaultHttpMethodRetryHandler
 
getRetryCount() - Method in class org.apache.commons.httpclient.DefaultMethodRetryHandler
Deprecated.  
getScheme() - Method in class org.apache.commons.httpclient.auth.AuthScope
 
getScheme() - Method in class org.apache.commons.httpclient.HttpsURL
Get the scheme.
getScheme() - Method in class org.apache.commons.httpclient.HttpURL
Get the scheme.
getScheme() - Method in class org.apache.commons.httpclient.protocol.Protocol
Returns the scheme.
getScheme() - Method in class org.apache.commons.httpclient.URI
Get the scheme.
getSchemeName() - Method in interface org.apache.commons.httpclient.auth.AuthScheme
Returns textual designation of the given authentication scheme.
getSchemeName() - Method in class org.apache.commons.httpclient.auth.BasicScheme
Returns textual designation of the basic authentication scheme.
getSchemeName() - Method in class org.apache.commons.httpclient.auth.DigestScheme
Returns textual designation of the digest authentication scheme.
getSchemeName() - Method in class org.apache.commons.httpclient.auth.NTLMScheme
Returns textual designation of the NTLM authentication scheme.
getSecure() - Method in class org.apache.commons.httpclient.Cookie
 
getSendBufferSize() - Method in class org.apache.commons.httpclient.HttpConnection
Gets the socket's sendBufferSize.
getSendBufferSize() - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Returns a hint the size of the underlying buffers used by the platform for outgoing network I/O.
getSocket() - Method in class org.apache.commons.httpclient.HttpConnection
Returns the connection socket.
getSocket() - Method in class org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory.SocketTask
Return the socket.
getSocket() - Method in class org.apache.commons.httpclient.ProxyClient.ConnectResponse
Gets the socket connected and authenticated (if appropriate) to the configured HTTP proxy, or null if a connection could not be made.
getSocketFactory() - Method in class org.apache.commons.httpclient.protocol.Protocol
Returns the socketFactory.
getSoTimeout() - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. Use HttpConnectionParams.getSoTimeout(), HttpConnection.getParams().
getSoTimeout() - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Returns the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
getSoTimeout() - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Returns the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
getSource() - Method in class org.apache.commons.httpclient.methods.multipart.FilePart
Returns the source of the file part.
getSpecByPolicy(int) - Static method in class org.apache.commons.httpclient.cookie.CookiePolicy
Deprecated. Use CookiePolicy.getCookieSpec(String)
getSpecByVersion(int) - Static method in class org.apache.commons.httpclient.cookie.CookiePolicy
Deprecated. Use CookiePolicy.getCookieSpec(String)
getState() - Method in class org.apache.commons.httpclient.HttpClient
Returns HTTP state associated with the HttpClient.
getState() - Method in class org.apache.commons.httpclient.ProxyClient
Returns HTTP state associated with the ProxyClient.
getStatusCode() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the status code associated with the latest response.
getStatusCode() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the response status code.
getStatusCode() - Method in class org.apache.commons.httpclient.StatusLine
 
getStatusLine() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the Status-Line from the most recent response for this method, or null if the method has not been executed.
getStatusLine() - Method in class org.apache.commons.httpclient.HttpMethodBase
Provides access to the response status line.
getStatusText() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the status text (or "reason phrase") associated with the latest response.
getStatusText() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the status text (or "reason phrase") associated with the latest response.
getStatusText(int) - Static method in class org.apache.commons.httpclient.HttpStatus
Get the reason phrase for a particular status code.
getString(byte[], int, int) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the byte array of HTTP element characters to a string This method is to be used when decoding content of HTTP elements (such as response headers)
getString(byte[]) - Static method in class org.apache.commons.httpclient.HttpConstants
Deprecated. Converts the byte array of HTTP element characters to a string This method is to be used when decoding content of HTTP elements (such as response headers)
getString(byte[], int, int, String) - Static method in class org.apache.commons.httpclient.util.EncodingUtil
Converts the byte array of HTTP content characters to a string.
getString(byte[], String) - Static method in class org.apache.commons.httpclient.util.EncodingUtil
Converts the byte array of HTTP content characters to a string.
getTcpNoDelay() - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Tests if Nagle's algorithm is to be used.
getTransferEncoding() - Method in class org.apache.commons.httpclient.methods.multipart.Part
Return the transfer encoding of this part.
getTransferEncoding() - Method in class org.apache.commons.httpclient.methods.multipart.PartBase
Returns the transfer encoding of this part.
getURI() - Method in class org.apache.commons.httpclient.ConnectMethod
 
getURI() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns the URI for this method.
getURI() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns the URI of the HTTP method
getURI() - Method in class org.apache.commons.httpclient.URI
It can be gotten the URI character sequence.
getUriCharset() - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Returns the charset to be used for parsing URIs.
getURIReference() - Method in class org.apache.commons.httpclient.URI
Get the original URI reference string.
getURL() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Return the URL
getUseCaches() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.
getUseExpectHeader() - Method in class org.apache.commons.httpclient.methods.ExpectContinueMethod
Deprecated. Use HttpMethodParams
getUser() - Method in class org.apache.commons.httpclient.HttpURL
Get the user.
getUserinfo() - Method in class org.apache.commons.httpclient.URI
Get the userinfo.
getUserName() - Method in class org.apache.commons.httpclient.UsernamePasswordCredentials
User name property getter.
getValidDateFormats() - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Returns the Collection of date patterns used for parsing.
getValidDateFormats() - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
 
getValidDateFormats() - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
 
getValue() - Method in class org.apache.commons.httpclient.NameValuePair
Return the current value.
getValues() - Method in class org.apache.commons.httpclient.Header
Deprecated. Use #getElements
getVersion() - Method in interface org.apache.commons.httpclient.cookie.CookieVersionSupport
 
getVersion() - Method in class org.apache.commons.httpclient.Cookie
Returns the version of the cookie specification to which this cookie conforms.
getVersion() - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
 
getVersion() - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Returns HTTP protocol version to be used by the HTTP methods that this collection of parameters applies to.
getVersionHeader() - Method in interface org.apache.commons.httpclient.cookie.CookieVersionSupport
 
getVersionHeader() - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
 
getVirtualHost() - Method in class org.apache.commons.httpclient.HostConfiguration
Deprecated. use HostParams
getVirtualHost() - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. no longer applicable
getVirtualHost() - Method in class org.apache.commons.httpclient.params.HostParams
Returns the virtual host name.
getVirtualHost() - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Returns the virtual host name.
greaterEquals(HttpVersion) - Method in class org.apache.commons.httpclient.HttpVersion
Test if the HTTP protocol version is greater or equal to the given number.

H

handleCloseIdleConnections(HttpConnectionManager) - Method in class org.apache.commons.httpclient.util.IdleConnectionTimeoutThread
Handles calling closeIdleConnections() and doing any other cleanup work on the given connection mangaer.
hasAuthority() - Method in class org.apache.commons.httpclient.URI
Tell whether or not this URI has authority.
hasBeenUsed() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns true if the HTTP method has been already executed, but not recycled.
hasBeenUsed() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns true if the HTTP method has been already executed, but not recycled.
hasFragment() - Method in class org.apache.commons.httpclient.URI
Tell whether or not this URI has fragment.
hash - Variable in class org.apache.commons.httpclient.URI
Cache the hash code for this URI.
HASH_OFFSET - Static variable in class org.apache.commons.httpclient.util.LangUtils
 
HASH_SEED - Static variable in class org.apache.commons.httpclient.util.LangUtils
 
hashCode() - Method in class org.apache.commons.httpclient.auth.AuthSchemeBase
Deprecated.  
hashCode() - Method in class org.apache.commons.httpclient.auth.AuthScope
 
hashCode() - Method in class org.apache.commons.httpclient.Cookie
Returns a hash code in keeping with the Object.hashCode() general hashCode contract.
hashCode() - Method in class org.apache.commons.httpclient.HostConfiguration
 
hashCode() - Method in class org.apache.commons.httpclient.HttpHost
 
hashCode() - Method in class org.apache.commons.httpclient.HttpVersion
 
hashCode() - Method in class org.apache.commons.httpclient.NameValuePair
 
hashCode() - Method in class org.apache.commons.httpclient.NTCredentials
Computes a hash code based on all the case-sensitive parts of the credentials object.
hashCode() - Method in class org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory
All instances of DefaultProtocolSocketFactory have the same hash code.
hashCode() - Method in class org.apache.commons.httpclient.protocol.Protocol
Return a hash code for this object
hashCode() - Method in class org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory
All instances of SSLProtocolSocketFactory have the same hash code.
hashCode() - Method in class org.apache.commons.httpclient.URI
Return a hash code for this URI.
hashCode() - Method in class org.apache.commons.httpclient.UsernamePasswordCredentials
Does a hash of both user name and password.
hashCode(int, int) - Static method in class org.apache.commons.httpclient.util.LangUtils
 
hashCode(int, Object) - Static method in class org.apache.commons.httpclient.util.LangUtils
 
hashCode(int, boolean) - Static method in class org.apache.commons.httpclient.util.LangUtils
 
hasQuery() - Method in class org.apache.commons.httpclient.URI
Tell whether or not this URI has query.
hasRequestContent() - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Returns true if there is a request body to be sent.
hasRequestContent() - Method in class org.apache.commons.httpclient.methods.ExpectContinueMethod
Returns true if there is a request body to be sent.
hasRequestContent() - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Returns true
hasRequestContent() - Method in class org.apache.commons.httpclient.methods.PostMethod
Returns true if there is a request body to be sent.
hasUserinfo() - Method in class org.apache.commons.httpclient.URI
Tell whether or not this URI has userinfo.
HEAD_BODY_CHECK_TIMEOUT - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Sets period of time in milliseconds to wait for a content body sent in response to HEAD method from a non-compliant server.
Header - Class in org.apache.commons.httpclient
An HTTP header.
Header() - Constructor for class org.apache.commons.httpclient.Header
Default constructor.
Header(String, String) - Constructor for class org.apache.commons.httpclient.Header
Constructor with name and value
Header(String, String, boolean) - Constructor for class org.apache.commons.httpclient.Header
Constructor with name and value
HeaderElement - Class in org.apache.commons.httpclient
One element of an HTTP header's value.
HeaderElement() - Constructor for class org.apache.commons.httpclient.HeaderElement
Default constructor.
HeaderElement(String, String) - Constructor for class org.apache.commons.httpclient.HeaderElement
Constructor.
HeaderElement(String, String, NameValuePair[]) - Constructor for class org.apache.commons.httpclient.HeaderElement
Constructor with name, value and parameters.
HeaderElement(char[], int, int) - Constructor for class org.apache.commons.httpclient.HeaderElement
Constructor with array of characters.
HeaderElement(char[]) - Constructor for class org.apache.commons.httpclient.HeaderElement
Constructor with array of characters.
HeaderGroup - Class in org.apache.commons.httpclient
A class for combining a set of headers.
HeaderGroup() - Constructor for class org.apache.commons.httpclient.HeaderGroup
Constructor for HeaderGroup.
HeadMethod - Class in org.apache.commons.httpclient.methods
Implements the HTTP HEAD method.
HeadMethod() - Constructor for class org.apache.commons.httpclient.methods.HeadMethod
No-arg constructor.
HeadMethod(String) - Constructor for class org.apache.commons.httpclient.methods.HeadMethod
Constructor specifying a URI.
hex - Static variable in class org.apache.commons.httpclient.URI
BitSet for hex.
hier_part - Static variable in class org.apache.commons.httpclient.URI
BitSet for hier_part.
host - Static variable in class org.apache.commons.httpclient.URI
BitSet for host.
HostConfiguration - Class in org.apache.commons.httpclient
Holds all of the variables needed to describe an HTTP connection to a host.
HostConfiguration() - Constructor for class org.apache.commons.httpclient.HostConfiguration
Constructor for HostConfiguration.
HostConfiguration(HostConfiguration) - Constructor for class org.apache.commons.httpclient.HostConfiguration
Copy constructor for HostConfiguration
hostEquals(HttpConnection) - Method in class org.apache.commons.httpclient.HostConfiguration
Tests if the host configuration equals the configuration set on the connection.
hostname - Static variable in class org.apache.commons.httpclient.URI
BitSet for hostname.
HostParams - Class in org.apache.commons.httpclient.params
This class represents a collection of HTTP protocol parameters applicable to instances of HostConfiguration.
HostParams() - Constructor for class org.apache.commons.httpclient.params.HostParams
Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent.
HostParams(HttpParams) - Constructor for class org.apache.commons.httpclient.params.HostParams
Creates a new collection of parameters with the given parent.
hostport - Static variable in class org.apache.commons.httpclient.URI
BitSet for hostport.
HTTP_0_9 - Static variable in class org.apache.commons.httpclient.HttpVersion
HTTP protocol version 0.9
HTTP_1_0 - Static variable in class org.apache.commons.httpclient.HttpVersion
HTTP protocol version 1.0
HTTP_1_1 - Static variable in class org.apache.commons.httpclient.HttpVersion
HTTP protocol version 1.1
HTTP_CONTENT_CHARSET - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines the charset to be used for encoding content body.
HTTP_ELEMENT_CHARSET - Static variable in class org.apache.commons.httpclient.HttpConstants
Deprecated. Character set used to encode HTTP protocol elements
HTTP_ELEMENT_CHARSET - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines the charset to be used for encoding HTTP protocol elements.
HTTP_URI_CHARSET - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines the charset to be used for parsing URIs.
HttpAuthenticator - Class in org.apache.commons.httpclient.auth
Deprecated. no longer used
HttpAuthenticator() - Constructor for class org.apache.commons.httpclient.auth.HttpAuthenticator
Deprecated.  
HttpAuthRealm - Class in org.apache.commons.httpclient.auth
Deprecated. no longer used
HttpAuthRealm(String, String) - Constructor for class org.apache.commons.httpclient.auth.HttpAuthRealm
Deprecated. Creates a new HttpAuthRealm for the given domain and realm.
HttpClient - Class in org.apache.commons.httpclient
An HTTP "user-agent", containing an HTTP state and one or more HTTP connections, to which HTTP methods can be applied.
HttpClient() - Constructor for class org.apache.commons.httpclient.HttpClient
Creates an instance of HttpClient using default parameter set.
HttpClient(HttpClientParams) - Constructor for class org.apache.commons.httpclient.HttpClient
Creates an instance of HttpClient using the given parameter set.
HttpClient(HttpClientParams, HttpConnectionManager) - Constructor for class org.apache.commons.httpclient.HttpClient
Creates an instance of HttpClient with a user specified parameter set and HTTP connection manager.
HttpClient(HttpConnectionManager) - Constructor for class org.apache.commons.httpclient.HttpClient
Creates an instance of HttpClient with a user specified HTTP connection manager.
HttpClientError - Error in org.apache.commons.httpclient
Signals that an error has occurred.
HttpClientError() - Constructor for error org.apache.commons.httpclient.HttpClientError
Creates a new HttpClientError with a null detail message.
HttpClientError(String) - Constructor for error org.apache.commons.httpclient.HttpClientError
Creates a new HttpClientError with the specified detail message.
HttpClientParams - Class in org.apache.commons.httpclient.params
This class represents a collection of HTTP protocol parameters applicable to instances of HttpClient.
HttpClientParams() - Constructor for class org.apache.commons.httpclient.params.HttpClientParams
Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent.
HttpClientParams(HttpParams) - Constructor for class org.apache.commons.httpclient.params.HttpClientParams
Creates a new collection of parameters with the given parent.
HttpConnection - Class in org.apache.commons.httpclient
An abstraction of an HTTP InputStream and OutputStream pair, together with the relevant attributes.
HttpConnection(String, int) - Constructor for class org.apache.commons.httpclient.HttpConnection
Creates a new HTTP connection for the given host and port.
HttpConnection(String, int, Protocol) - Constructor for class org.apache.commons.httpclient.HttpConnection
Creates a new HTTP connection for the given host and port using the given protocol.
HttpConnection(String, String, int, Protocol) - Constructor for class org.apache.commons.httpclient.HttpConnection
Creates a new HTTP connection for the given host with the virtual alias and port using given protocol.
HttpConnection(String, int, String, int) - Constructor for class org.apache.commons.httpclient.HttpConnection
Creates a new HTTP connection for the given host and port via the given proxy host and port using the default protocol.
HttpConnection(HostConfiguration) - Constructor for class org.apache.commons.httpclient.HttpConnection
Creates a new HTTP connection for the given host configuration.
HttpConnection(String, int, String, String, int, Protocol) - Constructor for class org.apache.commons.httpclient.HttpConnection
Deprecated. use #HttpConnection(String, int, String, int, Protocol)
HttpConnection(String, int, String, int, Protocol) - Constructor for class org.apache.commons.httpclient.HttpConnection
Creates a new HTTP connection for the given host with the virtual alias and port via the given proxy host and port using the given protocol.
httpConnection - Variable in class org.apache.commons.httpclient.SimpleHttpConnectionManager
The http connection
HttpConnectionManager - Interface in org.apache.commons.httpclient
An interface for classes that manage HttpConnections.
HttpConnectionManagerParams - Class in org.apache.commons.httpclient.params
This class represents a collection of HTTP protocol parameters applicable to HTTP connection managers.
HttpConnectionManagerParams() - Constructor for class org.apache.commons.httpclient.params.HttpConnectionManagerParams
 
HttpConnectionParams - Class in org.apache.commons.httpclient.params
This class represents a collection of HTTP protocol parameters applicable to HTTP connections.
HttpConnectionParams() - Constructor for class org.apache.commons.httpclient.params.HttpConnectionParams
Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent.
HttpConstants - Class in org.apache.commons.httpclient
Deprecated. use EncodingUtil class
HttpConstants() - Constructor for class org.apache.commons.httpclient.HttpConstants
Deprecated.  
HttpContentTooLargeException - Exception in org.apache.commons.httpclient
Signals that the response content was larger than anticipated.
HttpContentTooLargeException(String, int) - Constructor for exception org.apache.commons.httpclient.HttpContentTooLargeException
 
HttpException - Exception in org.apache.commons.httpclient
Signals that an HTTP or HttpClient exception has occurred.
HttpException() - Constructor for exception org.apache.commons.httpclient.HttpException
Creates a new HttpException with a null detail message.
HttpException(String) - Constructor for exception org.apache.commons.httpclient.HttpException
Creates a new HttpException with the specified detail message.
HttpException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.HttpException
Creates a new HttpException with the specified detail message and cause.
HttpHost - Class in org.apache.commons.httpclient
Holds all of the variables needed to describe an HTTP connection to a host.
HttpHost(String, int, Protocol) - Constructor for class org.apache.commons.httpclient.HttpHost
Constructor for HttpHost.
HttpHost(String, int) - Constructor for class org.apache.commons.httpclient.HttpHost
Constructor for HttpHost.
HttpHost(String) - Constructor for class org.apache.commons.httpclient.HttpHost
Constructor for HttpHost.
HttpHost(URI) - Constructor for class org.apache.commons.httpclient.HttpHost
URI constructor for HttpHost.
HttpHost(HttpHost) - Constructor for class org.apache.commons.httpclient.HttpHost
Copy constructor for HttpHost
HttpMethod - Interface in org.apache.commons.httpclient
HttpMethod interface represents a request to be sent via a HTTP connection and a corresponding response.
HttpMethodBase - Class in org.apache.commons.httpclient
An abstract base implementation of HttpMethod.
HttpMethodBase() - Constructor for class org.apache.commons.httpclient.HttpMethodBase
No-arg constructor.
HttpMethodBase(String) - Constructor for class org.apache.commons.httpclient.HttpMethodBase
Constructor specifying a URI.
HttpMethodParams - Class in org.apache.commons.httpclient.params
This class represents a collection of HTTP protocol parameters applicable to HTTP methods.
HttpMethodParams() - Constructor for class org.apache.commons.httpclient.params.HttpMethodParams
Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent.
HttpMethodParams(HttpParams) - Constructor for class org.apache.commons.httpclient.params.HttpMethodParams
Creates a new collection of parameters with the given parent.
HttpMethodRetryHandler - Interface in org.apache.commons.httpclient
A handler for determining if an HttpMethod should be retried after a recoverable exception during execution.
HttpParams - Interface in org.apache.commons.httpclient.params
This interface represents a collection of HTTP protocol parameters.
HttpParamsFactory - Interface in org.apache.commons.httpclient.params
A factory for getting the default set of parameters to use when creating an instance of HttpParams.
HttpParser - Class in org.apache.commons.httpclient
A utility class for parsing http header values according to RFC-2616 Section 4 and 19.3.
HttpRecoverableException - Exception in org.apache.commons.httpclient
Deprecated. no longer used
HttpRecoverableException() - Constructor for exception org.apache.commons.httpclient.HttpRecoverableException
Deprecated. Creates a new HttpRecoverableException with a null detail message.
HttpRecoverableException(String) - Constructor for exception org.apache.commons.httpclient.HttpRecoverableException
Deprecated. Creates a new HttpRecoverableException with the specified detail message.
HttpState - Class in org.apache.commons.httpclient
A container for HTTP attributes that may persist from request to request, such as cookies and authentication credentials.
HttpState() - Constructor for class org.apache.commons.httpclient.HttpState
Default constructor.
HttpStatus - Class in org.apache.commons.httpclient
Constants enumerating the HTTP status codes.
HttpStatus() - Constructor for class org.apache.commons.httpclient.HttpStatus
 
HttpsURL - Class in org.apache.commons.httpclient
The HTTPS URL.
HttpsURL() - Constructor for class org.apache.commons.httpclient.HttpsURL
Create an instance as an internal use.
HttpsURL(char[], String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL as an escaped form of a character array with the given charset to do escape encoding.
HttpsURL(char[]) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL as an escaped form of a character array.
HttpsURL(String, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from a given string with the given charset to do escape encoding.
HttpsURL(String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from a given string.
HttpsURL(String, int, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from given components.
HttpsURL(String, int, String, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from given components.
HttpsURL(String, String, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from given components.
HttpsURL(String, String, String, int) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from given components.
HttpsURL(String, String, String, int, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from given components.
HttpsURL(String, String, String, int, String, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from given components.
HttpsURL(String, String, String, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from given components.
HttpsURL(String, String, String, String, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from given components.
HttpsURL(String, String, int, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from given components.
HttpsURL(String, String, int, String, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from given components.
HttpsURL(String, String, int, String, String, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL from given components.
HttpsURL(String, String, String, int, String, String, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTP URL from given components.
HttpsURL(HttpsURL, String) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL with a given relative HTTPS URL string.
HttpsURL(HttpsURL, HttpsURL) - Constructor for class org.apache.commons.httpclient.HttpsURL
Construct a HTTPS URL with a given relative URL.
HttpURL - Class in org.apache.commons.httpclient
The HTTP URL.
HttpURL() - Constructor for class org.apache.commons.httpclient.HttpURL
Create an instance as an internal use.
HttpURL(char[], String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL as an escaped form of a character array with the given charset to do escape encoding.
HttpURL(char[]) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL as an escaped form of a character array.
HttpURL(String, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from a given string with the given charset to do escape encoding.
HttpURL(String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from a given string.
HttpURL(String, int, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(String, int, String, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(String, String, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(String, String, String, int) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(String, String, String, int, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(String, String, String, int, String, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(String, String, String, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(String, String, String, String, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(String, String, int, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(String, String, int, String, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(String, String, int, String, String, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(String, String, String, int, String, String, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL from given components.
HttpURL(HttpURL, String) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL with a given relative URL string.
HttpURL(HttpURL, HttpURL) - Constructor for class org.apache.commons.httpclient.HttpURL
Construct a HTTP URL with a given relative URL.
HttpURLConnection - Class in org.apache.commons.httpclient.util
Provides a HttpURLConnection wrapper around HttpClient's HttpMethod.
HttpURLConnection(HttpMethod, URL) - Constructor for class org.apache.commons.httpclient.util.HttpURLConnection
Creates an HttpURLConnection from a HttpMethod.
HttpURLConnection(URL) - Constructor for class org.apache.commons.httpclient.util.HttpURLConnection
Create an instance.
HttpVersion - Class in org.apache.commons.httpclient
HTTP version, as specified in RFC 2616.
HttpVersion(int, int) - Constructor for class org.apache.commons.httpclient.HttpVersion
Create an HTTP protocol version designator.

I

IdleConnectionHandler - Class in org.apache.commons.httpclient.util
A helper class for connection managers to track idle connections.
IdleConnectionHandler() - Constructor for class org.apache.commons.httpclient.util.IdleConnectionHandler
 
IdleConnectionTimeoutThread - Class in org.apache.commons.httpclient.util
A utility class for periodically closing idle connections.
IdleConnectionTimeoutThread() - Constructor for class org.apache.commons.httpclient.util.IdleConnectionTimeoutThread
 
IGNORE_COOKIES - Static variable in class org.apache.commons.httpclient.cookie.CookiePolicy
The policy that ignores cookies.
IgnoreCookiesSpec - Class in org.apache.commons.httpclient.cookie
A cookie spec that does nothing.
IgnoreCookiesSpec() - Constructor for class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
 
indexFirstOf(String, String) - Method in class org.apache.commons.httpclient.URI
Get the earlier index that to be searched for the first occurrance in one of any of the given string.
indexFirstOf(String, String, int) - Method in class org.apache.commons.httpclient.URI
Get the earlier index that to be searched for the first occurrance in one of any of the given string.
indexFirstOf(char[], char) - Method in class org.apache.commons.httpclient.URI
Get the earlier index that to be searched for the first occurrance in one of any of the given array.
indexFirstOf(char[], char, int) - Method in class org.apache.commons.httpclient.URI
Get the earlier index that to be searched for the first occurrance in one of any of the given array.
initCause(Throwable, Throwable) - Static method in class org.apache.commons.httpclient.util.ExceptionUtil
If we're running on JDK 1.4 or later, initialize the cause for the given throwable.
InputStreamRequestEntity - Class in org.apache.commons.httpclient.methods
A RequestEntity that contains an InputStream.
InputStreamRequestEntity(InputStream) - Constructor for class org.apache.commons.httpclient.methods.InputStreamRequestEntity
Creates a new InputStreamRequestEntity with the given content and a content type of InputStreamRequestEntity.CONTENT_LENGTH_AUTO.
InputStreamRequestEntity(InputStream, String) - Constructor for class org.apache.commons.httpclient.methods.InputStreamRequestEntity
Creates a new InputStreamRequestEntity with the given content, content type, and a content length of InputStreamRequestEntity.CONTENT_LENGTH_AUTO.
InputStreamRequestEntity(InputStream, long) - Constructor for class org.apache.commons.httpclient.methods.InputStreamRequestEntity
Creates a new InputStreamRequestEntity with the given content and content length.
InputStreamRequestEntity(InputStream, long, String) - Constructor for class org.apache.commons.httpclient.methods.InputStreamRequestEntity
Creates a new InputStreamRequestEntity with the given content, content length, and content type.
invalidate() - Method in class org.apache.commons.httpclient.auth.AuthState
Invalidates the authentication state by resetting its parameters.
InvalidCredentialsException - Exception in org.apache.commons.httpclient.auth
Authentication credentials required to respond to a authentication challenge are invalid
InvalidCredentialsException() - Constructor for exception org.apache.commons.httpclient.auth.InvalidCredentialsException
Creates a new InvalidCredentialsException with a null detail message.
InvalidCredentialsException(String) - Constructor for exception org.apache.commons.httpclient.auth.InvalidCredentialsException
Creates a new InvalidCredentialsException with the specified message.
InvalidCredentialsException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.auth.InvalidCredentialsException
Creates a new InvalidCredentialsException with the specified detail message and cause.
InvalidRedirectLocationException - Exception in org.apache.commons.httpclient
Signals violation of HTTP specification caused by an invalid redirect location
InvalidRedirectLocationException(String, String) - Constructor for exception org.apache.commons.httpclient.InvalidRedirectLocationException
Creates a new InvalidRedirectLocationException with the specified detail message.
InvalidRedirectLocationException(String, String, Throwable) - Constructor for exception org.apache.commons.httpclient.InvalidRedirectLocationException
Creates a new RedirectException with the specified detail message and cause.
IPv4address - Static variable in class org.apache.commons.httpclient.URI
Bitset that combines digit and dot fo IPv$address.
IPv6address - Static variable in class org.apache.commons.httpclient.URI
RFC 2373.
IPv6reference - Static variable in class org.apache.commons.httpclient.URI
RFC 2732, 2373.
isAborted() - Method in class org.apache.commons.httpclient.HttpMethodBase
Tests whether the execution of this method has been aborted
isAbsoluteURI() - Method in class org.apache.commons.httpclient.URI
Tell whether or not this URI is absolute.
isAbsPath() - Method in class org.apache.commons.httpclient.URI
Tell whether or not the relativeURI or hier_part of this URI is abs_path.
isAllowed(String) - Method in class org.apache.commons.httpclient.methods.OptionsMethod
Is the specified method allowed ?
isAlwaysUseQuotes() - Method in class org.apache.commons.httpclient.util.ParameterFormatter
Determines whether all parameter values must be enclosed in quotation marks, even if they do not contain any special characters
isAuthAttempted() - Method in class org.apache.commons.httpclient.auth.AuthState
Tests whether authenication challenge has been responsed to
isAuthenticationPreemptive() - Method in class org.apache.commons.httpclient.HttpState
Deprecated. Use HttpClientParams.isAuthenticationPreemptive(), HttpClient.getParams().
isAuthenticationPreemptive() - Method in class org.apache.commons.httpclient.params.HttpClientParams
Returns true if authentication should be attempted preemptively, false otherwise.
isAuthRequested() - Method in class org.apache.commons.httpclient.auth.AuthState
Tests whether authenication challenge has been received
isAutogenerated() - Method in class org.apache.commons.httpclient.Header
Returns the value of the auto-generated header flag.
isComplete() - Method in interface org.apache.commons.httpclient.auth.AuthScheme
Authentication process may involve a series of challenge-response exchanges.
isComplete() - Method in class org.apache.commons.httpclient.auth.BasicScheme
Tests if the Basic authentication process has been completed.
isComplete() - Method in class org.apache.commons.httpclient.auth.DigestScheme
Tests if the Digest authentication process has been completed.
isComplete() - Method in class org.apache.commons.httpclient.auth.NTLMScheme
Tests if the NTLM authentication process has been completed.
isConnectionBased() - Method in interface org.apache.commons.httpclient.auth.AuthScheme
Tests if the authentication scheme is provides authorization on a per connection basis instead of usual per request basis
isConnectionBased() - Method in class org.apache.commons.httpclient.auth.BasicScheme
Returns false.
isConnectionBased() - Method in class org.apache.commons.httpclient.auth.DigestScheme
Returns false.
isConnectionBased() - Method in class org.apache.commons.httpclient.auth.NTLMScheme
Returns true.
isConnectionCloseForced() - Method in class org.apache.commons.httpclient.HttpMethodBase
Tests if the connection should be force-closed when no longer needed.
isConnectionStaleCheckingEnabled() - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Deprecated. Use HttpConnectionParams.isStaleCheckingEnabled(), HttpConnectionManager.getParams().
isConnectionStaleCheckingEnabled() - Method in class org.apache.commons.httpclient.SimpleHttpConnectionManager
Deprecated. Use HttpConnectionParams.isStaleCheckingEnabled(), HttpConnectionManager.getParams().
isDomainAttributeSpecified() - Method in class org.apache.commons.httpclient.Cookie
Returns true if cookie's domain was set via a domain attribute in the Set-Cookie header.
isExpired() - Method in class org.apache.commons.httpclient.Cookie
Returns true if this cookie has expired.
isExpired(Date) - Method in class org.apache.commons.httpclient.Cookie
Returns true if this cookie has expired according to the time passed in.
isHierPart() - Method in class org.apache.commons.httpclient.URI
Tell whether or not the absoluteURI of this URI is hier_part.
isHostname() - Method in class org.apache.commons.httpclient.URI
Tell whether or not the host part of this URI is hostname.
isHostSet() - Method in class org.apache.commons.httpclient.HostConfiguration
Deprecated. no longer used
isHttp11() - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. Use HttpMethodParams.getVersion()
isIPv4address() - Method in class org.apache.commons.httpclient.URI
Tell whether or not the host part of this URI is IPv4address.
isIPv6reference() - Method in class org.apache.commons.httpclient.URI
Tell whether or not the host part of this URI is IPv6reference.
isLocked() - Method in class org.apache.commons.httpclient.HttpConnection
Tests if the connection is locked.
isNetPath() - Method in class org.apache.commons.httpclient.URI
Tell whether or not the relativeURI or heir_part of this URI is net_path.
isOpaquePart() - Method in class org.apache.commons.httpclient.URI
Tell whether or not the absoluteURI of this URI is opaque_part.
isOpen - Variable in class org.apache.commons.httpclient.HttpConnection
Whether or not the connection is connected.
isOpen() - Method in class org.apache.commons.httpclient.HttpConnection
Tests if the connection is open.
isParameterFalse(String) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
isParameterFalse(String) - Method in interface org.apache.commons.httpclient.params.HttpParams
Returns true if the parameter is either not set or is false, false otherwise.
isParameterSet(String) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
isParameterSet(String) - Method in interface org.apache.commons.httpclient.params.HttpParams
Returns true if the parameter is set at any level, false otherwise.
isParameterSetLocally(String) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
isParameterSetLocally(String) - Method in interface org.apache.commons.httpclient.params.HttpParams
Returns true if the parameter is set locally, false otherwise.
isParameterTrue(String) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
isParameterTrue(String) - Method in interface org.apache.commons.httpclient.params.HttpParams
Returns true if the parameter is set and is true, false otherwise.
isPathAttributeSpecified() - Method in class org.apache.commons.httpclient.Cookie
Returns true if cookie's path was set via a path attribute in the Set-Cookie header.
isPersistent() - Method in class org.apache.commons.httpclient.cookie.Cookie2
Returns false if the cookie should be discarded at the end of the "session"; true otherwise.
isPersistent() - Method in class org.apache.commons.httpclient.Cookie
Returns false if the cookie should be discarded at the end of the "session"; true otherwise.
isPortAttributeBlank() - Method in class org.apache.commons.httpclient.cookie.Cookie2
 
isPortAttributeSpecified() - Method in class org.apache.commons.httpclient.cookie.Cookie2
 
isPreemptive() - Method in class org.apache.commons.httpclient.auth.AuthState
Tests if preemptive authentication is used.
isProxied() - Method in class org.apache.commons.httpclient.HttpConnection
Returns true if the connection is established via a proxy, false otherwise.
isProxySet() - Method in class org.apache.commons.httpclient.HostConfiguration
Deprecated. no longer used
isRegName() - Method in class org.apache.commons.httpclient.URI
Tell whether or not the authority component of this URI is reg_name.
isRelativeURI() - Method in class org.apache.commons.httpclient.URI
Tell whether or not this URI is relative.
isRelPath() - Method in class org.apache.commons.httpclient.URI
Tell whether or not the relativeURI of this URI is rel_path.
isRepeatable() - Method in class org.apache.commons.httpclient.methods.ByteArrayRequestEntity
 
isRepeatable() - Method in class org.apache.commons.httpclient.methods.FileRequestEntity
 
isRepeatable() - Method in class org.apache.commons.httpclient.methods.InputStreamRequestEntity
Tests if this method is repeatable.
isRepeatable() - Method in class org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity
Returns true if all parts are repeatable, false otherwise.
isRepeatable() - Method in class org.apache.commons.httpclient.methods.multipart.Part
Tests if this part can be sent more than once.
isRepeatable() - Method in interface org.apache.commons.httpclient.methods.RequestEntity
Tests if RequestEntity.writeRequest(OutputStream) can be called more than once.
isRepeatable() - Method in class org.apache.commons.httpclient.methods.StringRequestEntity
 
isRequestSent() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns true if the HTTP has been transmitted to the target server in its entirety, false otherwise.
isRequestSent() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns true if the HTTP has been transmitted to the target server in its entirety, false otherwise.
isRequestSentRetryEnabled() - Method in class org.apache.commons.httpclient.DefaultHttpMethodRetryHandler
 
isRequestSentRetryEnabled() - Method in class org.apache.commons.httpclient.DefaultMethodRetryHandler
Deprecated.  
isResponseAvailable() - Method in class org.apache.commons.httpclient.HttpConnection
Tests if input data avaialble.
isResponseAvailable(int) - Method in class org.apache.commons.httpclient.HttpConnection
Tests if input data becomes available within the given period time in milliseconds.
isSecure() - Method in class org.apache.commons.httpclient.cookie.CookieOrigin
 
isSecure() - Method in class org.apache.commons.httpclient.HttpConnection
Returns true if the connection is established over a secure protocol.
isSecure() - Method in class org.apache.commons.httpclient.protocol.Protocol
Returns true if this protocol is secure
isServer() - Method in class org.apache.commons.httpclient.URI
Tell whether or not the authority component of this URI is server.
isSocketTimeoutException(InterruptedIOException) - Static method in class org.apache.commons.httpclient.util.ExceptionUtil
If SocketTimeoutExceptionClass is defined, returns true only if the exception is an instance of SocketTimeoutExceptionClass.
isStale() - Method in class org.apache.commons.httpclient.HttpConnection
Determines whether this connection is "stale", which is to say that either it is no longer open, or an attempt to read the connection would fail.
isStaleCheckingEnabled() - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. Use HttpConnectionParams.isStaleCheckingEnabled(), HttpConnection.getParams().
isStaleCheckingEnabled() - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Tests whether stale connection check is to be used.
isStrictMode() - Method in class org.apache.commons.httpclient.HttpClient
Deprecated. Use DefaultHttpParams.getParameter(String) to exercise a more granular control over HTTP protocol strictness.
isStrictMode() - Method in interface org.apache.commons.httpclient.HttpMethod
Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.
isStrictMode() - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.
isTransparent() - Method in class org.apache.commons.httpclient.HttpConnection
Indicates if the connection is completely transparent from end to end.
isVersionAttributeSpecified() - Method in class org.apache.commons.httpclient.cookie.Cookie2
 

L

LangUtils - Class in org.apache.commons.httpclient.util
A set of utility methods to help produce consistent Object#equals(Object) and Object#hashCode methods.
length() - Method in class org.apache.commons.httpclient.methods.multipart.Part
Return the full length of all the data.
lengthOfData() - Method in class org.apache.commons.httpclient.methods.multipart.FilePart
Return the length of the data.
lengthOfData() - Method in class org.apache.commons.httpclient.methods.multipart.Part
Return the length of the main content
lengthOfData() - Method in class org.apache.commons.httpclient.methods.multipart.StringPart
Return the length of the data.
lessEquals(HttpVersion) - Method in class org.apache.commons.httpclient.HttpVersion
Test if the HTTP protocol version is less or equal to the given number.
LOG - Static variable in class org.apache.commons.httpclient.auth.AuthPolicy
Log object.
LOG - Static variable in class org.apache.commons.httpclient.cookie.CookiePolicy
Log object.
LOG - Static variable in class org.apache.commons.httpclient.cookie.CookieSpecBase
Log object

M

makeLenient() - Method in class org.apache.commons.httpclient.params.HttpClientParams
 
makeLenient() - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Makes the HTTP methods attempt to mimic the exact behaviour of commonly used HTTP agents, which many HTTP servers expect, even though such behaviour may violate the HTTP protocol specification (RFC 2616 and other relevant RFCs).
makeStrict() - Method in class org.apache.commons.httpclient.params.HttpClientParams
 
makeStrict() - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Makes the HTTP methods strictly follow the HTTP protocol specification (RFC 2616 and other relevant RFCs).
MalformedChallengeException - Exception in org.apache.commons.httpclient.auth
Signals that authentication challenge is in some way invalid or illegal in the given context
MalformedChallengeException() - Constructor for exception org.apache.commons.httpclient.auth.MalformedChallengeException
Creates a new MalformedChallengeException with a null detail message.
MalformedChallengeException(String) - Constructor for exception org.apache.commons.httpclient.auth.MalformedChallengeException
Creates a new MalformedChallengeException with the specified message.
MalformedChallengeException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.auth.MalformedChallengeException
Creates a new MalformedChallengeException with the specified detail message and cause.
MalformedCookieException - Exception in org.apache.commons.httpclient.cookie
Signals that a cookie is in some way invalid or illegal in a given context
MalformedCookieException() - Constructor for exception org.apache.commons.httpclient.cookie.MalformedCookieException
Creates a new MalformedCookieException with a null detail message.
MalformedCookieException(String) - Constructor for exception org.apache.commons.httpclient.cookie.MalformedCookieException
Creates a new MalformedCookieException with a specified message string.
MalformedCookieException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.cookie.MalformedCookieException
Creates a new MalformedCookieException with the specified detail message and cause.
mark - Static variable in class org.apache.commons.httpclient.URI
BitSet for mark.
match(AuthScope) - Method in class org.apache.commons.httpclient.auth.AuthScope
Tests if the authentication scopes match.
match(Cookie, CookieOrigin) - Method in interface org.apache.commons.httpclient.cookie.CookieAttributeHandler
Matches the given value (property of the destination host where request is being submitted) with the corresponding cookie attribute.
match(String, int, String, boolean, Cookie) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Determines if a Cookie matches a location.
match(String, int, String, boolean, Cookie[]) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Determines which of an array of Cookies matches a location.
match(String, int, String, boolean, Cookie) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Return true if the cookie should be submitted with a request with given attributes, false otherwise.
match(String, int, String, boolean, Cookie[]) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Return an array of Cookies that should be submitted with a request with given attributes, false otherwise.
match(String, int, String, boolean, Cookie) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
 
match(String, int, String, boolean, Cookie[]) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
Returns an empty cookie array.
match(String, int, String, boolean, Cookie) - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
Return true if the cookie should be submitted with a request with given attributes, false otherwise.
MAX_HOST_CONNECTIONS - Static variable in class org.apache.commons.httpclient.params.HttpConnectionManagerParams
Defines the maximum number of connections allowed per host configuration.
MAX_REDIRECTS - Static variable in class org.apache.commons.httpclient.params.HttpClientParams
Defines the maximum number of redirects to be followed.
MAX_TOTAL_CONNECTIONS - Static variable in class org.apache.commons.httpclient.params.HttpConnectionManagerParams
Defines the maximum number of connections allowed overall.
MAXAGE - Static variable in class org.apache.commons.httpclient.cookie.Cookie2
 
MethodRetryHandler - Interface in org.apache.commons.httpclient
Deprecated. use HttpMethodRetryHandler
MULTIPART_BOUNDARY - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Sets the value to use as the multipart boundary.
MULTIPART_FORM_CONTENT_TYPE - Static variable in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. The Content-Type for multipart/form-data.
MultipartPostMethod - Class in org.apache.commons.httpclient.methods
Deprecated. Use MultipartRequestEntity in conjunction with PostMethod instead.
MultipartPostMethod() - Constructor for class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. No-arg constructor.
MultipartPostMethod(String) - Constructor for class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Constructor specifying a URI.
MultipartRequestEntity - Class in org.apache.commons.httpclient.methods.multipart
Implements a request entity suitable for an HTTP multipart POST method.
MultipartRequestEntity(Part[], HttpMethodParams) - Constructor for class org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity
Creates a new multipart entity containing the given parts.
MultiThreadedHttpConnectionManager - Class in org.apache.commons.httpclient
Manages a set of HttpConnections for various HostConfigurations.
MultiThreadedHttpConnectionManager() - Constructor for class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
No-args constructor

N

NAME - Static variable in class org.apache.commons.httpclient.ConnectMethod
the name of this method
NameValuePair - Class in org.apache.commons.httpclient
A simple class encapsulating a name/value pair.
NameValuePair() - Constructor for class org.apache.commons.httpclient.NameValuePair
Default constructor.
NameValuePair(String, String) - Constructor for class org.apache.commons.httpclient.NameValuePair
Constructor.
needContentLength() - Method in class org.apache.commons.httpclient.methods.OptionsMethod
Deprecated. only entity enclosing methods set content length header
net_path - Static variable in class org.apache.commons.httpclient.URI
BitSet for net_path.
NETSCAPE - Static variable in class org.apache.commons.httpclient.cookie.CookiePolicy
The Netscape cookie draft compliant policy.
NETSCAPE_DRAFT - Static variable in class org.apache.commons.httpclient.cookie.CookiePolicy
Deprecated. Use CookiePolicy.NETSCAPE
NetscapeDraftSpec - Class in org.apache.commons.httpclient.cookie
Netscape cookie draft specific cookie management functions
NetscapeDraftSpec() - Constructor for class org.apache.commons.httpclient.cookie.NetscapeDraftSpec
Default constructor
NoHttpResponseException - Exception in org.apache.commons.httpclient
Signals that the target server failed to respond with a valid HTTP response.
NoHttpResponseException() - Constructor for exception org.apache.commons.httpclient.NoHttpResponseException
Creates a new NoHttpResponseException with a null detail message.
NoHttpResponseException(String) - Constructor for exception org.apache.commons.httpclient.NoHttpResponseException
Creates a new NoHttpResponseException with the specified detail message.
NoHttpResponseException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.NoHttpResponseException
Creates a new NoHttpResponseException with the specified detail message and cause.
normalize(char[]) - Method in class org.apache.commons.httpclient.URI
Normalize the given hier path part.
normalize() - Method in class org.apache.commons.httpclient.URI
Normalizes the path part of this URI.
NTCredentials - Class in org.apache.commons.httpclient
Credentials for use with the NTLM authentication scheme which requires additional information.
NTCredentials() - Constructor for class org.apache.commons.httpclient.NTCredentials
Deprecated. Do not use. Null user name, domain & host no longer allowed
NTCredentials(String, String, String, String) - Constructor for class org.apache.commons.httpclient.NTCredentials
Constructor.
NTLM - Static variable in class org.apache.commons.httpclient.auth.AuthPolicy
The NTLM scheme is a proprietary Microsoft Windows Authentication protocol (considered to be the most secure among currently supported authentication schemes).
NTLMScheme - Class in org.apache.commons.httpclient.auth
An implementation of the Microsoft proprietary NTLM authentication scheme.
NTLMScheme() - Constructor for class org.apache.commons.httpclient.auth.NTLMScheme
Default constructor for the NTLM authentication scheme.
NTLMScheme(String) - Constructor for class org.apache.commons.httpclient.auth.NTLMScheme
Constructor for the NTLM authentication scheme.

O

opaque_part - Static variable in class org.apache.commons.httpclient.URI
URI bitset that combines uric_no_slash and uric.
open() - Method in class org.apache.commons.httpclient.HttpConnection
Establishes a connection to the specified host and port (via a proxy if specified).
OptionsMethod - Class in org.apache.commons.httpclient.methods
Implements the HTTP OPTIONS method.
OptionsMethod() - Constructor for class org.apache.commons.httpclient.methods.OptionsMethod
Method constructor.
OptionsMethod(String) - Constructor for class org.apache.commons.httpclient.methods.OptionsMethod
Constructor specifying a URI.
org.apache.commons.httpclient - package org.apache.commons.httpclient
Classes and interfaces supporting the client side of the HTTP protocol.
org.apache.commons.httpclient.auth - package org.apache.commons.httpclient.auth
Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests.
org.apache.commons.httpclient.cookie - package org.apache.commons.httpclient.cookie
Provides cookie handling in conjunction with Cookie.
org.apache.commons.httpclient.methods - package org.apache.commons.httpclient.methods
Classes implementing HttpMethod for the base HTTP methods.
org.apache.commons.httpclient.methods.multipart - package org.apache.commons.httpclient.methods.multipart
Provides Multipart support classes for the MultipartPostMethod.
org.apache.commons.httpclient.params - package org.apache.commons.httpclient.params
HttpClient preferences framework.
org.apache.commons.httpclient.protocol - package org.apache.commons.httpclient.protocol
Provides protocol specific socket factory handling.
org.apache.commons.httpclient.util - package org.apache.commons.httpclient.util
Provides some utility classes for use by HttpClient.

P

param - Static variable in class org.apache.commons.httpclient.URI
BitSet for param (alias for pchar).
ParameterFormatter - Class in org.apache.commons.httpclient.util
This formatter produces a textual representation of attribute/value pairs.
ParameterFormatter() - Constructor for class org.apache.commons.httpclient.util.ParameterFormatter
Default ParameterFormatter constructor
ParameterParser - Class in org.apache.commons.httpclient.util
A simple parser intended to parse sequences of name/value pairs.
ParameterParser() - Constructor for class org.apache.commons.httpclient.util.ParameterParser
Default ParameterParser constructor
parse(Cookie, String) - Method in interface org.apache.commons.httpclient.cookie.CookieAttributeHandler
Parse the given cookie attribute value and update the corresponding Cookie property.
parse(String, int, String, boolean, String) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Parse the "Set-Cookie" header value into Cookie array.
parse(String, int, String, boolean, Header) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Parse the "Set-Cookie" Header into an array of Cookies.
parse(String, int, String, boolean, String) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Parses the Set-Cookie value into an array of Cookies.
parse(String, int, String, boolean, Header) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Parse the "Set-Cookie" Header into an array of Cookies.
parse(String, int, String, boolean, String) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
Returns an empty cookie array.
parse(String, int, String, boolean, Header) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
Returns an empty cookie array.
parse(String, int, String, boolean, String) - Method in class org.apache.commons.httpclient.cookie.NetscapeDraftSpec
Parses the Set-Cookie value into an array of Cookies.
parse(String, int, String, boolean, Header) - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
Parses the Set-Cookie2 value into an array of Cookies.
parse(String, int, String, boolean, String) - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
 
parse(String) - Static method in class org.apache.commons.httpclient.HeaderElement
Deprecated. Use #parseElements(String).
parse(String) - Static method in class org.apache.commons.httpclient.HttpVersion
Parses the textual representation of the given HTTP protocol version.
parse(String, char) - Method in class org.apache.commons.httpclient.util.ParameterParser
Extracts a list of NameValuePairs from the given string.
parse(char[], char) - Method in class org.apache.commons.httpclient.util.ParameterParser
Extracts a list of NameValuePairs from the given array of characters.
parse(char[], int, int, char) - Method in class org.apache.commons.httpclient.util.ParameterParser
Extracts a list of NameValuePairs from the given array of characters.
parseAttribute(NameValuePair, Cookie) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Parse the cookie attribute and update the corresponsing Cookie properties.
parseAttribute(NameValuePair, Cookie) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Parse the cookie attribute and update the corresponsing Cookie properties.
parseAttribute(NameValuePair, Cookie) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
Does nothing.
parseAttribute(NameValuePair, Cookie) - Method in class org.apache.commons.httpclient.cookie.NetscapeDraftSpec
Parse the cookie attribute and update the corresponsing Cookie properties as defined by the Netscape draft specification
parseAttribute(NameValuePair, Cookie) - Method in class org.apache.commons.httpclient.cookie.RFC2109Spec
Parse RFC 2109 specific cookie attribute and update the corresponsing Cookie properties.
parseAttribute(NameValuePair, Cookie) - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
Parse RFC 2965 specific cookie attribute and update the corresponsing Cookie properties.
parseAuthority(String, boolean) - Method in class org.apache.commons.httpclient.URI
Parse the authority component.
parseChallenges(Header[]) - Static method in class org.apache.commons.httpclient.auth.AuthChallengeParser
Extracts a map of challenges ordered by authentication scheme name
parseDate(String) - Static method in class org.apache.commons.httpclient.util.DateParser
Deprecated. Parses a date value.
parseDate(String, Collection) - Static method in class org.apache.commons.httpclient.util.DateParser
Deprecated. Parses the date value using the given date formats.
parseDate(String) - Static method in class org.apache.commons.httpclient.util.DateUtil
Parses a date value.
parseDate(String, Collection) - Static method in class org.apache.commons.httpclient.util.DateUtil
Parses the date value using the given date formats.
parseDate(String, Collection, Date) - Static method in class org.apache.commons.httpclient.util.DateUtil
Parses the date value using the given date formats.
parseElements(char[]) - Static method in class org.apache.commons.httpclient.HeaderElement
This parses the value part of a header.
parseElements(String) - Static method in class org.apache.commons.httpclient.HeaderElement
This parses the value part of a header.
parseHeaders(InputStream, String) - Static method in class org.apache.commons.httpclient.HttpParser
Parses headers from the given stream.
parseHeaders(InputStream) - Static method in class org.apache.commons.httpclient.HttpParser
Deprecated. use #parseHeaders(InputStream, String)
parseUriReference(String, boolean) - Method in class org.apache.commons.httpclient.URI
In order to avoid any possilbity of conflict with non-ASCII characters, Parse a URI reference as a String with the character encoding of the local system or the document.
PARSING - Static variable in exception org.apache.commons.httpclient.URIException
The URI parsing error.
Part - Class in org.apache.commons.httpclient.methods.multipart
Abstract class for one Part of a multipart post object.
Part() - Constructor for class org.apache.commons.httpclient.methods.multipart.Part
 
PartBase - Class in org.apache.commons.httpclient.methods.multipart
Provides setters and getters for the basic Part properties.
PartBase(String, String, String, String) - Constructor for class org.apache.commons.httpclient.methods.multipart.PartBase
Constructor.
parts - Variable in class org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity
The MIME parts as set by the constructor
PartSource - Interface in org.apache.commons.httpclient.methods.multipart
An interface for providing access to data when posting MultiPart messages.
PATH - Static variable in class org.apache.commons.httpclient.cookie.Cookie2
 
path - Static variable in class org.apache.commons.httpclient.URI
URI bitset that combines absolute path and opaque part.
PATH_DELIM - Static variable in interface org.apache.commons.httpclient.cookie.CookieSpec
Path delimiter
PATH_DELIM_CHAR - Static variable in interface org.apache.commons.httpclient.cookie.CookieSpec
Path delimiting charachter
path_segments - Static variable in class org.apache.commons.httpclient.URI
BitSet for path segments.
pathMatch(String, String) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Performs path-match as defined by the cookie specification.
pathMatch(String, String) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Performs path-match as implemented in common browsers.
pathMatch(String, String) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
 
PATTERN_ASCTIME - Static variable in class org.apache.commons.httpclient.util.DateParser
Deprecated. Date format pattern used to parse HTTP date headers in ANSI C asctime() format.
PATTERN_ASCTIME - Static variable in class org.apache.commons.httpclient.util.DateUtil
Date format pattern used to parse HTTP date headers in ANSI C asctime() format.
PATTERN_RFC1036 - Static variable in class org.apache.commons.httpclient.util.DateParser
Deprecated. Date format pattern used to parse HTTP date headers in RFC 1036 format.
PATTERN_RFC1036 - Static variable in class org.apache.commons.httpclient.util.DateUtil
Date format pattern used to parse HTTP date headers in RFC 1036 format.
PATTERN_RFC1123 - Static variable in class org.apache.commons.httpclient.util.DateParser
Deprecated. Date format pattern used to parse HTTP date headers in RFC 1123 format.
PATTERN_RFC1123 - Static variable in class org.apache.commons.httpclient.util.DateUtil
Date format pattern used to parse HTTP date headers in RFC 1123 format.
pchar - Static variable in class org.apache.commons.httpclient.URI
BitSet for pchar.
percent - Static variable in class org.apache.commons.httpclient.URI
The percent "%" character always has the reserved purpose of being the escape indicator, it must be escaped as "%25" in order to be used as data within a URI.
PORT - Static variable in class org.apache.commons.httpclient.cookie.Cookie2
 
port - Static variable in class org.apache.commons.httpclient.URI
Port, a logical alias for digit.
PostMethod - Class in org.apache.commons.httpclient.methods
Implements the HTTP POST method.
PostMethod() - Constructor for class org.apache.commons.httpclient.methods.PostMethod
No-arg constructor.
PostMethod(String) - Constructor for class org.apache.commons.httpclient.methods.PostMethod
Constructor specifying a URI.
PREEMPTIVE_AUTH_SCHEME - Static variable in class org.apache.commons.httpclient.auth.AuthState
 
PREEMPTIVE_AUTHENTICATION - Static variable in class org.apache.commons.httpclient.params.HttpClientParams
Defines whether authentication should be attempted preemptively.
PREEMPTIVE_DEFAULT - Static variable in class org.apache.commons.httpclient.HttpState
Deprecated. This field and feature will be removed following HttpClient 3.0.
PREEMPTIVE_PROPERTY - Static variable in class org.apache.commons.httpclient.HttpState
Deprecated. This field and feature will be removed following HttpClient 3.0.
prevalidate(String, BitSet) - Method in class org.apache.commons.httpclient.URI
Pre-validate the unescaped URI string within a specific component.
print(String) - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. Use HttpConnection.print(String, String) Writes the specified String (as bytes) to the output stream.
print(String, String) - Method in class org.apache.commons.httpclient.HttpConnection
Writes the specified String (as bytes) to the output stream.
printLine(String) - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. Use HttpConnection.printLine(String, String) Writes the specified String (as bytes), followed by "\r\n".getBytes() to the output stream.
printLine(String, String) - Method in class org.apache.commons.httpclient.HttpConnection
Writes the specified String (as bytes), followed by "\r\n".getBytes() to the output stream.
printLine() - Method in class org.apache.commons.httpclient.HttpConnection
Writes "\r\n".getBytes() to the output stream.
printStackTrace() - Method in exception org.apache.commons.httpclient.HttpException
Print this HttpException and its stack trace to the standard error stream.
printStackTrace(PrintStream) - Method in exception org.apache.commons.httpclient.HttpException
Print this HttpException and its stack trace to the specified print stream.
printStackTrace(PrintWriter) - Method in exception org.apache.commons.httpclient.HttpException
Print this HttpException and its stack trace to the specified print writer.
processChallenge(AuthState, Map) - Method in class org.apache.commons.httpclient.auth.AuthChallengeProcessor
Processes the given collection of challenges and updates the state of the authentication process.
processChallenge(String) - Method in interface org.apache.commons.httpclient.auth.AuthScheme
Processes the given challenge token.
processChallenge(String) - Method in class org.apache.commons.httpclient.auth.BasicScheme
Processes the Basic challenge.
processChallenge(String) - Method in class org.apache.commons.httpclient.auth.DigestScheme
Processes the Digest challenge.
processChallenge(String) - Method in class org.apache.commons.httpclient.auth.NTLMScheme
Processes the NTLM challenge.
processChallenge(String) - Method in class org.apache.commons.httpclient.auth.RFC2617Scheme
Processes the given challenge token.
processCookieHeaders(CookieSpec, Header[], HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
This method processes the specified cookie headers.
processResponseBody(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
This method is invoked immediately after HttpMethodBase.readResponseBody(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom body processing.
processResponseHeaders(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
This method is invoked immediately after HttpMethodBase.readResponseHeaders(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom response headers processing.
processResponseHeaders(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.methods.OptionsMethod
This implementation will parse the Allow header to obtain the set of methods supported by the resource identified by the Request-URI.
processStatusLine(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
This method is invoked immediately after HttpMethodBase.readStatusLine(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom response status line processing.
Protocol - Class in org.apache.commons.httpclient.protocol
A class to encapsulate the specifics of a protocol.
Protocol(String, ProtocolSocketFactory, int) - Constructor for class org.apache.commons.httpclient.protocol.Protocol
Constructs a new Protocol.
Protocol(String, SecureProtocolSocketFactory, int) - Constructor for class org.apache.commons.httpclient.protocol.Protocol
Deprecated. Use the constructor that uses ProtocolSocketFactory, this version of the constructor is only kept for backwards API compatibility.
PROTOCOL_CHARSET - Static variable in exception org.apache.commons.httpclient.URI.DefaultCharsetChanged
Protocol charset changed.
PROTOCOL_VERSION - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines the HTTP protocol version used by HTTP methods per default.
protocolCharset - Variable in class org.apache.commons.httpclient.URI
The charset of the protocol used by this URI instance.
ProtocolException - Exception in org.apache.commons.httpclient
Signals that an HTTP protocol violation has occurred.
ProtocolException() - Constructor for exception org.apache.commons.httpclient.ProtocolException
Creates a new ProtocolException with a null detail message.
ProtocolException(String) - Constructor for exception org.apache.commons.httpclient.ProtocolException
Creates a new ProtocolException with the specified detail message.
ProtocolException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.ProtocolException
Creates a new ProtocolException with the specified detail message and cause.
ProtocolSocketFactory - Interface in org.apache.commons.httpclient.protocol
A factory for creating Sockets.
PROVIDER - Static variable in interface org.apache.commons.httpclient.auth.CredentialsProvider
Sets the credentials provider parameter.
PROXY_AUTH - Static variable in class org.apache.commons.httpclient.auth.HttpAuthenticator
Deprecated. The proxy authenticate challange header.
PROXY_AUTH_RESP - Static variable in class org.apache.commons.httpclient.auth.HttpAuthenticator
Deprecated. The proxy authenticate response header.
ProxyClient - Class in org.apache.commons.httpclient
A client that provides sockets for communicating through HTTP proxies via the HTTP CONNECT method.
ProxyClient() - Constructor for class org.apache.commons.httpclient.ProxyClient
Creates an instance of ProxyClient using default parameter set.
ProxyClient(HttpClientParams) - Constructor for class org.apache.commons.httpclient.ProxyClient
Creates an instance of ProxyClient using the given parameter set.
ProxyClient.ConnectResponse - Class in org.apache.commons.httpclient
Contains the method used to execute the connect along with the created socket.
proxyCred - Variable in class org.apache.commons.httpclient.HttpState
Map of proxy credentials by realm that this HTTP state contains
proxyEquals(HttpConnection) - Method in class org.apache.commons.httpclient.HostConfiguration
Tests if the proxy configuration equals the configuration set on the connection.
ProxyHost - Class in org.apache.commons.httpclient
Holds all of the variables needed to describe an HTTP connection to a proxy.
ProxyHost(ProxyHost) - Constructor for class org.apache.commons.httpclient.ProxyHost
Copy constructor for HttpHost
ProxyHost(String, int) - Constructor for class org.apache.commons.httpclient.ProxyHost
Constructor for ProxyHost.
ProxyHost(String) - Constructor for class org.apache.commons.httpclient.ProxyHost
Constructor for HttpHost.
PUNYCODE - Static variable in exception org.apache.commons.httpclient.URIException
The DNS punycode encoding or decoding error.
purgeExpiredCookies() - Method in class org.apache.commons.httpclient.HttpState
Removes all of cookies in this HTTP state that have expired according to the current system time.
purgeExpiredCookies(Date) - Method in class org.apache.commons.httpclient.HttpState
Removes all of cookies in this HTTP state that have expired by the specified date.
PutMethod - Class in org.apache.commons.httpclient.methods
Implements the HTTP PUT method.
PutMethod() - Constructor for class org.apache.commons.httpclient.methods.PutMethod
No-arg constructor.
PutMethod(String) - Constructor for class org.apache.commons.httpclient.methods.PutMethod
Constructor specifying a URI.

Q

query - Static variable in class org.apache.commons.httpclient.URI
BitSet for query (alias for uric).
QUOTE - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Content dispostion characters
QUOTE_BYTES - Static variable in class org.apache.commons.httpclient.methods.multipart.Part
Content dispostion as a byte array

R

read() - Method in class org.apache.commons.httpclient.ChunkedInputStream
Returns all the data in a chunked stream in coalesced form.
read(byte[], int, int) - Method in class org.apache.commons.httpclient.ChunkedInputStream
Read some bytes from the stream.
read(byte[]) - Method in class org.apache.commons.httpclient.ChunkedInputStream
Read some bytes from the stream.
read() - Method in class org.apache.commons.httpclient.ContentLengthInputStream
Read the next byte from the stream
read(byte[], int, int) - Method in class org.apache.commons.httpclient.ContentLengthInputStream
Does standard InputStream.read(byte[], int, int) behavior, but also notifies the watcher when the contents have been consumed.
read(byte[]) - Method in class org.apache.commons.httpclient.ContentLengthInputStream
Read more bytes from the stream.
readLine() - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. use #readLine(String)
readLine(String) - Method in class org.apache.commons.httpclient.HttpConnection
Reads up to "\n" from the (unchunked) input stream.
readLine(InputStream, String) - Static method in class org.apache.commons.httpclient.HttpParser
Read up to "\n" from an (unchunked) input stream.
readLine(InputStream) - Static method in class org.apache.commons.httpclient.HttpParser
Deprecated. use #readLine(InputStream, String)
readRawLine(InputStream) - Static method in class org.apache.commons.httpclient.HttpParser
Return byte array from an (unchunked) input stream.
readResponse(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Reads the response from the given connection.
readResponseBody(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Read the response body from the given HttpConnection.
readResponseBody(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.methods.HeadMethod
Overrides HttpMethodBase method to not read a response body, despite the presence of a Content-Length or Transfer-Encoding header.
readResponseHeaders(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Reads the response headers from the given connection.
readStatusLine(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Read the status line from the given HttpConnection, setting my status code and status text.
reason - Variable in exception org.apache.commons.httpclient.URIException
The reason message.
reasonCode - Variable in exception org.apache.commons.httpclient.URIException
The reason code.
recycle() - Method in interface org.apache.commons.httpclient.HttpMethod
Deprecated. no longer supported and will be removed in the future version of HttpClient
recycle() - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. no longer supported and will be removed in the future version of HttpClient
recycle() - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Deprecated. no longer supported and will be removed in the future version of HttpClient
recycle() - Method in class org.apache.commons.httpclient.methods.GetMethod
Deprecated. no longer supported and will be removed in the future version of HttpClient
recycle() - Method in class org.apache.commons.httpclient.methods.HeadMethod
Deprecated. no longer supported and will be removed in the future version of HttpClient
recycle() - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. no longer supported and will be removed in the future version of HttpClient
recycle() - Method in class org.apache.commons.httpclient.methods.TraceMethod
Deprecated. no longer supported and will be removed in the future version of HttpClient
RedirectException - Exception in org.apache.commons.httpclient
Signals violation of HTTP specification caused by an invalid redirect
RedirectException() - Constructor for exception org.apache.commons.httpclient.RedirectException
Creates a new RedirectException with a null detail message.
RedirectException(String) - Constructor for exception org.apache.commons.httpclient.RedirectException
Creates a new RedirectException with the specified detail message.
RedirectException(String, Throwable) - Constructor for exception org.apache.commons.httpclient.RedirectException
Creates a new RedirectException with the specified detail message and cause.
ReflectionSocketFactory - Class in org.apache.commons.httpclient.protocol
This helper class uses refelction in order to execute Socket methods available in Java 1.4 and above
reg_name - Static variable in class org.apache.commons.httpclient.URI
BitSet for reg_name.
registerAttribHandler(String, CookieAttributeHandler) - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
 
registerAuthScheme(String, Class) - Static method in class org.apache.commons.httpclient.auth.AuthPolicy
Registers a class implementing an authentication scheme with the given identifier.
registerCookieSpec(String, Class) - Static method in class org.apache.commons.httpclient.cookie.CookiePolicy
Registers a new cookie specification with the given identifier.
registerProtocol(String, Protocol) - Static method in class org.apache.commons.httpclient.protocol.Protocol
Registers a new protocol with the given identifier.
REJECT_HEAD_BODY - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines whether the content body sent in response to HeadMethod should be rejected.
REJECT_RELATIVE_REDIRECT - Static variable in class org.apache.commons.httpclient.params.HttpClientParams
Defines whether relative redirects should be rejected.
rel_path - Static variable in class org.apache.commons.httpclient.URI
BitSet for rel_path.
rel_segment - Static variable in class org.apache.commons.httpclient.URI
BitSet for rel_segment.
relativeURI - Static variable in class org.apache.commons.httpclient.URI
BitSet for relativeURI.
releaseConnection() - Method in class org.apache.commons.httpclient.HttpConnection
Releases the connection.
releaseConnection(HttpConnection) - Method in interface org.apache.commons.httpclient.HttpConnectionManager
Releases the given HttpConnection for use by other requests.
releaseConnection() - Method in interface org.apache.commons.httpclient.HttpMethod
Releases the connection being used by this HTTP method.
releaseConnection() - Method in class org.apache.commons.httpclient.HttpMethodBase
Releases the connection being used by this HTTP method.
releaseConnection(HttpConnection) - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Make the given HttpConnection available for use by other requests.
releaseConnection(HttpConnection) - Method in class org.apache.commons.httpclient.SimpleHttpConnectionManager
 
remove(HttpConnection) - Method in class org.apache.commons.httpclient.util.IdleConnectionHandler
Removes the given connection from the list of connections to be closed when idle.
removeAll() - Method in class org.apache.commons.httpclient.util.IdleConnectionHandler
Removes all connections referenced by this handler.
removeConnectionManager(HttpConnectionManager) - Method in class org.apache.commons.httpclient.util.IdleConnectionTimeoutThread
Removes the connection manager from this class.
removeFragmentIdentifier(char[]) - Method in class org.apache.commons.httpclient.URI
Remove the fragment identifier of the given component.
removeHeader(Header) - Method in class org.apache.commons.httpclient.HeaderGroup
Removes the given header.
removeParameter(String) - Method in class org.apache.commons.httpclient.methods.PostMethod
Removes all parameters with the given paramName.
removeParameter(String, String) - Method in class org.apache.commons.httpclient.methods.PostMethod
Removes all parameter with the given paramName and paramValue.
removeRequestHeader(String) - Method in interface org.apache.commons.httpclient.HttpMethod
Removes all request headers with the given name.
removeRequestHeader(Header) - Method in interface org.apache.commons.httpclient.HttpMethod
Removes the given request header.
removeRequestHeader(String) - Method in class org.apache.commons.httpclient.HttpMethodBase
Remove the request header associated with the given name.
removeRequestHeader(Header) - Method in class org.apache.commons.httpclient.HttpMethodBase
Removes the given request header.
replace(String, char[], char[]) - Static method in class org.apache.commons.httpclient.util.URIUtil.Coder
Deprecated. Replace from a given character to given character in an array order for a given string.
replace(String, char, char) - Static method in class org.apache.commons.httpclient.util.URIUtil.Coder
Deprecated. Replace from a given character to given character for a given string.
RequestEntity - Interface in org.apache.commons.httpclient.methods
 
reserved - Static variable in class org.apache.commons.httpclient.URI
BitSet for reserved.
resolvePath(char[], char[]) - Method in class org.apache.commons.httpclient.URI
Resolve the base and relative path.
resolvePort(int) - Method in class org.apache.commons.httpclient.protocol.Protocol
Resolves the correct port for this protocol.
responseBodyConsumed() - Method in class org.apache.commons.httpclient.HttpMethodBase
A response has been consumed.
RETRY_HANDLER - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Sets the method retry handler parameter.
retryMethod(HttpMethod, IOException, int) - Method in class org.apache.commons.httpclient.DefaultHttpMethodRetryHandler
Used retryCount and requestSentRetryEnabled to determine if the given method should be retried.
retryMethod(HttpMethod, HttpConnection, HttpRecoverableException, int, boolean) - Method in class org.apache.commons.httpclient.DefaultMethodRetryHandler
Deprecated. Used retryCount and requestSentRetryEnabled to determine if the given method should be retried.
retryMethod(HttpMethod, IOException, int) - Method in interface org.apache.commons.httpclient.HttpMethodRetryHandler
Determines if a method should be retried after an HttpRecoverableException occurs during execution.
retryMethod(HttpMethod, HttpConnection, HttpRecoverableException, int, boolean) - Method in interface org.apache.commons.httpclient.MethodRetryHandler
Deprecated. Determines if a method should be retried after an HttpRecoverableException occurs during execution.
RFC2109 - Static variable in class org.apache.commons.httpclient.cookie.CookiePolicy
Deprecated. Use CookiePolicy.RFC_2109
RFC2109Spec - Class in org.apache.commons.httpclient.cookie
RFC 2109 specific cookie management functions
RFC2109Spec() - Constructor for class org.apache.commons.httpclient.cookie.RFC2109Spec
Default constructor
RFC2617Scheme - Class in org.apache.commons.httpclient.auth
Abstract authentication scheme class that lays foundation for all RFC 2617 compliant authetication schemes and provides capabilities common to all authentication schemes defined in RFC 2617.
RFC2617Scheme() - Constructor for class org.apache.commons.httpclient.auth.RFC2617Scheme
Default constructor for RFC2617 compliant authetication schemes.
RFC2617Scheme(String) - Constructor for class org.apache.commons.httpclient.auth.RFC2617Scheme
Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
RFC2965 - Static variable in class org.apache.commons.httpclient.cookie.CookiePolicy
Deprecated. Use CookiePolicy.RFC_2965
RFC2965Spec - Class in org.apache.commons.httpclient.cookie
RFC 2965 specific cookie management functions.
RFC2965Spec() - Constructor for class org.apache.commons.httpclient.cookie.RFC2965Spec
Default constructor
RFC_2109 - Static variable in class org.apache.commons.httpclient.cookie.CookiePolicy
The RFC 2109 compliant policy.
RFC_2965 - Static variable in class org.apache.commons.httpclient.cookie.CookiePolicy
The RFC 2965 compliant policy.
rootPath - Static variable in class org.apache.commons.httpclient.URI
The root path.
run() - Method in class org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory.SocketTask
Execute the logic in this object and keep track of any exceptions.
run() - Method in class org.apache.commons.httpclient.util.IdleConnectionTimeoutThread
Closes idle connections.

S

SC_ACCEPTED - Static variable in class org.apache.commons.httpclient.HttpStatus
202 Accepted (HTTP/1.0 - RFC 1945)
SC_BAD_GATEWAY - Static variable in class org.apache.commons.httpclient.HttpStatus
502 Bad Gateway (HTTP/1.0 - RFC 1945)
SC_BAD_REQUEST - Static variable in class org.apache.commons.httpclient.HttpStatus
400 Bad Request (HTTP/1.1 - RFC 2616)
SC_CONFLICT - Static variable in class org.apache.commons.httpclient.HttpStatus
409 Conflict (HTTP/1.1 - RFC 2616)
SC_CONTINUE - Static variable in class org.apache.commons.httpclient.HttpStatus
100 Continue (HTTP/1.1 - RFC 2616)
SC_CREATED - Static variable in class org.apache.commons.httpclient.HttpStatus
201 Created (HTTP/1.0 - RFC 1945)
SC_EXPECTATION_FAILED - Static variable in class org.apache.commons.httpclient.HttpStatus
417 Expectation Failed (HTTP/1.1 - RFC 2616)
SC_FAILED_DEPENDENCY - Static variable in class org.apache.commons.httpclient.HttpStatus
424 Failed Dependency (WebDAV - RFC 2518)
SC_FORBIDDEN - Static variable in class org.apache.commons.httpclient.HttpStatus
403 Forbidden (HTTP/1.0 - RFC 1945)
SC_GATEWAY_TIMEOUT - Static variable in class org.apache.commons.httpclient.HttpStatus
504 Gateway Timeout (HTTP/1.1 - RFC 2616)
SC_GONE - Static variable in class org.apache.commons.httpclient.HttpStatus
410 Gone (HTTP/1.1 - RFC 2616)
SC_HTTP_VERSION_NOT_SUPPORTED - Static variable in class org.apache.commons.httpclient.HttpStatus
505 HTTP Version Not Supported (HTTP/1.1 - RFC 2616)
SC_INSUFFICIENT_SPACE_ON_RESOURCE - Static variable in class org.apache.commons.httpclient.HttpStatus
Static constant for a 419 error.
SC_INSUFFICIENT_STORAGE - Static variable in class org.apache.commons.httpclient.HttpStatus
507 Insufficient Storage (WebDAV - RFC 2518)
SC_INTERNAL_SERVER_ERROR - Static variable in class org.apache.commons.httpclient.HttpStatus
500 Server Error (HTTP/1.0 - RFC 1945)
SC_LENGTH_REQUIRED - Static variable in class org.apache.commons.httpclient.HttpStatus
411 Length Required (HTTP/1.1 - RFC 2616)
SC_LOCKED - Static variable in class org.apache.commons.httpclient.HttpStatus
423 Locked (WebDAV - RFC 2518)
SC_METHOD_FAILURE - Static variable in class org.apache.commons.httpclient.HttpStatus
Static constant for a 420 error.
SC_METHOD_NOT_ALLOWED - Static variable in class org.apache.commons.httpclient.HttpStatus
405 Method Not Allowed (HTTP/1.1 - RFC 2616)
SC_MOVED_PERMANENTLY - Static variable in class org.apache.commons.httpclient.HttpStatus
301 Moved Permanently (HTTP/1.0 - RFC 1945)
SC_MOVED_TEMPORARILY - Static variable in class org.apache.commons.httpclient.HttpStatus
302 Moved Temporarily (Sometimes Found) (HTTP/1.0 - RFC 1945)
SC_MULTI_STATUS - Static variable in class org.apache.commons.httpclient.HttpStatus
207 Multi-Status (WebDAV - RFC 2518) or 207 Partial Update OK (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?)
SC_MULTIPLE_CHOICES - Static variable in class org.apache.commons.httpclient.HttpStatus
300 Mutliple Choices (HTTP/1.1 - RFC 2616)
SC_NO_CONTENT - Static variable in class org.apache.commons.httpclient.HttpStatus
204 No Content (HTTP/1.0 - RFC 1945)
SC_NON_AUTHORITATIVE_INFORMATION - Static variable in class org.apache.commons.httpclient.HttpStatus
203 Non Authoritative Information (HTTP/1.1 - RFC 2616)
SC_NOT_ACCEPTABLE - Static variable in class org.apache.commons.httpclient.HttpStatus
406 Not Acceptable (HTTP/1.1 - RFC 2616)
SC_NOT_FOUND - Static variable in class org.apache.commons.httpclient.HttpStatus
404 Not Found (HTTP/1.0 - RFC 1945)
SC_NOT_IMPLEMENTED - Static variable in class org.apache.commons.httpclient.HttpStatus
501 Not Implemented (HTTP/1.0 - RFC 1945)
SC_NOT_MODIFIED - Static variable in class org.apache.commons.httpclient.HttpStatus
304 Not Modified (HTTP/1.0 - RFC 1945)
SC_OK - Static variable in class org.apache.commons.httpclient.HttpStatus
200 OK (HTTP/1.0 - RFC 1945)
SC_PARTIAL_CONTENT - Static variable in class org.apache.commons.httpclient.HttpStatus
206 Partial Content (HTTP/1.1 - RFC 2616)
SC_PAYMENT_REQUIRED - Static variable in class org.apache.commons.httpclient.HttpStatus
402 Payment Required (HTTP/1.1 - RFC 2616)
SC_PRECONDITION_FAILED - Static variable in class org.apache.commons.httpclient.HttpStatus
412 Precondition Failed (HTTP/1.1 - RFC 2616)
SC_PROCESSING - Static variable in class org.apache.commons.httpclient.HttpStatus
102 Processing (WebDAV - RFC 2518)
SC_PROXY_AUTHENTICATION_REQUIRED - Static variable in class org.apache.commons.httpclient.HttpStatus
407 Proxy Authentication Required (HTTP/1.1 - RFC 2616)
SC_REQUEST_TIMEOUT - Static variable in class org.apache.commons.httpclient.HttpStatus
408 Request Timeout (HTTP/1.1 - RFC 2616)
SC_REQUEST_TOO_LONG - Static variable in class org.apache.commons.httpclient.HttpStatus
413 Request Entity Too Large (HTTP/1.1 - RFC 2616)
SC_REQUEST_URI_TOO_LONG - Static variable in class org.apache.commons.httpclient.HttpStatus
414 Request-URI Too Long (HTTP/1.1 - RFC 2616)
SC_REQUESTED_RANGE_NOT_SATISFIABLE - Static variable in class org.apache.commons.httpclient.HttpStatus
416 Requested Range Not Satisfiable (HTTP/1.1 - RFC 2616)
SC_RESET_CONTENT - Static variable in class org.apache.commons.httpclient.HttpStatus
205 Reset Content (HTTP/1.1 - RFC 2616)
SC_SEE_OTHER - Static variable in class org.apache.commons.httpclient.HttpStatus
303 See Other (HTTP/1.1 - RFC 2616)
SC_SERVICE_UNAVAILABLE - Static variable in class org.apache.commons.httpclient.HttpStatus
503 Service Unavailable (HTTP/1.0 - RFC 1945)
SC_SWITCHING_PROTOCOLS - Static variable in class org.apache.commons.httpclient.HttpStatus
101 Switching Protocols (HTTP/1.1 - RFC 2616)
SC_TEMPORARY_REDIRECT - Static variable in class org.apache.commons.httpclient.HttpStatus
307 Temporary Redirect (HTTP/1.1 - RFC 2616)
SC_UNAUTHORIZED - Static variable in class org.apache.commons.httpclient.HttpStatus
401 Unauthorized (HTTP/1.0 - RFC 1945)
SC_UNPROCESSABLE_ENTITY - Static variable in class org.apache.commons.httpclient.HttpStatus
422 Unprocessable Entity (WebDAV - RFC 2518)
SC_UNSUPPORTED_MEDIA_TYPE - Static variable in class org.apache.commons.httpclient.HttpStatus
415 Unsupported Media Type (HTTP/1.1 - RFC 2616)
SC_USE_PROXY - Static variable in class org.apache.commons.httpclient.HttpStatus
305 Use Proxy (HTTP/1.1 - RFC 2616)
scheme - Static variable in class org.apache.commons.httpclient.URI
BitSet for scheme.
SECURE - Static variable in class org.apache.commons.httpclient.cookie.Cookie2
 
SecureProtocolSocketFactory - Interface in org.apache.commons.httpclient.protocol
A ProtocolSocketFactory that is secure.
segment - Static variable in class org.apache.commons.httpclient.URI
BitSet for segment.
selectAuthScheme(Map) - Method in class org.apache.commons.httpclient.auth.AuthChallengeProcessor
Determines the preferred authentication scheme that can be used to respond to the given collection of challenges.
selectAuthScheme(Header[]) - Static method in class org.apache.commons.httpclient.auth.HttpAuthenticator
Deprecated. Use AuthChallengeParser.parseChallenges(Header[]) and AuthPolicy.getAuthScheme(String)
send(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.Part
Write all the data to the output stream.
sendContentTypeHeader(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.Part
Write the content type header to the specified output stream
sendData(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.FilePart
Write the data in "source" to the specified stream.
sendData(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.Part
Write the data to the specified output stream
sendData(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.StringPart
Writes the data to the given OutputStream.
sendDispositionHeader(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.FilePart
Write the disposition header to the output stream
sendDispositionHeader(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.Part
Write the content disposition header to the specified output stream
sendEnd(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.Part
Write the end data to the output stream.
sendEndOfHeader(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.Part
Write the end of the header to the output stream
sendParts(OutputStream, Part[]) - Static method in class org.apache.commons.httpclient.methods.multipart.Part
Write all parts and the last boundary to the specified output stream.
sendParts(OutputStream, Part[], byte[]) - Static method in class org.apache.commons.httpclient.methods.multipart.Part
Write all parts and the last boundary to the specified output stream.
sendStart(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.Part
Write the start to the specified output stream
sendTransferEncodingHeader(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.Part
Write the content transfer encoding header to the specified output stream
server - Static variable in class org.apache.commons.httpclient.URI
Bitset for server.
SET_COOKIE2_KEY - Static variable in class org.apache.commons.httpclient.cookie.RFC2965Spec
Cookie Response Header name for cookies processed by this spec.
SET_COOKIE_KEY - Static variable in class org.apache.commons.httpclient.cookie.RFC2109Spec
Cookie Response Header name for cookies processed by this spec.
setAllowUserInteraction(boolean) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not available: the data must have already been retrieved.
setAlwaysUseQuotes(boolean) - Method in class org.apache.commons.httpclient.util.ParameterFormatter
Defines whether all parameter values must be enclosed in quotation marks, even if they do not contain any special characters
setAuthAttempted(boolean) - Method in class org.apache.commons.httpclient.auth.AuthState
Sets authentication attempt status
setAuthenticationPreemptive(boolean) - Method in class org.apache.commons.httpclient.HttpState
Deprecated. Use HttpClientParams.setAuthenticationPreemptive(boolean), HttpClient.getParams().
setAuthenticationPreemptive(boolean) - Method in class org.apache.commons.httpclient.params.HttpClientParams
Sets whether authentication should be attempted preemptively.
setAuthRequested(boolean) - Method in class org.apache.commons.httpclient.auth.AuthState
Sets authentication request status
setAuthScheme(AuthScheme) - Method in class org.apache.commons.httpclient.auth.AuthState
Assigns the given authentication scheme.
setBodyCheckTimeout(int) - Method in class org.apache.commons.httpclient.methods.HeadMethod
Deprecated. Use HttpMethodParams
setBooleanParameter(String, boolean) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
setBooleanParameter(String, boolean) - Method in interface org.apache.commons.httpclient.params.HttpParams
Assigns a Boolean to the parameter with the given name
setCharSet(String) - Method in class org.apache.commons.httpclient.methods.multipart.PartBase
Sets the character encoding.
setCharSet(String) - Method in class org.apache.commons.httpclient.methods.multipart.StringPart
 
setComment(String) - Method in class org.apache.commons.httpclient.Cookie
If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment.
setCommentURL(String) - Method in class org.apache.commons.httpclient.cookie.Cookie2
If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL.
setConnectionCloseForced(boolean) - Method in class org.apache.commons.httpclient.HttpMethodBase
Sets whether or not the connection should be force-closed when no longer needed.
setConnectionManagerClass(Class) - Method in class org.apache.commons.httpclient.params.HttpClientParams
Sets HTTP connection manager class to be used der default.
setConnectionManagerTimeout(long) - Method in class org.apache.commons.httpclient.params.HttpClientParams
Sets the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.
setConnectionStaleCheckingEnabled(boolean) - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Deprecated. Use HttpConnectionParams.setStaleCheckingEnabled(boolean), HttpConnectionManager.getParams().
setConnectionStaleCheckingEnabled(boolean) - Method in class org.apache.commons.httpclient.SimpleHttpConnectionManager
Deprecated. Use HttpConnectionParams.setStaleCheckingEnabled(boolean), HttpConnectionManager.getParams().
setConnectionTimeout(int) - Method in class org.apache.commons.httpclient.HttpClient
Deprecated. Use HttpConnectionParams.setConnectionTimeout(int), HttpConnectionManager.getParams().
setConnectionTimeout(int) - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. Use HttpConnectionParams.setConnectionTimeout(int), HttpConnection.getParams().
setConnectionTimeout(int) - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Sets the timeout until a connection is etablished.
setConnectionTimeout(long) - Method in class org.apache.commons.httpclient.util.IdleConnectionTimeoutThread
Sets the timeout value to use when testing for idle connections.
setContentCharset(String) - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Sets the default charset to be used for writing content body, when no charset explicitly specified.
setContentChunked(boolean) - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Sets whether or not the content should be chunked.
setContentType(String) - Method in class org.apache.commons.httpclient.methods.multipart.PartBase
Sets the content type.
setCookiePolicy(int) - Method in class org.apache.commons.httpclient.HttpState
Deprecated. Use HttpMethodParams.setCookiePolicy(String), HttpMethod.getParams().
setCookiePolicy(String) - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Assigns the cookie policy to be used by the HTTP methods this collection of parameters applies to.
setCredentialCharset(String) - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Sets the charset to be used for writing HTTP headers.
setCredentials(String, String, Credentials) - Method in class org.apache.commons.httpclient.HttpState
Deprecated. use #setCredentials(AuthScope, Credentials)
setCredentials(AuthScope, Credentials) - Method in class org.apache.commons.httpclient.HttpState
Sets the credentials for the given authentication scope.
setDefaultDocumentCharset(String) - Static method in class org.apache.commons.httpclient.URI
Set the default charset of the document.
setDefaultMaxConnectionsPerHost(int) - Method in class org.apache.commons.httpclient.params.HttpConnectionManagerParams
Sets the default maximum number of connections allowed for a given host config.
setDefaultPolicy(int) - Static method in class org.apache.commons.httpclient.cookie.CookiePolicy
Deprecated. Use CookiePolicy.registerCookieSpec(String, Class)
setDefaultProtocolCharset(String) - Static method in class org.apache.commons.httpclient.URI
Set the default charset of the protocol.
setDefaults(HttpParams) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
setDefaults(HttpParams) - Method in interface org.apache.commons.httpclient.params.HttpParams
Assigns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself
setDefaultUseCaches(boolean) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not available: the data must have already been retrieved.
setDiscard(boolean) - Method in class org.apache.commons.httpclient.cookie.Cookie2
Set the Discard attribute.
setDoAuthentication(boolean) - Method in interface org.apache.commons.httpclient.HttpMethod
Sets whether or not the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.)
setDoAuthentication(boolean) - Method in class org.apache.commons.httpclient.HttpMethodBase
Sets whether or not the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.)
setDoInput(boolean) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not available: the data must have already been retrieved.
setDomain(String) - Method in class org.apache.commons.httpclient.Cookie
Sets the domain attribute.
setDomain(String) - Method in class org.apache.commons.httpclient.NTCredentials
Deprecated. Do not use. The NTCredentials objects should be immutable
setDomainAttributeSpecified(boolean) - Method in class org.apache.commons.httpclient.Cookie
Indicates whether the cookie had a domain specified in a domain attribute of the Set-Cookie header.
setDoOutput(boolean) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not available: the data must have already been retrieved.
setDoubleParameter(String, double) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
setDoubleParameter(String, double) - Method in interface org.apache.commons.httpclient.params.HttpParams
Assigns a Double to the parameter with the given name
setEscapedAuthority(String) - Method in class org.apache.commons.httpclient.URI
Set the authority.
setEscapedFragment(String) - Method in class org.apache.commons.httpclient.URI
Set the escaped fragment string.
setEscapedPassword(String) - Method in class org.apache.commons.httpclient.HttpURL
Set the escaped password string.
setEscapedPath(String) - Method in class org.apache.commons.httpclient.URI
Set the escaped path.
setEscapedQuery(String) - Method in class org.apache.commons.httpclient.URI
Set the escaped query string.
setEscapedUser(String) - Method in class org.apache.commons.httpclient.HttpURL
Set the escaped user string.
setEscapedUserinfo(String, String) - Method in class org.apache.commons.httpclient.HttpURL
Set the raw-escaped user and password.
setExpiryDate(Date) - Method in class org.apache.commons.httpclient.Cookie
Sets expiration date.
setFollowRedirects(boolean) - Method in interface org.apache.commons.httpclient.HttpMethod
Sets whether or not the HTTP method should automatically follow HTTP redirects (status code 302, etc.)
setFollowRedirects(boolean) - Method in class org.apache.commons.httpclient.HttpMethodBase
Sets whether or not the HTTP method should automatically follow HTTP redirects (status code 302, etc.)
setFollowRedirects(boolean) - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Entity enclosing requests cannot be redirected without user intervention according to RFC 2616.
setFragment(String) - Method in class org.apache.commons.httpclient.URI
Set the fragment.
setHeaders(Header[]) - Method in class org.apache.commons.httpclient.HeaderGroup
Sets all of the headers contained within this group overriding any existing headers.
setHost(HttpHost) - Method in class org.apache.commons.httpclient.HostConfiguration
Sets the given host
setHost(String, int, String) - Method in class org.apache.commons.httpclient.HostConfiguration
Sets the given host, port and protocol
setHost(String, String, int, Protocol) - Method in class org.apache.commons.httpclient.HostConfiguration
Deprecated. #setHost(String, int, Protocol)
setHost(String, int, Protocol) - Method in class org.apache.commons.httpclient.HostConfiguration
Sets the given host, port and protocol.
setHost(String, int) - Method in class org.apache.commons.httpclient.HostConfiguration
Sets the given host and port.
setHost(String) - Method in class org.apache.commons.httpclient.HostConfiguration
Set the given host.
setHost(URI) - Method in class org.apache.commons.httpclient.HostConfiguration
Sets the protocol, host and port from the given URI.
setHost(String) - Method in class org.apache.commons.httpclient.HttpConnection
Sets the host to connect to.
setHost(String) - Method in class org.apache.commons.httpclient.NTCredentials
Deprecated. Do not use. The NTCredentials objects should be immutable
setHostConfiguration(HostConfiguration) - Method in class org.apache.commons.httpclient.HttpClient
Assigns the host configuration to use with the HttpClient.
setHostConfiguration(HostConfiguration) - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. no longer applicable
setHostConfiguration(HostConfiguration) - Method in class org.apache.commons.httpclient.ProxyClient
Assigns the host configuration to use with the ProxyClient.
setHttp11(boolean) - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. Use HttpMethodParams.setVersion(HttpVersion)
setHttpConnectionFactoryTimeout(long) - Method in class org.apache.commons.httpclient.HttpClient
Deprecated. Use HttpClientParams.setConnectionManagerTimeout(long), HttpClient.getParams()
setHttpConnectionManager(HttpConnectionManager) - Method in class org.apache.commons.httpclient.HttpClient
Assigns the HTTP connection manager to use with the HttpClient.
setHttpConnectionManager(HttpConnectionManager) - Method in class org.apache.commons.httpclient.HttpConnection
Sets the httpConnectionManager.
setHttpElementCharset(String) - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Sets the charset to be used for writing HTTP headers.
setHttpParamsFactory(HttpParamsFactory) - Static method in class org.apache.commons.httpclient.params.DefaultHttpParams
Sets the factory that will provide the default HttpParams.
setIfModifiedSince(long) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not available: the data must have already been retrieved.
setInstanceFollowRedirects(boolean) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not available: the data must have already been retrieved.
setIntParameter(String, int) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
setIntParameter(String, int) - Method in interface org.apache.commons.httpclient.params.HttpParams
Assigns an Integer to the parameter with the given name
setLastResponseInputStream(InputStream) - Method in class org.apache.commons.httpclient.HttpConnection
Set the state to keep track of the last response for the last request.
setLinger(int) - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Returns linger-on-close timeout.
setLocalAddress(InetAddress) - Method in class org.apache.commons.httpclient.HostConfiguration
Set the local address to be used when creating connections.
setLocalAddress(InetAddress) - Method in class org.apache.commons.httpclient.HttpConnection
Set the local address used when creating the connection.
setLocked(boolean) - Method in class org.apache.commons.httpclient.HttpConnection
Locks or unlocks the connection.
setLongParameter(String, long) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
setLongParameter(String, long) - Method in interface org.apache.commons.httpclient.params.HttpParams
Assigns a Long to the parameter with the given name
setMaxConnectionsPerHost(int) - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Deprecated. Use HttpConnectionManagerParams.setDefaultMaxConnectionsPerHost(int), HttpConnectionManager.getParams().
setMaxConnectionsPerHost(HostConfiguration, int) - Method in class org.apache.commons.httpclient.params.HttpConnectionManagerParams
Sets the maximum number of connections to be used for the given host config.
setMaxTotalConnections(int) - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Deprecated. Use HttpConnectionManagerParams.setMaxTotalConnections(int), HttpConnectionManager.getParams().
setMaxTotalConnections(int) - Method in class org.apache.commons.httpclient.params.HttpConnectionManagerParams
Sets the maximum number of connections allowed.
setMethodRetryHandler(MethodRetryHandler) - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. use HttpMethodParams
setName(String) - Method in class org.apache.commons.httpclient.methods.multipart.PartBase
Sets the part name.
setName(String) - Method in class org.apache.commons.httpclient.NameValuePair
Set the name.
setParameter(String, String) - Method in class org.apache.commons.httpclient.methods.PostMethod
Sets the value of parameter with parameterName to parameterValue.
setParameter(String, Object) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
 
setParameter(String, Object) - Method in interface org.apache.commons.httpclient.params.HttpParams
Assigns the value to the parameter with the given name
setParameters(String[], Object) - Method in class org.apache.commons.httpclient.params.DefaultHttpParams
Assigns the value to all the parameter with the given names
setParams(HostParams) - Method in class org.apache.commons.httpclient.HostConfiguration
Assigns HTTP protocol parameters specific to this host.
setParams(HttpClientParams) - Method in class org.apache.commons.httpclient.HttpClient
Assigns HTTP protocol parameters for this HttpClient.
setParams(HttpConnectionParams) - Method in class org.apache.commons.httpclient.HttpConnection
Assigns HTTP protocol parameters for this method.
setParams(HttpConnectionManagerParams) - Method in interface org.apache.commons.httpclient.HttpConnectionManager
Assigns parameters for this connection manager.
setParams(HttpMethodParams) - Method in interface org.apache.commons.httpclient.HttpMethod
Assigns HTTP protocol parameters for this method.
setParams(HttpMethodParams) - Method in class org.apache.commons.httpclient.HttpMethodBase
Assigns HTTP protocol parameters for this method.
setParams(HttpConnectionManagerParams) - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Assigns parameters for this connection manager.
setParams(HttpClientParams) - Method in class org.apache.commons.httpclient.ProxyClient
Assigns HTTP protocol parameters for this ProxyClient.
setParams(HttpConnectionManagerParams) - Method in class org.apache.commons.httpclient.SimpleHttpConnectionManager
Assigns parameters for this connection manager.
setPassword(String) - Method in class org.apache.commons.httpclient.HttpURL
Set the password string.
setPassword(String) - Method in class org.apache.commons.httpclient.UsernamePasswordCredentials
Deprecated. Do not use. The UsernamePasswordCredentials objects should be immutable
setPath(String) - Method in class org.apache.commons.httpclient.Cookie
Sets the path attribute.
setPath(String) - Method in interface org.apache.commons.httpclient.HttpMethod
Sets the path of the HTTP method.
setPath(String) - Method in class org.apache.commons.httpclient.HttpMethodBase
Sets the path of the HTTP method.
setPath(String) - Method in class org.apache.commons.httpclient.URI
Set the path.
setPathAttributeSpecified(boolean) - Method in class org.apache.commons.httpclient.Cookie
Indicates whether the cookie had a path specified in a path attribute of the Set-Cookie header.
setPort(int) - Method in class org.apache.commons.httpclient.HttpConnection
Sets the port to connect to.
setPortAttributeBlank(boolean) - Method in class org.apache.commons.httpclient.cookie.Cookie2
Indicates whether the Port attribute in Set-Cookie2 header contains no value (is of the form Port="").
setPortAttributeSpecified(boolean) - Method in class org.apache.commons.httpclient.cookie.Cookie2
Indicates whether the cookie had a port attribute specified in the Set-Cookie2 response header.
setPorts(int[]) - Method in class org.apache.commons.httpclient.cookie.Cookie2
Set the Port attribute.
setPreemptive() - Method in class org.apache.commons.httpclient.auth.AuthState
Preemptively assigns Basic authentication scheme.
setProtocol(Protocol) - Method in class org.apache.commons.httpclient.HttpConnection
Sets the protocol used to establish the connection
setProxy(String, int) - Method in class org.apache.commons.httpclient.HostConfiguration
Set the proxy settings.
setProxyCredentials(String, String, Credentials) - Method in class org.apache.commons.httpclient.HttpState
Deprecated. use #setProxyCredentials(AuthScope, Credentials)
setProxyCredentials(AuthScope, Credentials) - Method in class org.apache.commons.httpclient.HttpState
Sets the proxy credentials for the given authentication realm.
setProxyHost(ProxyHost) - Method in class org.apache.commons.httpclient.HostConfiguration
Sets the given proxy host
setProxyHost(String) - Method in class org.apache.commons.httpclient.HttpConnection
Sets the host to proxy through.
setProxyPort(int) - Method in class org.apache.commons.httpclient.HttpConnection
Sets the port of the host to proxy through.
setQuery(String, String) - Method in class org.apache.commons.httpclient.HttpURL
Set the query as the name and value pair.
setQuery(String[], String[]) - Method in class org.apache.commons.httpclient.HttpURL
Set the query as the name and value pairs.
setQuery(String) - Method in class org.apache.commons.httpclient.URI
Set the query.
setQueryString(String) - Method in interface org.apache.commons.httpclient.HttpMethod
Sets the query string of the HTTP method.
setQueryString(NameValuePair[]) - Method in interface org.apache.commons.httpclient.HttpMethod
Sets the query string of this HTTP method.
setQueryString(String) - Method in class org.apache.commons.httpclient.HttpMethodBase
Sets the query string of this HTTP method.
setQueryString(NameValuePair[]) - Method in class org.apache.commons.httpclient.HttpMethodBase
Sets the query string of this HTTP method.
setRawAuthority(char[]) - Method in class org.apache.commons.httpclient.URI
Set the authority.
setRawFragment(char[]) - Method in class org.apache.commons.httpclient.URI
Set the raw-escaped fragment.
setRawPassword(char[]) - Method in class org.apache.commons.httpclient.HttpURL
Set the raw-escaped password.
setRawPath(char[]) - Method in class org.apache.commons.httpclient.URI
Set the raw-escaped path.
setRawQuery(char[]) - Method in class org.apache.commons.httpclient.URI
Set the raw-escaped query.
setRawUser(char[]) - Method in class org.apache.commons.httpclient.HttpURL
Set the raw-escaped user.
setRawUserinfo(char[], char[]) - Method in class org.apache.commons.httpclient.HttpURL
Set the raw-escaped user and password.
setReason(String) - Method in exception org.apache.commons.httpclient.HttpException
Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.
setReason(String) - Method in exception org.apache.commons.httpclient.URIException
Deprecated. Callers should instead set this via a parameter to the constructor.
setReasonCode(int) - Method in exception org.apache.commons.httpclient.HttpException
Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.
setReasonCode(int) - Method in exception org.apache.commons.httpclient.URIException
Deprecated. Callers should set the reason code as a parameter to the constructor.
setReceiveBufferSize(int) - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Sets a hint the size of the underlying buffers used by the platform for incoming network I/O.
setRequestBody(InputStream) - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Deprecated. use EntityEnclosingMethod.setRequestEntity(RequestEntity)
setRequestBody(String) - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Deprecated. use EntityEnclosingMethod.setRequestEntity(RequestEntity)
setRequestBody(NameValuePair[]) - Method in class org.apache.commons.httpclient.methods.PostMethod
Sets an array of parameters to be used in the POST request body
setRequestContentLength(int) - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Deprecated. Use EntityEnclosingMethod.setContentChunked(boolean) or EntityEnclosingMethod.setRequestEntity(RequestEntity)
setRequestContentLength(long) - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Deprecated. Use EntityEnclosingMethod.setContentChunked(boolean) or EntityEnclosingMethod.setRequestEntity(RequestEntity)
setRequestEntity(RequestEntity) - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
 
setRequestHeader(String, String) - Method in interface org.apache.commons.httpclient.HttpMethod
Sets the specified request header, overwriting any previous value.
setRequestHeader(Header) - Method in interface org.apache.commons.httpclient.HttpMethod
Sets the specified request header, overwriting any previous value.
setRequestHeader(String, String) - Method in class org.apache.commons.httpclient.HttpMethodBase
Set the specified request header, overwriting any previous value.
setRequestHeader(Header) - Method in class org.apache.commons.httpclient.HttpMethodBase
Sets the specified request header, overwriting any previous value.
setRequestMethod(String) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not available: the data must have already been retrieved.
setRequestProperty(String, String) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not available: the data must have already been retrieved.
setRequestSentRetryEnabled(boolean) - Method in class org.apache.commons.httpclient.DefaultMethodRetryHandler
Deprecated.  
setResponseStream(InputStream) - Method in class org.apache.commons.httpclient.HttpMethodBase
Sets the response stream.
setRetryCount(int) - Method in class org.apache.commons.httpclient.DefaultMethodRetryHandler
Deprecated.  
setSecure(boolean) - Method in class org.apache.commons.httpclient.Cookie
Sets the secure attribute of the cookie.
setSendBufferSize(int) - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. Use HttpConnectionParams.setSendBufferSize(int), HttpConnection.getParams().
setSendBufferSize(int) - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Sets a hint the size of the underlying buffers used by the platform for outgoing network I/O.
setSocket(Socket) - Method in class org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory.SocketTask
Set the socket.
setSocketTimeout(int) - Method in class org.apache.commons.httpclient.HttpConnection
Sets SO_TIMEOUT value directly on the underlying socket.
setSoTimeout(int) - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. Use HttpConnectionParams.setSoTimeout(int), HttpConnection.getParams().
setSoTimeout(int) - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
setSoTimeout(int) - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
setStaleCheckingEnabled(boolean) - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. Use HttpConnectionParams.setStaleCheckingEnabled(boolean), HttpConnection.getParams().
setStaleCheckingEnabled(boolean) - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Defines whether stale connection check is to be used.
setState(HttpState) - Method in class org.apache.commons.httpclient.HttpClient
Assigns HTTP state for the HttpClient.
setState(HttpState) - Method in class org.apache.commons.httpclient.ProxyClient
Assigns HTTP state for the ProxyClient.
setStrictMode(boolean) - Method in class org.apache.commons.httpclient.HttpClient
Deprecated. Use DefaultHttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.
setStrictMode(boolean) - Method in interface org.apache.commons.httpclient.HttpMethod
Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.
setStrictMode(boolean) - Method in class org.apache.commons.httpclient.HttpMethodBase
Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.
setTcpNoDelay(boolean) - Method in class org.apache.commons.httpclient.params.HttpConnectionParams
Determines whether Nagle's algorithm is to be used.
setTimeout(int) - Method in class org.apache.commons.httpclient.HttpClient
Deprecated. Use HttpConnectionParams.setSoTimeout(int), HttpConnectionManager.getParams().
setTimeoutInterval(long) - Method in class org.apache.commons.httpclient.util.IdleConnectionTimeoutThread
Sets the interval used by this class between closing idle connections.
setTransferEncoding(String) - Method in class org.apache.commons.httpclient.methods.multipart.PartBase
Sets the transfer encoding.
setURI(URI) - Method in interface org.apache.commons.httpclient.HttpMethod
Sets the URI for this method.
setURI(URI) - Method in class org.apache.commons.httpclient.HttpMethodBase
Sets the URI for this method.
setURI() - Method in class org.apache.commons.httpclient.HttpURL
Once it's parsed successfully, set this URI.
setURI() - Method in class org.apache.commons.httpclient.URI
Once it's parsed successfully, set this URI.
setUriCharset(String) - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Sets the charset to be used for parsing URIs.
setUseCaches(boolean) - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not available: the data must have already been retrieved.
setUseExpectHeader(boolean) - Method in class org.apache.commons.httpclient.methods.ExpectContinueMethod
Deprecated. Use HttpMethodParams
setUser(String) - Method in class org.apache.commons.httpclient.HttpURL
Set the user string.
setUserinfo(String, String) - Method in class org.apache.commons.httpclient.HttpURL
Set the user and password.
setUserName(String) - Method in class org.apache.commons.httpclient.UsernamePasswordCredentials
Deprecated. Do not use. The UsernamePasswordCredentials objects should be immutable
setValidDateFormats(Collection) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Sets the Collection of date patterns used for parsing.
setValidDateFormats(Collection) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
 
setValidDateFormats(Collection) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
Does nothing.
setValue(String) - Method in class org.apache.commons.httpclient.NameValuePair
Set the value.
setVersion(int) - Method in class org.apache.commons.httpclient.Cookie
Sets the version of the cookie specification to which this cookie conforms.
setVersion(HttpVersion) - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Assigns the HTTP protocol version to be used by the HTTP methods that this collection of parameters applies to.
setVersionAttributeSpecified(boolean) - Method in class org.apache.commons.httpclient.cookie.Cookie2
Indicates whether the cookie had a version attribute specified in the Set-Cookie2 response header.
setVirtualHost(String) - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. no longer applicable
setVirtualHost(String) - Method in class org.apache.commons.httpclient.params.HostParams
Sets the virtual host name.
setVirtualHost(String) - Method in class org.apache.commons.httpclient.params.HttpMethodParams
Sets the virtual host name.
shouldCloseConnection(HttpConnection) - Method in class org.apache.commons.httpclient.ConnectMethod
Returns true if the status code is anything other than SC_OK, false otherwise.
shouldCloseConnection(HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Tests if the connection should be closed after the method has been executed.
shutdown() - Method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Shuts down the connection manager and releases all resources.
shutdown() - Method in class org.apache.commons.httpclient.SimpleHttpConnectionManager
since 3.1
shutdown() - Method in class org.apache.commons.httpclient.util.IdleConnectionTimeoutThread
Stops the thread used to close idle connections.
shutdownAll() - Static method in class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
Shuts down and cleans up resources used by all instances of MultiThreadedHttpConnectionManager.
shutdownOutput() - Method in class org.apache.commons.httpclient.HttpConnection
Deprecated. unused
SimpleHttpConnectionManager - Class in org.apache.commons.httpclient
A connection manager that provides access to a single HttpConnection.
SimpleHttpConnectionManager(boolean) - Constructor for class org.apache.commons.httpclient.SimpleHttpConnectionManager
The connection manager created with this constructor will try to keep the connection open (alive) between consecutive requests if the alwaysClose parameter is set to false.
SimpleHttpConnectionManager() - Constructor for class org.apache.commons.httpclient.SimpleHttpConnectionManager
The connection manager created with this constructor will always try to keep the connection open (alive) between consecutive requests.
SINGLE_COOKIE_HEADER - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines whether cookies should be put on a single response header.
skip(long) - Method in class org.apache.commons.httpclient.ContentLengthInputStream
Skips and discards a number of bytes from the input stream.
SO_LINGER - Static variable in class org.apache.commons.httpclient.params.HttpConnectionParams
Sets SO_LINGER with the specified linger time in seconds.
SO_RCVBUF - Static variable in class org.apache.commons.httpclient.params.HttpConnectionParams
Determines a hint the size of the underlying buffers used by the platform for incoming network I/O.
SO_SNDBUF - Static variable in class org.apache.commons.httpclient.params.HttpConnectionParams
Determines a hint the size of the underlying buffers used by the platform for outgoing network I/O.
SO_TIMEOUT - Static variable in class org.apache.commons.httpclient.params.HttpConnectionParams
Defines the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
SO_TIMEOUT - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Sets the socket timeout (SO_TIMEOUT) in milliseconds to be used when executing the method.
space - Static variable in class org.apache.commons.httpclient.URI
BitSet for space.
SSLProtocolSocketFactory - Class in org.apache.commons.httpclient.protocol
A SecureProtocolSocketFactory that uses JSSE to create sockets.
SSLProtocolSocketFactory() - Constructor for class org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory
Constructor for SSLProtocolSocketFactory.
STALE_CONNECTION_CHECK - Static variable in class org.apache.commons.httpclient.params.HttpConnectionParams
Determines whether stale connection check is to be used.
startsWithHTTP(String) - Static method in class org.apache.commons.httpclient.StatusLine
Tests if the string starts with 'HTTP' signature.
STATUS_LINE_GARBAGE_LIMIT - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines the maximum number of ignorable lines before we expect a HTTP response's status code.
statusLine - Variable in class org.apache.commons.httpclient.HttpMethodBase
The Status-Line from the response.
StatusLine - Class in org.apache.commons.httpclient
Represents a Status-Line as returned from a HTTP server.
StatusLine(String) - Constructor for class org.apache.commons.httpclient.StatusLine
Default constructor.
STRICT_TRANSFER_ENCODING - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines whether responses with an invalid Transfer-Encoding header should be rejected.
StringPart - Class in org.apache.commons.httpclient.methods.multipart
Simple string parameter for a multipart post
StringPart(String, String, String) - Constructor for class org.apache.commons.httpclient.methods.multipart.StringPart
Constructor.
StringPart(String, String) - Constructor for class org.apache.commons.httpclient.methods.multipart.StringPart
Constructor.
StringRequestEntity - Class in org.apache.commons.httpclient.methods
A RequestEntity that contains a String.
StringRequestEntity(String) - Constructor for class org.apache.commons.httpclient.methods.StringRequestEntity
Deprecated. use StringRequestEntity.StringRequestEntity(String, String, String) instead
StringRequestEntity(String, String, String) - Constructor for class org.apache.commons.httpclient.methods.StringRequestEntity
Creates a new entity with the given content, content type, and charset.

T

TCP_NODELAY - Static variable in class org.apache.commons.httpclient.params.HttpConnectionParams
Determines whether Nagle's algorithm is to be used.
TimeoutController - Class in org.apache.commons.httpclient.util
Executes a task with a specified timeout.
TimeoutController.TimeoutException - Exception in org.apache.commons.httpclient.util
Signals that the task timed out.
TimeoutController.TimeoutException() - Constructor for exception org.apache.commons.httpclient.util.TimeoutController.TimeoutException
Create an instance
toExternalForm() - Method in class org.apache.commons.httpclient.cookie.Cookie2
Return a textual representation of the cookie.
toExternalForm() - Method in class org.apache.commons.httpclient.Cookie
Return a textual representation of the cookie.
toExternalForm() - Method in class org.apache.commons.httpclient.Header
Returns a String representation of the header.
toplabel - Static variable in class org.apache.commons.httpclient.URI
BitSet for toplabel.
toString() - Method in class org.apache.commons.httpclient.auth.AuthSchemeBase
Deprecated.  
toString() - Method in class org.apache.commons.httpclient.auth.AuthScope
 
toString() - Method in class org.apache.commons.httpclient.auth.AuthState
 
toString() - Method in class org.apache.commons.httpclient.Cookie
Return a textual representation of the cookie.
toString() - Method in class org.apache.commons.httpclient.Header
Returns a String representation of the header.
toString() - Method in class org.apache.commons.httpclient.HostConfiguration
 
toString() - Method in class org.apache.commons.httpclient.HttpHost
 
toString() - Method in class org.apache.commons.httpclient.HttpState
Returns a string representation of this HTTP state.
toString() - Method in class org.apache.commons.httpclient.HttpVersion
 
toString() - Method in class org.apache.commons.httpclient.methods.multipart.Part
Return a string representation of this object.
toString() - Method in class org.apache.commons.httpclient.NameValuePair
Get a String representation of this pair.
toString() - Method in class org.apache.commons.httpclient.NTCredentials
Return a string representation of this object.
toString() - Method in class org.apache.commons.httpclient.protocol.Protocol
Return a string representation of this object.
toString() - Method in class org.apache.commons.httpclient.StatusLine
Return a string representation of this object.
toString() - Method in class org.apache.commons.httpclient.URI
Get the escaped URI string.
toString() - Method in class org.apache.commons.httpclient.UsernamePasswordCredentials
Get this object string.
toURI() - Method in class org.apache.commons.httpclient.HttpHost
Return the host uri.
toUserinfo(String, String) - Static method in class org.apache.commons.httpclient.HttpURL
 
TraceMethod - Class in org.apache.commons.httpclient.methods
Implements the HTTP TRACE method.
TraceMethod(String) - Constructor for class org.apache.commons.httpclient.methods.TraceMethod
Constructor specifying a URI.
tunnelCreated() - Method in class org.apache.commons.httpclient.HttpConnection
Instructs the proxy to establish a secure tunnel to the host.

U

UNAMBIGUOUS_STATUS_LINE - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines whether HTTP methods should reject ambiguous HTTP status line.
UNKNOWN - Static variable in exception org.apache.commons.httpclient.URI.DefaultCharsetChanged
No specified reason code.
UNKNOWN - Static variable in exception org.apache.commons.httpclient.URIException
No specified reason code.
unregisterAuthScheme(String) - Static method in class org.apache.commons.httpclient.auth.AuthPolicy
Unregisters the class implementing an authentication scheme with the given ID.
unregisterCookieSpec(String) - Static method in class org.apache.commons.httpclient.cookie.CookiePolicy
Unregisters the cookie specification with the given ID.
unregisterProtocol(String) - Static method in class org.apache.commons.httpclient.protocol.Protocol
Unregisters the protocol with the given ID.
unreserved - Static variable in class org.apache.commons.httpclient.URI
Data characters that are allowed in a URI but do not have a reserved purpose are called unreserved.
UNSUPPORTED_ENCODING - Static variable in exception org.apache.commons.httpclient.URIException
The unsupported character encoding.
unwise - Static variable in class org.apache.commons.httpclient.URI
BitSet for unwise.
URI - Class in org.apache.commons.httpclient
The interface for the URI(Uniform Resource Identifiers) version of RFC 2396.
URI() - Constructor for class org.apache.commons.httpclient.URI
Create an instance as an internal use
URI(String, boolean, String) - Constructor for class org.apache.commons.httpclient.URI
Construct a URI from a string with the given charset.
URI(String, boolean) - Constructor for class org.apache.commons.httpclient.URI
Construct a URI from a string with the given charset.
URI(char[], String) - Constructor for class org.apache.commons.httpclient.URI
Deprecated. Use #URI(String, boolean, String)
URI(char[]) - Constructor for class org.apache.commons.httpclient.URI
Deprecated. Use #URI(String, boolean)
URI(String, String) - Constructor for class org.apache.commons.httpclient.URI
Deprecated. Use #URI(String, boolean, String)
URI(String) - Constructor for class org.apache.commons.httpclient.URI
Deprecated. Use #URI(String, boolean)
URI(String, String, String) - Constructor for class org.apache.commons.httpclient.URI
Construct a general URI from the given components.
URI(String, String, String, String, String) - Constructor for class org.apache.commons.httpclient.URI
Construct a general URI from the given components.
URI(String, String, String, int) - Constructor for class org.apache.commons.httpclient.URI
Construct a general URI from the given components.
URI(String, String, String, int, String) - Constructor for class org.apache.commons.httpclient.URI
Construct a general URI from the given components.
URI(String, String, String, int, String, String) - Constructor for class org.apache.commons.httpclient.URI
Construct a general URI from the given components.
URI(String, String, String, int, String, String, String) - Constructor for class org.apache.commons.httpclient.URI
Construct a general URI from the given components.
URI(String, String, String, String) - Constructor for class org.apache.commons.httpclient.URI
Construct a general URI from the given components.
URI(URI, String) - Constructor for class org.apache.commons.httpclient.URI
Deprecated. Use #URI(URI, String, boolean)
URI(URI, String, boolean) - Constructor for class org.apache.commons.httpclient.URI
Construct a general URI with the given relative URI string.
URI(URI, URI) - Constructor for class org.apache.commons.httpclient.URI
Construct a general URI with the given relative URI.
URI.DefaultCharsetChanged - Exception in org.apache.commons.httpclient
The charset-changed normal operation to represent to be required to alert to user the fact the default charset is changed.
URI.DefaultCharsetChanged(int, String) - Constructor for exception org.apache.commons.httpclient.URI.DefaultCharsetChanged
The constructor with a reason string and its code arguments.
URI.LocaleToCharsetMap - Class in org.apache.commons.httpclient
A mapping to determine the (somewhat arbitrarily) preferred charset for a given locale.
URI.LocaleToCharsetMap() - Constructor for class org.apache.commons.httpclient.URI.LocaleToCharsetMap
 
URI_reference - Static variable in class org.apache.commons.httpclient.URI
BitSet for URI-reference.
uric - Static variable in class org.apache.commons.httpclient.URI
BitSet for uric.
uric_no_slash - Static variable in class org.apache.commons.httpclient.URI
URI bitset for encoding typical non-slash characters.
URIException - Exception in org.apache.commons.httpclient
The URI parsing and escape encoding exception.
URIException() - Constructor for exception org.apache.commons.httpclient.URIException
Default constructor.
URIException(int) - Constructor for exception org.apache.commons.httpclient.URIException
The constructor with a reason code argument.
URIException(int, String) - Constructor for exception org.apache.commons.httpclient.URIException
The constructor with a reason string and its code arguments.
URIException(String) - Constructor for exception org.apache.commons.httpclient.URIException
The constructor with a reason string argument.
URIUtil - Class in org.apache.commons.httpclient.util
The URI escape and character encoding and decoding utility.
URIUtil() - Constructor for class org.apache.commons.httpclient.util.URIUtil
 
URIUtil.Coder - Class in org.apache.commons.httpclient.util
Deprecated. use org.apache.commons.codec.net.URLCodec
URIUtil.Coder() - Constructor for class org.apache.commons.httpclient.util.URIUtil.Coder
Deprecated.  
USE_EXPECT_CONTINUE - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Activates 'Expect: 100-Continue' handshake for the entity enclosing methods.
USER_AGENT - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines the content of the User-Agent header used by HTTP methods.
userinfo - Static variable in class org.apache.commons.httpclient.URI
Bitset for userinfo.
UsernamePasswordCredentials - Class in org.apache.commons.httpclient
Username and password Credentials.
UsernamePasswordCredentials() - Constructor for class org.apache.commons.httpclient.UsernamePasswordCredentials
Deprecated. Do not use. Null user name no longer allowed
UsernamePasswordCredentials(String) - Constructor for class org.apache.commons.httpclient.UsernamePasswordCredentials
The constructor with the username and password combined string argument.
UsernamePasswordCredentials(String, String) - Constructor for class org.apache.commons.httpclient.UsernamePasswordCredentials
The constructor with the username and password arguments.
usingProxy() - Method in class org.apache.commons.httpclient.util.HttpURLConnection
Not yet implemented.

V

validate(Cookie, CookieOrigin) - Method in interface org.apache.commons.httpclient.cookie.CookieAttributeHandler
Peforms cookie validation for the given attribute value.
validate(String, int, String, boolean, Cookie) - Method in interface org.apache.commons.httpclient.cookie.CookieSpec
Validate the cookie according to validation rules defined by the cookie specification.
validate(String, int, String, boolean, Cookie) - Method in class org.apache.commons.httpclient.cookie.CookieSpecBase
Performs most common Cookie validation
validate(String, int, String, boolean, Cookie) - Method in class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
Does nothing.
validate(String, int, String, boolean, Cookie) - Method in class org.apache.commons.httpclient.cookie.NetscapeDraftSpec
Performs Netscape draft compliant Cookie validation
validate(String, int, String, boolean, Cookie) - Method in class org.apache.commons.httpclient.cookie.RFC2109Spec
Performs RFC 2109 compliant Cookie validation
validate(String, int, String, boolean, Cookie) - Method in class org.apache.commons.httpclient.cookie.RFC2965Spec
Performs RFC 2965 compliant Cookie validation
validate() - Method in interface org.apache.commons.httpclient.HttpMethod
Returns true the method is ready to execute, false otherwise.
validate() - Method in class org.apache.commons.httpclient.HttpMethodBase
Returns true the method is ready to execute, false otherwise.
validate(char[], BitSet) - Method in class org.apache.commons.httpclient.URI
Validate the URI characters within a specific component.
validate(char[], int, int, BitSet) - Method in class org.apache.commons.httpclient.URI
Validate the URI characters within a specific component.
verifyEscaped(char[]) - Static method in class org.apache.commons.httpclient.util.URIUtil.Coder
Deprecated. Verify whether a given string is escaped or not
VERSION - Static variable in class org.apache.commons.httpclient.cookie.Cookie2
 
VIRTUAL_HOST - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines the virtual host name.

W

WARN_EXTRA_INPUT - Static variable in class org.apache.commons.httpclient.params.HttpMethodParams
Defines HttpClient's behavior when a response provides more bytes than expected (specified with Content-Length, for example).
within_userinfo - Static variable in class org.apache.commons.httpclient.URI
BitSet for within the userinfo component like user and password.
write(int) - Method in class org.apache.commons.httpclient.ChunkedOutputStream
Write the specified byte to our output stream.
write(byte[]) - Method in class org.apache.commons.httpclient.ChunkedOutputStream
Writes the array.
write(byte[], int, int) - Method in class org.apache.commons.httpclient.ChunkedOutputStream
 
write(byte[]) - Method in class org.apache.commons.httpclient.HttpConnection
Writes the specified bytes to the output stream.
write(byte[], int, int) - Method in class org.apache.commons.httpclient.HttpConnection
Writes length bytes in data starting at offset to the output stream.
writeClosingChunk() - Method in class org.apache.commons.httpclient.ChunkedOutputStream
 
writeLine(byte[]) - Method in class org.apache.commons.httpclient.HttpConnection
Writes the specified bytes, followed by "\r\n".getBytes() to the output stream.
writeLine() - Method in class org.apache.commons.httpclient.HttpConnection
Writes "\r\n".getBytes() to the output stream.
writeRequest(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Sends the request via the given connection.
writeRequest(OutputStream) - Method in class org.apache.commons.httpclient.methods.ByteArrayRequestEntity
 
writeRequest(OutputStream) - Method in class org.apache.commons.httpclient.methods.FileRequestEntity
 
writeRequest(OutputStream) - Method in class org.apache.commons.httpclient.methods.InputStreamRequestEntity
 
writeRequest(OutputStream) - Method in class org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity
 
writeRequest(OutputStream) - Method in interface org.apache.commons.httpclient.methods.RequestEntity
Writes the request entity to the given stream.
writeRequest(OutputStream) - Method in class org.apache.commons.httpclient.methods.StringRequestEntity
 
writeRequestBody(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Writes the request body to the given connection.
writeRequestBody(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.methods.EntityEnclosingMethod
Writes the request body to the given connection.
writeRequestBody(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.methods.MultipartPostMethod
Deprecated. Writes the request body to the given connection.
writeRequestHeaders(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Writes the request headers to the given connection.
writeRequestLine(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.ConnectMethod
Special Connect request.
writeRequestLine(HttpState, HttpConnection) - Method in class org.apache.commons.httpclient.HttpMethodBase
Writes the request line to the given connection.
WWW_AUTH - Static variable in class org.apache.commons.httpclient.auth.HttpAuthenticator
Deprecated. The www authenticate challange header.
WWW_AUTH_RESP - Static variable in class org.apache.commons.httpclient.auth.HttpAuthenticator
Deprecated. The www authenticate response header.

_

_authority - Variable in class org.apache.commons.httpclient.URI
The authority.
_default_port - Static variable in class org.apache.commons.httpclient.HttpsURL
Deprecated. Use HttpsURL.DEFAULT_PORT instead. This one doesn't conform to the project naming conventions.
_default_port - Static variable in class org.apache.commons.httpclient.HttpURL
Deprecated. Use HttpURL.DEFAULT_PORT instead. This one doesn't conform to the project naming conventions.
_default_scheme - Static variable in class org.apache.commons.httpclient.HttpsURL
Deprecated. Use HttpsURL.DEFAULT_SCHEME instead. This one doesn't conform to the project naming conventions.
_default_scheme - Static variable in class org.apache.commons.httpclient.HttpURL
Deprecated. Use HttpURL.DEFAULT_SCHEME instead. This one doesn't conform to the project naming conventions.
_fragment - Variable in class org.apache.commons.httpclient.URI
The fragment.
_host - Variable in class org.apache.commons.httpclient.URI
The host.
_is_abs_path - Variable in class org.apache.commons.httpclient.URI
 
_is_hier_part - Variable in class org.apache.commons.httpclient.URI
 
_is_hostname - Variable in class org.apache.commons.httpclient.URI
 
_is_IPv4address - Variable in class org.apache.commons.httpclient.URI
 
_is_IPv6reference - Variable in class org.apache.commons.httpclient.URI
 
_is_net_path - Variable in class org.apache.commons.httpclient.URI
 
_is_opaque_part - Variable in class org.apache.commons.httpclient.URI
 
_is_reg_name - Variable in class org.apache.commons.httpclient.URI
 
_is_rel_path - Variable in class org.apache.commons.httpclient.URI
 
_is_server - Variable in class org.apache.commons.httpclient.URI
 
_opaque - Variable in class org.apache.commons.httpclient.URI
The opaque.
_path - Variable in class org.apache.commons.httpclient.URI
The path.
_port - Variable in class org.apache.commons.httpclient.URI
The port.
_query - Variable in class org.apache.commons.httpclient.URI
The query.
_scheme - Variable in class org.apache.commons.httpclient.URI
The scheme.
_uri - Variable in class org.apache.commons.httpclient.URI
This Uniform Resource Identifier (URI).
_userinfo - Variable in class org.apache.commons.httpclient.URI
The userinfo.

A B C D E F G H I L M N O P Q R S T U V W _

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/index.html100644 0 0 2567 10661532627 16724 0ustar 0 0 HttpClient 3.1 API <H2> Frame Alert</H2> <P> This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. <BR> Link to<A HREF="overview-summary.html">Non-frame version.</A> commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ChunkedInputStream.html100644 0 0 56471 10661532627 27256 0ustar 0 0 ChunkedInputStream (HttpClient 3.1 API)

org.apache.commons.httpclient
Class ChunkedInputStream

java.lang.Object
  extended by java.io.InputStream
      extended by org.apache.commons.httpclient.ChunkedInputStream
All Implemented Interfaces:
Closeable

public class ChunkedInputStream
extends InputStream

Transparently coalesces chunks of a HTTP stream that uses Transfer-Encoding chunked.

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 invocation of subsequent HTTP 1.1 calls, while not requiring the client to remember to read the entire contents of the response.

Since:
2.0
Author:
Ortwin Glueck, Sean C. Sullivan, Martin Elwin, Eric Johnson, Mike Bowler, Michael Becke, Oleg Kalnichevski

Constructor Summary
ChunkedInputStream(InputStream in)
          ChunkedInputStream constructor
ChunkedInputStream(InputStream in, HttpMethod method)
          ChunkedInputStream constructor that associates the chunked input stream with a HTTP method.
 
Method Summary
 void close()
          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.
 int read()
           Returns all the data in a chunked stream in coalesced form.
 int read(byte[] b)
          Read some bytes from the stream.
 int read(byte[] b, int off, int len)
          Read some bytes from the stream.
 
Methods inherited from class java.io.InputStream
available, mark, markSupported, reset, skip
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ChunkedInputStream

public ChunkedInputStream(InputStream in,
                          HttpMethod method)
                   throws IOException
ChunkedInputStream constructor that associates the chunked input stream with a HTTP method. Usually it should be the same HTTP method the chunked input stream originates from. If chunked input stream contains any footers (trailing headers), they will be added to the associated HTTP method.

Parameters:
in - the raw input stream
method - the HTTP method to associate this input stream with. Can be null.
Throws:
IOException - If an IO error occurs

ChunkedInputStream

public ChunkedInputStream(InputStream in)
                   throws IOException
ChunkedInputStream constructor

Parameters:
in - the raw input stream
Throws:
IOException - If an IO error occurs
Method Detail

read

public int read()
         throws IOException

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 automcatically at the end of the stream and can be obtained with the getResponseFooters() method.

Specified by:
read in class InputStream
Returns:
-1 of the end of the stream has been reached or the next data byte
Throws:
IOException - If an IO problem occurs
See Also:
HttpMethod.getResponseFooters()

read

public int read(byte[] b,
                int off,
                int len)
         throws IOException
Read some bytes from the stream.

Overrides:
read in class InputStream
Parameters:
b - The byte array that will hold the contents from the stream.
off - The offset into the byte array at which bytes will start to be placed.
len - the maximum number of bytes that can be returned.
Returns:
The number of bytes returned or -1 if the end of stream has been reached.
Throws:
IOException - if an IO problem occurs.
See Also:
InputStream.read(byte[], int, int)

read

public int read(byte[] b)
         throws IOException
Read some bytes from the stream.

Overrides:
read in class InputStream
Parameters:
b - The byte array that will hold the contents from the stream.
Returns:
The number of bytes returned or -1 if the end of stream has been reached.
Throws:
IOException - if an IO problem occurs.
See Also:
InputStream.read(byte[])

close

public void close()
           throws IOException
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.

Specified by:
close in interface Closeable
Overrides:
close in class InputStream
Throws:
IOException - If an IO problem occurs.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ChunkedOutputStream.html100644 0 0 62761 10661532627 27456 0ustar 0 0 ChunkedOutputStream (HttpClient 3.1 API)

org.apache.commons.httpclient
Class ChunkedOutputStream

java.lang.Object
  extended by java.io.OutputStream
      extended by org.apache.commons.httpclient.ChunkedOutputStream
All Implemented Interfaces:
Closeable, Flushable

public class ChunkedOutputStream
extends OutputStream

Implements HTTP chunking support. Writes are buffered to an internal buffer (2048 default size). Chunks are guaranteed to be at least as large as the buffer size (except for the last chunk).

Author:
Mohammad Rezaei, Goldman, Sachs & Co.

Constructor Summary
ChunkedOutputStream(OutputStream stream)
          Wraps a stream and chunks the output.
ChunkedOutputStream(OutputStream stream, int bufferSize)
          Wraps a stream and chunks the output.
 
Method Summary
 void close()
          Finishes writing to the underlying stream, but does NOT close the underlying stream.
 void finish()
          Must be called to ensure the internal cache is flushed and the closing chunk is written.
 void flush()
          Flushes the underlying stream, but leaves the internal buffer alone.
protected  void flushCache()
          Writes the cache out onto the underlying stream
protected  void flushCacheWithAppend(byte[] bufferToAppend, int off, int len)
          Writes the cache and bufferToAppend to the underlying stream as one large chunk
 void write(byte[] b)
          Writes the array.
 void write(byte[] src, int off, int len)
           
 void write(int b)
          Write the specified byte to our output stream.
protected  void writeClosingChunk()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ChunkedOutputStream

public ChunkedOutputStream(OutputStream stream,
                           int bufferSize)
                    throws IOException
Wraps a stream and chunks the output.

Parameters:
stream - to wrap
bufferSize - minimum chunk size (excluding last chunk)
Throws:
IOException
Since:
3.0

ChunkedOutputStream

public ChunkedOutputStream(OutputStream stream)
                    throws IOException
Wraps a stream and chunks the output. The default buffer size of 2048 was chosen because the chunk overhead is less than 0.5%

Parameters:
stream -
Throws:
IOException
Method Detail

flushCache

protected void flushCache()
                   throws IOException
Writes the cache out onto the underlying stream

Throws:
IOException
Since:
3.0

flushCacheWithAppend

protected void flushCacheWithAppend(byte[] bufferToAppend,
                                    int off,
                                    int len)
                             throws IOException
Writes the cache and bufferToAppend to the underlying stream as one large chunk

Parameters:
bufferToAppend -
off -
len -
Throws:
IOException
Since:
3.0

writeClosingChunk

protected void writeClosingChunk()
                          throws IOException
Throws:
IOException

finish

public void finish()
            throws IOException
Must be called to ensure the internal cache is flushed and the closing chunk is written.

Throws:
IOException
Since:
3.0

write

public void write(int b)
           throws IOException
Write the specified byte to our output stream. Note: Avoid this method as it will cause an inefficient single byte chunk. Use write (byte[], int, int) instead.

Specified by:
write in class OutputStream
Parameters:
b - The byte to be written
Throws:
IOException - if an input/output error occurs

write

public void write(byte[] b)
           throws IOException
Writes the array. If the array does not fit within the buffer, it is not split, but rather written out as one large chunk.

Overrides:
write in class OutputStream
Parameters:
b -
Throws:
IOException
Since:
3.0

write

public void write(byte[] src,
                  int off,
                  int len)
           throws IOException
Overrides:
write in class OutputStream
Throws:
IOException

flush

public void flush()
           throws IOException
Flushes the underlying stream, but leaves the internal buffer alone.

Specified by:
flush in interface Flushable
Overrides:
flush in class OutputStream
Throws:
IOException

close

public void close()
           throws IOException
Finishes writing to the underlying stream, but does NOT close the underlying stream.

Specified by:
close in interface Closeable
Overrides:
close in class OutputStream
Throws:
IOException


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/CircularRedirectException.html100644 0 0 44526 10661532627 30604 0ustar 0 0 CircularRedirectException (HttpClient 3.1 API)

org.apache.commons.httpclient
Class CircularRedirectException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.ProtocolException
                      extended by org.apache.commons.httpclient.RedirectException
                          extended by org.apache.commons.httpclient.CircularRedirectException
All Implemented Interfaces:
Serializable

public class CircularRedirectException
extends RedirectException

Signals a circular redirect

Since:
3.0
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
CircularRedirectException()
          Creates a new CircularRedirectException with a null detail message.
CircularRedirectException(String message)
          Creates a new CircularRedirectException with the specified detail message.
CircularRedirectException(String message, Throwable cause)
          Creates a new CircularRedirectException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

CircularRedirectException

public CircularRedirectException()
Creates a new CircularRedirectException with a null detail message.


CircularRedirectException

public CircularRedirectException(String message)
Creates a new CircularRedirectException with the specified detail message.

Parameters:
message - The exception detail message

CircularRedirectException

public CircularRedirectException(String message,
                                 Throwable cause)
Creates a new CircularRedirectException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ConnectMethod.html100644 0 0 141470 10661532627 26245 0ustar 0 0 ConnectMethod (HttpClient 3.1 API)

org.apache.commons.httpclient
Class ConnectMethod

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
      extended by org.apache.commons.httpclient.ConnectMethod
All Implemented Interfaces:
HttpMethod

public class ConnectMethod
extends HttpMethodBase

Establishes a tunneled HTTP connection via the CONNECT method.

Since:
2.0
Version:
$Revision: 483949 $ $Date: 2006-12-08 12:34:50 +0100 (Fri, 08 Dec 2006) $
Author:
Ortwin Gl???ck, dIon Gillard, Mike Bowler, Oleg Kalnichevski

Field Summary
static String NAME
          the name of this method
 
Fields inherited from class org.apache.commons.httpclient.HttpMethodBase
effectiveVersion, statusLine
 
Constructor Summary
ConnectMethod()
          Deprecated. use #ConnectMethod(HttpHost); Create a connect method.
ConnectMethod(HostConfiguration targethost)
          Create a connect method.
ConnectMethod(HttpMethod method)
          Deprecated. the wrapped method is no longer used Create a connect method wrapping the existing method
 
Method Summary
protected  void addCookieRequestHeader(HttpState state, HttpConnection conn)
          This method does nothing.
protected  void addRequestHeaders(HttpState state, HttpConnection conn)
          Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
 int execute(HttpState state, HttpConnection conn)
          Execute this method and create a tunneled HttpConnection.
 String getName()
          Provide the name of this method.
 String getPath()
          Gets the path of this HTTP method.
 URI getURI()
          Returns the URI of the HTTP method
protected  boolean shouldCloseConnection(HttpConnection conn)
          Returns true if the status code is anything other than SC_OK, false otherwise.
protected  void writeRequestLine(HttpState state, HttpConnection conn)
          Special Connect request.
 
Methods inherited from class org.apache.commons.httpclient.HttpMethodBase
abort, addHostRequestHeader, addProxyConnectionHeader, addRequestHeader, addRequestHeader, addResponseFooter, addUserAgentRequestHeader, checkNotUsed, checkUsed, generateRequestLine, getAuthenticationRealm, getContentCharSet, getDoAuthentication, getEffectiveVersion, getFollowRedirects, getHostAuthState, getHostConfiguration, getMethodRetryHandler, getParams, getProxyAuthenticationRealm, getProxyAuthState, getQueryString, getRecoverableExceptionCount, getRequestCharSet, getRequestHeader, getRequestHeaderGroup, getRequestHeaders, getRequestHeaders, getResponseBody, getResponseBody, getResponseBodyAsStream, getResponseBodyAsString, getResponseBodyAsString, getResponseCharSet, getResponseContentLength, getResponseFooter, getResponseFooters, getResponseHeader, getResponseHeaderGroup, getResponseHeaders, getResponseHeaders, getResponseStream, getResponseTrailerHeaderGroup, getStatusCode, getStatusLine, getStatusText, hasBeenUsed, isAborted, isConnectionCloseForced, isHttp11, isRequestSent, isStrictMode, processCookieHeaders, processResponseBody, processResponseHeaders, processStatusLine, readResponse, readResponseBody, readResponseHeaders, readStatusLine, recycle, releaseConnection, removeRequestHeader, removeRequestHeader, responseBodyConsumed, setConnectionCloseForced, setDoAuthentication, setFollowRedirects, setHostConfiguration, setHttp11, setMethodRetryHandler, setParams, setPath, setQueryString, setQueryString, setRequestHeader, setRequestHeader, setResponseStream, setStrictMode, setURI, validate, writeRequest, writeRequestBody, writeRequestHeaders
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

NAME

public static final String NAME
the name of this method

See Also:
Constant Field Values
Constructor Detail

ConnectMethod

public ConnectMethod()
Deprecated. use #ConnectMethod(HttpHost); Create a connect method.

Since:
3.0

ConnectMethod

public ConnectMethod(HttpMethod method)
Deprecated. the wrapped method is no longer used Create a connect method wrapping the existing method

Parameters:
method - the method to execute after connecting to the server

ConnectMethod

public ConnectMethod(HostConfiguration targethost)
Create a connect method.

Since:
3.0
Method Detail

getName

public String getName()
Provide the name of this method.

Specified by:
getName in interface HttpMethod
Specified by:
getName in class HttpMethodBase
Returns:
the String "CONNECT"

getPath

public String getPath()
Description copied from class: HttpMethodBase
Gets the path of this HTTP method. Calling this method after the request has been executed will return the actual path, following any redirects automatically handled by this HTTP method.

Specified by:
getPath in interface HttpMethod
Overrides:
getPath in class HttpMethodBase
Returns:
the path to request or "/" if the path is blank.

getURI

public URI getURI()
           throws URIException
Description copied from class: HttpMethodBase
Returns the URI of the HTTP method

Specified by:
getURI in interface HttpMethod
Overrides:
getURI in class HttpMethodBase
Returns:
The URI
Throws:
URIException - If the URI cannot be created.
See Also:
HttpMethod.getURI()

addCookieRequestHeader

protected void addCookieRequestHeader(HttpState state,
                                      HttpConnection conn)
                               throws IOException,
                                      HttpException
This method does nothing. CONNECT request is not supposed to contain Cookie request header.

Overrides:
addCookieRequestHeader in class HttpMethodBase
Parameters:
state - current state of http requests
conn - the connection to use for I/O
Throws:
IOException - when errors occur reading or writing to/from the connection
HttpException - when a recoverable error occurs
See Also:
HttpMethodBase.addCookieRequestHeader(HttpState, HttpConnection)

addRequestHeaders

protected void addRequestHeaders(HttpState state,
                                 HttpConnection conn)
                          throws IOException,
                                 HttpException
Populates the request headers map to with additional headers to be submitted to the given HttpConnection.

This implementation adds User-Agent, Host, and Proxy-Authorization headers, when appropriate.

Overrides:
addRequestHeaders in class HttpMethodBase
Parameters:
state - the client state
conn - the HttpConnection the headers will eventually be written to
Throws:
IOException - when an error occurs writing the request
HttpException - when a HTTP protocol error occurs
See Also:
HttpMethodBase.writeRequestHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)

execute

public int execute(HttpState state,
                   HttpConnection conn)
            throws IOException,
                   HttpException
Execute this method and create a tunneled HttpConnection. If the method is successful (i.e. the status is a 2xx) tunnelCreated() will be called on the connection.

Specified by:
execute in interface HttpMethod
Overrides:
execute in class HttpMethodBase
Parameters:
state - the current http state
conn - the connection to write to
Returns:
the http status code from execution
Throws:
HttpException - when an error occurs writing the headers
IOException - when an error occurs writing the headers
See Also:
HttpConnection.tunnelCreated()

writeRequestLine

protected void writeRequestLine(HttpState state,
                                HttpConnection conn)
                         throws IOException,
                                HttpException
Special Connect request.

Overrides:
writeRequestLine in class HttpMethodBase
Parameters:
state - the current http state
conn - the connection to write to
Throws:
IOException - when an error occurs writing the request
HttpException - when an error occurs writing the request
See Also:
HttpMethodBase.generateRequestLine(org.apache.commons.httpclient.HttpConnection, java.lang.String, java.lang.String, java.lang.String, java.lang.String)

shouldCloseConnection

protected boolean shouldCloseConnection(HttpConnection conn)
Returns true if the status code is anything other than SC_OK, false otherwise.

Overrides:
shouldCloseConnection in class HttpMethodBase
Parameters:
conn - the connection in question
Returns:
true if the connection should be closed
See Also:
HttpMethodBase.shouldCloseConnection(HttpConnection), HttpStatus.SC_OK


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ConnectTimeoutException.html100644 0 0 44471 10661532627 30315 0ustar 0 0 ConnectTimeoutException (HttpClient 3.1 API)

org.apache.commons.httpclient
Class ConnectTimeoutException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by java.io.InterruptedIOException
                  extended by org.apache.commons.httpclient.ConnectTimeoutException
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
ConnectionPoolTimeoutException

public class ConnectTimeoutException
extends InterruptedIOException

A timeout while connecting to an HTTP server or waiting for an available connection from an HttpConnectionManager.

Since:
3.0
Author:
Laura Werner
See Also:
Serialized Form

Field Summary
 
Fields inherited from class java.io.InterruptedIOException
bytesTransferred
 
Constructor Summary
ConnectTimeoutException()
          Creates a ConnectTimeoutException with a null detail message.
ConnectTimeoutException(String message)
          Creates a ConnectTimeoutException with the specified detail message.
ConnectTimeoutException(String message, Throwable cause)
          Creates a new ConnectTimeoutException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ConnectTimeoutException

public ConnectTimeoutException()
Creates a ConnectTimeoutException with a null detail message.


ConnectTimeoutException

public ConnectTimeoutException(String message)
Creates a ConnectTimeoutException with the specified detail message.

Parameters:
message - The exception detail message

ConnectTimeoutException

public ConnectTimeoutException(String message,
                               Throwable cause)
Creates a new ConnectTimeoutException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ConnectionPoolTimeoutException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ConnectionPoolTimeoutException.htm100644 0 0 45101 10661532627 31470 0ustar 0 0 ConnectionPoolTimeoutException (HttpClient 3.1 API)

org.apache.commons.httpclient
Class ConnectionPoolTimeoutException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by java.io.InterruptedIOException
                  extended by org.apache.commons.httpclient.ConnectTimeoutException
                      extended by org.apache.commons.httpclient.ConnectionPoolTimeoutException
All Implemented Interfaces:
Serializable

public class ConnectionPoolTimeoutException
extends ConnectTimeoutException

A timeout while connecting waiting for an available connection from an HttpConnectionManager.

Since:
3.0
Author:
Laura Werner
See Also:
Serialized Form

Field Summary
 
Fields inherited from class java.io.InterruptedIOException
bytesTransferred
 
Constructor Summary
ConnectionPoolTimeoutException()
          Creates a ConnectTimeoutException with a null detail message.
ConnectionPoolTimeoutException(String message)
          Creates a ConnectTimeoutException with the specified detail message.
ConnectionPoolTimeoutException(String message, Throwable cause)
          Creates a new ConnectTimeoutException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ConnectionPoolTimeoutException

public ConnectionPoolTimeoutException()
Creates a ConnectTimeoutException with a null detail message.


ConnectionPoolTimeoutException

public ConnectionPoolTimeoutException(String message)
Creates a ConnectTimeoutException with the specified detail message.

Parameters:
message - The exception detail message

ConnectionPoolTimeoutException

public ConnectionPoolTimeoutException(String message,
                                      Throwable cause)
Creates a new ConnectTimeoutException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ContentLengthInputStream.html100644 0 0 64121 10661532627 30440 0ustar 0 0 ContentLengthInputStream (HttpClient 3.1 API)

org.apache.commons.httpclient
Class ContentLengthInputStream

java.lang.Object
  extended by java.io.InputStream
      extended by org.apache.commons.httpclient.ContentLengthInputStream
All Implemented Interfaces:
Closeable

public class ContentLengthInputStream
extends InputStream

Cuts the wrapped InputStream off after a specified number of bytes.

Implementation note: Choices abound. One approach would pass through the InputStream.mark(int) and InputStream.reset() calls to the underlying stream. That's tricky, though, because you then have to start duplicating the work of keeping track of how much a reset rewinds. Further, you have to watch out for the "readLimit", and since the semantics for the readLimit leave room for differing implementations, you might get into a lot of trouble.

Alternatively, you could make this class extend BufferedInputStream and then use the protected members of that class to avoid duplicated effort. That solution has the side effect of adding yet another possible layer of buffering.

Then, there is the simple choice, which this takes - simply don't support InputStream.mark(int) and InputStream.reset(). That choice has the added benefit of keeping this class very simple.

Since:
2.0
Author:
Ortwin Glueck, Eric Johnson, Mike Bowler

Constructor Summary
ContentLengthInputStream(InputStream in, int contentLength)
          Deprecated. use ContentLengthInputStream(InputStream, long) Creates a new length limited stream
ContentLengthInputStream(InputStream in, long contentLength)
          Creates a new length limited stream
 
Method Summary
 int available()
           
 void close()
          Reads until the end of the known length of content.
 int read()
          Read the next byte from the stream
 int read(byte[] b)
          Read more bytes from the stream.
 int read(byte[] b, int off, int len)
          Does standard InputStream.read(byte[], int, int) behavior, but also notifies the watcher when the contents have been consumed.
 long skip(long n)
          Skips and discards a number of bytes from the input stream.
 
Methods inherited from class java.io.InputStream
mark, markSupported, reset
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ContentLengthInputStream

public ContentLengthInputStream(InputStream in,
                                int contentLength)
Deprecated. use ContentLengthInputStream(InputStream, long) Creates a new length limited stream

Parameters:
in - The stream to wrap
contentLength - The maximum number of bytes that can be read from the stream. Subsequent read operations will return -1.

ContentLengthInputStream

public ContentLengthInputStream(InputStream in,
                                long contentLength)
Creates a new length limited stream

Parameters:
in - The stream to wrap
contentLength - The maximum number of bytes that can be read from the stream. Subsequent read operations will return -1.
Since:
3.0
Method Detail

close

public void close()
           throws IOException

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.

Specified by:
close in interface Closeable
Overrides:
close in class InputStream
Throws:
IOException - If an IO problem occurs.

read

public int read()
         throws IOException
Read the next byte from the stream

Specified by:
read in class InputStream
Returns:
The next byte or -1 if the end of stream has been reached.
Throws:
IOException - If an IO problem occurs
See Also:
InputStream.read()

read

public int read(byte[] b,
                int off,
                int len)
         throws IOException
Does standard InputStream.read(byte[], int, int) behavior, but also notifies the watcher when the contents have been consumed.

Overrides:
read in class InputStream
Parameters:
b - The byte array to fill.
off - Start filling at this position.
len - The number of bytes to attempt to read.
Returns:
The number of bytes read, or -1 if the end of content has been reached.
Throws:
IOException - Should an error occur on the wrapped stream.

read

public int read(byte[] b)
         throws IOException
Read more bytes from the stream.

Overrides:
read in class InputStream
Parameters:
b - The byte array to put the new data in.
Returns:
The number of bytes read into the buffer.
Throws:
IOException - If an IO problem occurs
See Also:
InputStream.read(byte[])

skip

public long skip(long n)
          throws IOException
Skips and discards a number of bytes from the input stream.

Overrides:
skip in class InputStream
Parameters:
n - The number of bytes to skip.
Returns:
The actual number of bytes skipped. <= 0 if no bytes are skipped.
Throws:
IOException - If an error occurs while skipping bytes.
See Also:
InputStream.skip(long)

available

public int available()
              throws IOException
Overrides:
available in class InputStream
Throws:
IOException


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/Cookie.html100644 0 0 137256 10661532627 24733 0ustar 0 0 Cookie (HttpClient 3.1 API)

org.apache.commons.httpclient
Class Cookie

java.lang.Object
  extended by org.apache.commons.httpclient.NameValuePair
      extended by org.apache.commons.httpclient.Cookie
All Implemented Interfaces:
Serializable, Comparator
Direct Known Subclasses:
Cookie2

public class Cookie
extends NameValuePair
implements Serializable, Comparator

HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.

Version:
$Revision: 531354 $ $Date: 2007-04-23 08:53:20 +0200 (Mon, 23 Apr 2007) $
Author:
B.C. Holmes, Park, Sung-Gu, Doug Sale, Rod Waldhoff, dIon Gillard, Sean C. Sullivan, John Evans, Marc A. Saegesser, Oleg Kalnichevski, Mike Bowler
See Also:
Serialized Form

Constructor Summary
Cookie()
          Default constructor.
Cookie(String domain, String name, String value)
          Creates a cookie with the given name, value and domain attribute.
Cookie(String domain, String name, String value, String path, Date expires, boolean secure)
          Creates a cookie with the given name, value, domain attribute, path attribute, expiration attribute, and secure attribute
Cookie(String domain, String name, String value, String path, int maxAge, boolean secure)
          Creates a cookie with the given name, value, domain attribute, path attribute, maximum age attribute, and secure attribute
 
Method Summary
 int compare(Object o1, Object o2)
          Compares two cookies to determine order for cookie header.
 boolean equals(Object obj)
          Two cookies are equal if the name, path and domain match.
 String getComment()
          Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.
 String getDomain()
          Returns domain attribute of the cookie.
 Date getExpiryDate()
          Returns the expiration Date of the cookie, or null if none exists.
 String getPath()
          Returns the path attribute of the cookie
 boolean getSecure()
           
 int getVersion()
          Returns the version of the cookie specification to which this cookie conforms.
 int hashCode()
          Returns a hash code in keeping with the Object.hashCode() general hashCode contract.
 boolean isDomainAttributeSpecified()
          Returns true if cookie's domain was set via a domain attribute in the Set-Cookie header.
 boolean isExpired()
          Returns true if this cookie has expired.
 boolean isExpired(Date now)
          Returns true if this cookie has expired according to the time passed in.
 boolean isPathAttributeSpecified()
          Returns true if cookie's path was set via a path attribute in the Set-Cookie header.
 boolean isPersistent()
          Returns false if the cookie should be discarded at the end of the "session"; true otherwise.
 void setComment(String comment)
          If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment.
 void setDomain(String domain)
          Sets the domain attribute.
 void setDomainAttributeSpecified(boolean value)
          Indicates whether the cookie had a domain specified in a domain attribute of the Set-Cookie header.
 void setExpiryDate(Date expiryDate)
          Sets expiration date.
 void setPath(String path)
          Sets the path attribute.
 void setPathAttributeSpecified(boolean value)
          Indicates whether the cookie had a path specified in a path attribute of the Set-Cookie header.
 void setSecure(boolean secure)
          Sets the secure attribute of the cookie.
 void setVersion(int version)
          Sets the version of the cookie specification to which this cookie conforms.
 String toExternalForm()
          Return a textual representation of the cookie.
 String toString()
          Return a textual representation of the cookie.
 
Methods inherited from class org.apache.commons.httpclient.NameValuePair
getName, getValue, setName, setValue
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Cookie

public Cookie()
Default constructor. Creates a blank cookie


Cookie

public Cookie(String domain,
              String name,
              String value)
Creates a cookie with the given name, value and domain attribute.

Parameters:
name - the cookie name
value - the cookie value
domain - the domain this cookie can be sent to

Cookie

public Cookie(String domain,
              String name,
              String value,
              String path,
              Date expires,
              boolean secure)
Creates a cookie with the given name, value, domain attribute, path attribute, expiration attribute, and secure attribute

Parameters:
name - the cookie name
value - the cookie value
domain - the domain this cookie can be sent to
path - the path prefix for which this cookie can be sent
expires - the Date at which this cookie expires, or null if the cookie expires at the end of the session
secure - if true this cookie can only be sent over secure connections
Throws:
IllegalArgumentException - If cookie name is null or blank, cookie name contains a blank, or cookie name starts with character $

Cookie

public Cookie(String domain,
              String name,
              String value,
              String path,
              int maxAge,
              boolean secure)
Creates a cookie with the given name, value, domain attribute, path attribute, maximum age attribute, and secure attribute

Parameters:
name - the cookie name
value - the cookie value
domain - the domain this cookie can be sent to
path - the path prefix for which this cookie can be sent
maxAge - the number of seconds for which this cookie is valid. maxAge is expected to be a non-negative number. -1 signifies that the cookie should never expire.
secure - if true this cookie can only be sent over secure connections
Method Detail

getComment

public String getComment()
Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.

Returns:
comment
See Also:
setComment(String)

setComment

public void setComment(String comment)
If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment.

Parameters:
comment -
See Also:
getComment()

getExpiryDate

public Date getExpiryDate()
Returns the expiration Date of the cookie, or null if none exists.

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

Returns:
Expiration Date, or null.
See Also:
setExpiryDate(java.util.Date)

setExpiryDate

public void setExpiryDate(Date expiryDate)
Sets expiration date.

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

Parameters:
expiryDate - the Date after which this cookie is no longer valid.
See Also:
getExpiryDate()

isPersistent

public boolean isPersistent()
Returns false if the cookie should be discarded at the end of the "session"; true otherwise.

Returns:
false if the cookie should be discarded at the end of the "session"; true otherwise

getDomain

public String getDomain()
Returns domain attribute of the cookie.

Returns:
the value of the domain attribute
See Also:
setDomain(java.lang.String)

setDomain

public void setDomain(String domain)
Sets the domain attribute.

Parameters:
domain - The value of the domain attribute
See Also:
getDomain()

getPath

public String getPath()
Returns the path attribute of the cookie

Returns:
The value of the path attribute.
See Also:
setPath(java.lang.String)

setPath

public void setPath(String path)
Sets the path attribute.

Parameters:
path - The value of the path attribute
See Also:
getPath()

getSecure

public boolean getSecure()
Returns:
true if this cookie should only be sent over secure connections.
See Also:
setSecure(boolean)

setSecure

public void setSecure(boolean secure)
Sets the secure attribute of the cookie.

When true the cookie should only be sent using a secure protocol (https). This should only be set when the cookie's originating server used a secure protocol to set the cookie's value.

Parameters:
secure - The value of the secure attribute
See Also:
getSecure()

getVersion

public int getVersion()
Returns the version of the cookie specification to which this cookie conforms.

Returns:
the version of the cookie.
See Also:
setVersion(int)

setVersion

public void setVersion(int version)
Sets the version of the cookie specification to which this cookie conforms.

Parameters:
version - the version of the cookie.
See Also:
getVersion()

isExpired

public boolean isExpired()
Returns true if this cookie has expired.

Returns:
true if the cookie has expired.

isExpired

public boolean isExpired(Date now)
Returns true if this cookie has expired according to the time passed in.

Parameters:
now - The current time.
Returns:
true if the cookie expired.

setPathAttributeSpecified

public void setPathAttributeSpecified(boolean value)
Indicates whether the cookie had a path specified in a path attribute of the Set-Cookie header. This value is important for generating the Cookie header because some cookie specifications require that the Cookie header should only include a path attribute if the cookie's path was specified in the Set-Cookie header.

Parameters:
value - true if the cookie's path was explicitly set, false otherwise.
See Also:
isPathAttributeSpecified()

isPathAttributeSpecified

public boolean isPathAttributeSpecified()
Returns true if cookie's path was set via a path attribute in the Set-Cookie header.

Returns:
value true if the cookie's path was explicitly set, false otherwise.
See Also:
setPathAttributeSpecified(boolean)

setDomainAttributeSpecified

public void setDomainAttributeSpecified(boolean value)
Indicates whether the cookie had a domain specified in a domain attribute of the Set-Cookie header. This value is important for generating the Cookie header because some cookie specifications require that the Cookie header should only include a domain attribute if the cookie's domain was specified in the Set-Cookie header.

Parameters:
value - true if the cookie's domain was explicitly set, false otherwise.
See Also:
isDomainAttributeSpecified()

isDomainAttributeSpecified

public boolean isDomainAttributeSpecified()
Returns true if cookie's domain was set via a domain attribute in the Set-Cookie header.

Returns:
value true if the cookie's domain was explicitly set, false otherwise.
See Also:
setDomainAttributeSpecified(boolean)

hashCode

public int hashCode()
Returns a hash code in keeping with the Object.hashCode() general hashCode contract.

Overrides:
hashCode in class NameValuePair
Returns:
A hash code

equals

public boolean equals(Object obj)
Two cookies are equal if the name, path and domain match.

Specified by:
equals in interface Comparator
Overrides:
equals in class NameValuePair
Parameters:
obj - The object to compare against.
Returns:
true if the two objects are equal.

toExternalForm

public String toExternalForm()
Return a textual representation of the cookie.

Returns:
string.

compare

public int compare(Object o1,
                   Object o2)

Compares two cookies to determine order for cookie header.

Most specific should be first.

This method is implemented so a cookie can be used as a comparator for a SortedSet of cookies. Specifically it's used above in the createCookieHeader method.

Specified by:
compare in interface Comparator
Parameters:
o1 - The first object to be compared
o2 - The second object to be compared
Returns:
See Comparator.compare(Object,Object)

toString

public String toString()
Return a textual representation of the cookie.

Overrides:
toString in class NameValuePair
Returns:
string.
See Also:
toExternalForm()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/Credentials.html100644 0 0 17062 10661532627 25727 0ustar 0 0 Credentials (HttpClient 3.1 API)

org.apache.commons.httpclient
Interface Credentials

All Known Implementing Classes:
NTCredentials, UsernamePasswordCredentials

public interface Credentials

Authentication credentials.

This is just a marker interface, the current implementation has no methods.

Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
Unascribed, Mike Bowler



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/DefaultHttpMethodRetryHandler.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/DefaultHttpMethodRetryHandler.html100644 0 0 42422 10661532627 31401 0ustar 0 0 DefaultHttpMethodRetryHandler (HttpClient 3.1 API)

org.apache.commons.httpclient
Class DefaultHttpMethodRetryHandler

java.lang.Object
  extended by org.apache.commons.httpclient.DefaultHttpMethodRetryHandler
All Implemented Interfaces:
HttpMethodRetryHandler

public class DefaultHttpMethodRetryHandler
extends Object
implements HttpMethodRetryHandler

The default HttpMethodRetryHandler used by HttpMethods.

Author:
Michael Becke, Oleg Kalnichevski

Constructor Summary
DefaultHttpMethodRetryHandler()
          Creates a new DefaultHttpMethodRetryHandler that retries up to 3 times but does not retry methods that have successfully sent their requests.
DefaultHttpMethodRetryHandler(int retryCount, boolean requestSentRetryEnabled)
          Creates a new DefaultHttpMethodRetryHandler.
 
Method Summary
 int getRetryCount()
           
 boolean isRequestSentRetryEnabled()
           
 boolean retryMethod(HttpMethod method, IOException exception, int executionCount)
          Used retryCount and requestSentRetryEnabled to determine if the given method should be retried.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

DefaultHttpMethodRetryHandler

public DefaultHttpMethodRetryHandler(int retryCount,
                                     boolean requestSentRetryEnabled)
Creates a new DefaultHttpMethodRetryHandler.

Parameters:
retryCount - the number of times a method will be retried
requestSentRetryEnabled - if true, methods that have successfully sent their request will be retried

DefaultHttpMethodRetryHandler

public DefaultHttpMethodRetryHandler()
Creates a new DefaultHttpMethodRetryHandler that retries up to 3 times but does not retry methods that have successfully sent their requests.

Method Detail

retryMethod

public boolean retryMethod(HttpMethod method,
                           IOException exception,
                           int executionCount)
Used retryCount and requestSentRetryEnabled to determine if the given method should be retried.

Specified by:
retryMethod in interface HttpMethodRetryHandler
Parameters:
method - the method being executed
exception - the exception that occurred
executionCount - the number of times this method has been unsuccessfully executed
Returns:
true if the method should be retried, false otherwise
See Also:
HttpMethodRetryHandler.retryMethod(HttpMethod, IOException, int)

isRequestSentRetryEnabled

public boolean isRequestSentRetryEnabled()
Returns:
true if this handler will retry methods that have successfully sent their request, false otherwise

getRetryCount

public int getRetryCount()
Returns:
the maximum number of times a method will be retried


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/DefaultMethodRetryHandler.html100644 0 0 46000 10661532627 30535 0ustar 0 0 DefaultMethodRetryHandler (HttpClient 3.1 API)

org.apache.commons.httpclient
Class DefaultMethodRetryHandler

java.lang.Object
  extended by org.apache.commons.httpclient.DefaultMethodRetryHandler
All Implemented Interfaces:
MethodRetryHandler

Deprecated. use DefaultHttpMethodRetryHandler

public class DefaultMethodRetryHandler
extends Object
implements MethodRetryHandler

The default MethodRetryHandler used by HttpMethodBase.

Author:
Michael Becke
See Also:
HttpMethodBase.setMethodRetryHandler(MethodRetryHandler)

Constructor Summary
DefaultMethodRetryHandler()
          Deprecated.  
 
Method Summary
 int getRetryCount()
          Deprecated.  
 boolean isRequestSentRetryEnabled()
          Deprecated.  
 boolean retryMethod(HttpMethod method, HttpConnection connection, HttpRecoverableException recoverableException, int executionCount, boolean requestSent)
          Deprecated. Used retryCount and requestSentRetryEnabled to determine if the given method should be retried.
 void setRequestSentRetryEnabled(boolean requestSentRetryEnabled)
          Deprecated.  
 void setRetryCount(int retryCount)
          Deprecated.  
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

DefaultMethodRetryHandler

public DefaultMethodRetryHandler()
Deprecated. 
Method Detail

retryMethod

public boolean retryMethod(HttpMethod method,
                           HttpConnection connection,
                           HttpRecoverableException recoverableException,
                           int executionCount,
                           boolean requestSent)
Deprecated. 
Used retryCount and requestSentRetryEnabled to determine if the given method should be retried.

Specified by:
retryMethod in interface MethodRetryHandler
Parameters:
method - the method being executed
connection - the connection the method is using
recoverableException - the exception that occurred
executionCount - the number of times this method has been unsuccessfully executed
requestSent - this argument is unused and will be removed in the future. HttpMethod.isRequestSent() should be used instead
Returns:
true if the method should be retried, false otherwise
See Also:
MethodRetryHandler.retryMethod(HttpMethod, HttpConnection, HttpRecoverableException, int, boolean)

isRequestSentRetryEnabled

public boolean isRequestSentRetryEnabled()
Deprecated. 
Returns:
true if this handler will retry methods that have successfully sent their request, false otherwise

getRetryCount

public int getRetryCount()
Deprecated. 
Returns:
the maximum number of times a method will be retried

setRequestSentRetryEnabled

public void setRequestSentRetryEnabled(boolean requestSentRetryEnabled)
Deprecated. 
Parameters:
requestSentRetryEnabled - a flag indicating if methods that have successfully sent their request should be retried

setRetryCount

public void setRetryCount(int retryCount)
Deprecated. 
Parameters:
retryCount - the maximum number of times a method can be retried


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/Header.html100644 0 0 52265 10661532627 24666 0ustar 0 0 Header (HttpClient 3.1 API)

org.apache.commons.httpclient
Class Header

java.lang.Object
  extended by org.apache.commons.httpclient.NameValuePair
      extended by org.apache.commons.httpclient.Header
All Implemented Interfaces:
Serializable

public class Header
extends NameValuePair

An HTTP header.

Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
Remy Maucherat, Mike Bowler, Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
Header()
          Default constructor.
Header(String name, String value)
          Constructor with name and value
Header(String name, String value, boolean isAutogenerated)
          Constructor with name and value
 
Method Summary
 HeaderElement[] getElements()
          Returns an array of HeaderElements constructed from my value.
 HeaderElement[] getValues()
          Deprecated. Use #getElements
 boolean isAutogenerated()
          Returns the value of the auto-generated header flag.
 String toExternalForm()
          Returns a String representation of the header.
 String toString()
          Returns a String representation of the header.
 
Methods inherited from class org.apache.commons.httpclient.NameValuePair
equals, getName, getValue, hashCode, setName, setValue
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Header

public Header()
Default constructor.


Header

public Header(String name,
              String value)
Constructor with name and value

Parameters:
name - the header name
value - the header value

Header

public Header(String name,
              String value,
              boolean isAutogenerated)
Constructor with name and value

Parameters:
name - the header name
value - the header value
isAutogenerated - true if the header is autogenerated, false otherwise.
Since:
3.0
Method Detail

toExternalForm

public String toExternalForm()
Returns a String representation of the header.

Returns:
stringHEAD

toString

public String toString()
Returns a String representation of the header.

Overrides:
toString in class NameValuePair
Returns:
stringHEAD

getValues

public HeaderElement[] getValues()
                          throws HttpException
Deprecated. Use #getElements

Returns an array of HeaderElements constructed from my value.

Returns:
an array of header elements
Throws:
HttpException - if the header cannot be parsed
See Also:
HeaderElement.parse(java.lang.String)

getElements

public HeaderElement[] getElements()
Returns an array of HeaderElements constructed from my value.

Returns:
an array of header elements
Since:
3.0
See Also:
HeaderElement.parseElements(String)

isAutogenerated

public boolean isAutogenerated()
Returns the value of the auto-generated header flag.

Returns:
true if the header is autogenerated, false otherwise.
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HeaderElement.html100644 0 0 63702 10661532627 26176 0ustar 0 0 HeaderElement (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HeaderElement

java.lang.Object
  extended by org.apache.commons.httpclient.NameValuePair
      extended by org.apache.commons.httpclient.HeaderElement
All Implemented Interfaces:
Serializable

public class HeaderElement
extends NameValuePair

One element of an HTTP header's value.

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 String; if the "=" is also missing null will be stored instead.

This class represents an individual header element, containing both a name/value pair (value may be null) and optionally a set of additional parameters.

This class also exposes a parse(java.lang.String) method for parsing a Header value into an array of elements.

Since:
1.0
Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
B.C. Holmes, Park, Sung-Gu, Mike Bowler, Oleg Kalnichevski
See Also:
Header, Serialized Form

Constructor Summary
HeaderElement()
          Default constructor.
HeaderElement(char[] chars)
          Constructor with array of characters.
HeaderElement(char[] chars, int offset, int length)
          Constructor with array of characters.
HeaderElement(String name, String value)
          Constructor.
HeaderElement(String name, String value, NameValuePair[] parameters)
          Constructor with name, value and parameters.
 
Method Summary
 NameValuePair getParameterByName(String name)
          Returns parameter with the given name, if found.
 NameValuePair[] getParameters()
          Get parameters, if any.
static HeaderElement[] parse(String headerValue)
          Deprecated. Use #parseElements(String).
static HeaderElement[] parseElements(char[] headerValue)
          This parses the value part of a header.
static HeaderElement[] parseElements(String headerValue)
          This parses the value part of a header.
 
Methods inherited from class org.apache.commons.httpclient.NameValuePair
equals, getName, getValue, hashCode, setName, setValue, toString
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

HeaderElement

public HeaderElement()
Default constructor.


HeaderElement

public HeaderElement(String name,
                     String value)
Constructor.

Parameters:
name - my name
value - my (possibly null) value

HeaderElement

public HeaderElement(String name,
                     String value,
                     NameValuePair[] parameters)
Constructor with name, value and parameters.

Parameters:
name - my name
value - my (possibly null) value
parameters - my (possibly null) parameters

HeaderElement

public HeaderElement(char[] chars,
                     int offset,
                     int length)
Constructor with array of characters.

Parameters:
chars - the array of characters
offset - - the initial offset.
length - - the length.
Since:
3.0

HeaderElement

public HeaderElement(char[] chars)
Constructor with array of characters.

Parameters:
chars - the array of characters
Since:
3.0
Method Detail

getParameters

public NameValuePair[] getParameters()
Get parameters, if any.

Returns:
parameters as an array of NameValuePairs
Since:
2.0

parseElements

public static final HeaderElement[] parseElements(char[] headerValue)
This parses the value part of a header. The result is an array of HeaderElement objects.

Parameters:
headerValue - the array of char representation of the header value (as received from the web server).
Returns:
array of HeaderElements.
Since:
3.0

parseElements

public static final HeaderElement[] parseElements(String headerValue)
This parses the value part of a header. The result is an array of HeaderElement objects.

Parameters:
headerValue - the string representation of the header value (as received from the web server).
Returns:
array of HeaderElements.
Since:
3.0

parse

public static final HeaderElement[] parse(String headerValue)
                                   throws HttpException
Deprecated. Use #parseElements(String).

This parses the value part of a header. The result is an array of HeaderElement objects.

Parameters:
headerValue - the string representation of the header value (as received from the web server).
Returns:
array of HeaderElements.
Throws:
HttpException - if the above syntax rules are violated.

getParameterByName

public NameValuePair getParameterByName(String name)
Returns parameter with the given name, if found. Otherwise null is returned

Parameters:
name - The name to search by.
Returns:
NameValuePair parameter with the given name


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HeaderGroup.html100644 0 0 56237 10661532627 25706 0ustar 0 0 HeaderGroup (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HeaderGroup

java.lang.Object
  extended by org.apache.commons.httpclient.HeaderGroup

public class HeaderGroup
extends Object

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:
2.0beta1
Author:
Michael Becke

Constructor Summary
HeaderGroup()
          Constructor for HeaderGroup.
 
Method Summary
 void addHeader(Header header)
          Adds the given header to the group.
 void clear()
          Removes any contained headers.
 boolean containsHeader(String name)
          Tests if headers with the given name are contained within this group.
 Header[] getAllHeaders()
          Gets all of the headers contained within this group.
 Header getCondensedHeader(String name)
          Gets a header representing all of the header values with the given name.
 Header getFirstHeader(String name)
          Gets the first header with the given name.
 Header[] getHeaders(String name)
          Gets all of the headers with the given name.
 Iterator getIterator()
          Returns an iterator over this group of headers.
 Header getLastHeader(String name)
          Gets the last header with the given name.
 void removeHeader(Header header)
          Removes the given header.
 void setHeaders(Header[] headers)
          Sets all of the headers contained within this group overriding any existing headers.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

HeaderGroup

public HeaderGroup()
Constructor for HeaderGroup.

Method Detail

clear

public void clear()
Removes any contained headers.


addHeader

public void addHeader(Header header)
Adds the given header to the group. The order in which this header was added is preserved.

Parameters:
header - the header to add

removeHeader

public void removeHeader(Header header)
Removes the given header.

Parameters:
header - the header to remove

setHeaders

public void setHeaders(Header[] headers)
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.

Parameters:
headers - the headers to set

getCondensedHeader

public Header getCondensedHeader(String name)
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.

Parameters:
name - the name of the header(s) to get
Returns:
a header with a condensed value or null if no headers by the given name are present

getHeaders

public Header[] getHeaders(String name)
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.

Parameters:
name - the name of the header(s) to get
Returns:
an array of length >= 0

getFirstHeader

public Header getFirstHeader(String name)
Gets the first header with the given name.

Header name comparison is case insensitive.

Parameters:
name - the name of the header to get
Returns:
the first header or null

getLastHeader

public Header getLastHeader(String name)
Gets the last header with the given name.

Header name comparison is case insensitive.

Parameters:
name - the name of the header to get
Returns:
the last header or null

getAllHeaders

public Header[] getAllHeaders()
Gets all of the headers contained within this group.

Returns:
an array of length >= 0

containsHeader

public boolean containsHeader(String name)
Tests if headers with the given name are contained within this group.

Header name comparison is case insensitive.

Parameters:
name - the header name to test for
Returns:
true if at least one header with the name is contained, false otherwise

getIterator

public Iterator getIterator()
Returns an iterator over this group of headers.

Returns:
iterator over this group of headers.
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HostConfiguration.html100644 0 0 132274 10661532627 27162 0ustar 0 0 HostConfiguration (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HostConfiguration

java.lang.Object
  extended by org.apache.commons.httpclient.HostConfiguration
All Implemented Interfaces:
Cloneable

public class HostConfiguration
extends Object
implements Cloneable

Holds all of the variables needed to describe an HTTP connection to a host. This includes remote host, port and protocol, proxy host and port, local address, and virtual host.

Since:
2.0
Author:
Michael Becke, Mike Bowler, Oleg Kalnichevski, Laura Werner

Field Summary
static HostConfiguration ANY_HOST_CONFIGURATION
          A value to represent any host configuration, instead of using something like null.
 
Constructor Summary
HostConfiguration()
          Constructor for HostConfiguration.
HostConfiguration(HostConfiguration hostConfiguration)
          Copy constructor for HostConfiguration
 
Method Summary
 Object clone()
           
 boolean equals(Object o)
           
 String getHost()
          Returns the host.
 String getHostURL()
          Return the host url.
 InetAddress getLocalAddress()
          Return the local address to be used when creating connections.
 HostParams getParams()
          Returns HTTP protocol parameters associated with this host.
 int getPort()
          Returns the port.
 Protocol getProtocol()
          Returns the protocol.
 String getProxyHost()
          Returns the proxyHost.
 int getProxyPort()
          Returns the proxyPort.
 String getVirtualHost()
          Deprecated. use HostParams
 int hashCode()
           
 boolean hostEquals(HttpConnection connection)
          Tests if the host configuration equals the configuration set on the connection.
 boolean isHostSet()
          Deprecated. no longer used
 boolean isProxySet()
          Deprecated. no longer used
 boolean proxyEquals(HttpConnection connection)
          Tests if the proxy configuration equals the configuration set on the connection.
 void setHost(HttpHost host)
          Sets the given host
 void setHost(String host)
          Set the given host.
 void setHost(String host, int port)
          Sets the given host and port.
 void setHost(String host, int port, Protocol protocol)
          Sets the given host, port and protocol.
 void setHost(String host, int port, String protocol)
          Sets the given host, port and protocol
 void setHost(String host, String virtualHost, int port, Protocol protocol)
          Deprecated. #setHost(String, int, Protocol)
 void setHost(URI uri)
          Sets the protocol, host and port from the given URI.
 void setLocalAddress(InetAddress localAddress)
          Set the local address to be used when creating connections.
 void setParams(HostParams params)
          Assigns HTTP protocol parameters specific to this host.
 void setProxy(String proxyHost, int proxyPort)
          Set the proxy settings.
 void setProxyHost(ProxyHost proxyHost)
          Sets the given proxy host
 String toString()
           
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

ANY_HOST_CONFIGURATION

public static final HostConfiguration ANY_HOST_CONFIGURATION
A value to represent any host configuration, instead of using something like null. This value should be treated as immutable and only used in lookups and other such places to represent "any" host config.

Constructor Detail

HostConfiguration

public HostConfiguration()
Constructor for HostConfiguration.


HostConfiguration

public HostConfiguration(HostConfiguration hostConfiguration)
Copy constructor for HostConfiguration

Parameters:
hostConfiguration - the hostConfiguration to copy
Method Detail

clone

public Object clone()
Overrides:
clone in class Object
See Also:
Object.clone()

toString

public String toString()
Overrides:
toString in class Object
See Also:
Object.toString()

hostEquals

public boolean hostEquals(HttpConnection connection)
Tests if the host configuration equals the configuration set on the connection. True only if the host, port, protocol, local address and virtual address are equal. If no host configuration has been set false will be returned.

Parameters:
connection - the connection to test against
Returns:
true if the connection's host information equals that of this configuration
See Also:
proxyEquals(HttpConnection)

proxyEquals

public boolean proxyEquals(HttpConnection connection)
Tests if the proxy configuration equals the configuration set on the connection. True only if the proxyHost and proxyPort are equal.

Parameters:
connection - the connection to test against
Returns:
true if the connection's proxy information equals that of this configuration
See Also:
hostEquals(HttpConnection)

isHostSet

public boolean isHostSet()
Deprecated. no longer used

Returns true if the host is set.

Returns:
true if the host is set.

setHost

public void setHost(HttpHost host)
Sets the given host

Parameters:
host - the host

setHost

public void setHost(String host,
                    int port,
                    String protocol)
Sets the given host, port and protocol

Parameters:
host - the host(IP or DNS name)
port - The port
protocol - The protocol.

setHost

public void setHost(String host,
                    String virtualHost,
                    int port,
                    Protocol protocol)
Deprecated. #setHost(String, int, Protocol)

Sets the given host, virtual host, port and protocol.

Parameters:
host - the host(IP or DNS name)
virtualHost - the virtual host name or null
port - the host port or -1 to use protocol default
protocol - the protocol

setHost

public void setHost(String host,
                    int port,
                    Protocol protocol)
Sets the given host, port and protocol.

Parameters:
host - the host(IP or DNS name)
port - The port
protocol - the protocol

setHost

public void setHost(String host,
                    int port)
Sets the given host and port. Uses the default protocol "http".

Parameters:
host - the host(IP or DNS name)
port - The port

setHost

public void setHost(String host)
Set the given host. Uses the default protocol("http") and its port.

Parameters:
host - The host(IP or DNS name).

setHost

public void setHost(URI uri)
Sets the protocol, host and port from the given URI.

Parameters:
uri - the URI.

getHostURL

public String getHostURL()
Return the host url.

Returns:
The host url.

getHost

public String getHost()
Returns the host.

Returns:
the host(IP or DNS name), or null if not set
See Also:
isHostSet()

getVirtualHost

public String getVirtualHost()
Deprecated. use HostParams

Returns the virtual host.

Returns:
the virtual host name, or null if not set

getPort

public int getPort()
Returns the port.

Returns:
the host port, or -1 if not set
See Also:
isHostSet()

getProtocol

public Protocol getProtocol()
Returns the protocol.

Returns:
The protocol.

isProxySet

public boolean isProxySet()
Deprecated. no longer used

Tests if the proxy host/port have been set.

Returns:
true if a proxy server has been set.
See Also:
setProxy(String, int)

setProxyHost

public void setProxyHost(ProxyHost proxyHost)
Sets the given proxy host

Parameters:
proxyHost - the proxy host

setProxy

public void setProxy(String proxyHost,
                     int proxyPort)
Set the proxy settings.

Parameters:
proxyHost - The proxy host
proxyPort - The proxy port

getProxyHost

public String getProxyHost()
Returns the proxyHost.

Returns:
the proxy host, or null if not set
See Also:
isProxySet()

getProxyPort

public int getProxyPort()
Returns the proxyPort.

Returns:
the proxy port, or -1 if not set
See Also:
isProxySet()

setLocalAddress

public void setLocalAddress(InetAddress localAddress)
Set the local address to be used when creating connections. If this is unset, the default address will be used. This is useful for specifying the interface to use on multi-homed or clustered systems.

Parameters:
localAddress - the local address to use

getLocalAddress

public InetAddress getLocalAddress()
Return the local address to be used when creating connections. If this is unset, the default address should be used.

Returns:
the local address to be used when creating Sockets, or null

getParams

public HostParams getParams()
Returns HTTP protocol parameters associated with this host.

Returns:
HTTP parameters.
Since:
3.0

setParams

public void setParams(HostParams params)
Assigns HTTP protocol parameters specific to this host.

Since:
3.0
See Also:
HostParams

equals

public boolean equals(Object o)
Overrides:
equals in class Object
See Also:
Object.equals(java.lang.Object)

hashCode

public int hashCode()
Overrides:
hashCode in class Object
See Also:
Object.hashCode()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpClient.html100644 0 0 144331 10661532627 25570 0ustar 0 0 HttpClient (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpClient

java.lang.Object
  extended by org.apache.commons.httpclient.HttpClient

public class HttpClient
extends Object

An HTTP "user-agent", containing an HTTP state and one or more HTTP connections, to which HTTP methods can be applied.

Version:
$Revision: 509577 $ $Date: 2007-02-20 15:28:18 +0100 (Tue, 20 Feb 2007) $
Author:
Remy Maucherat, Rodney Waldhoff, Sean C. Sullivan, dIon Gillard, Ortwin Gl?ck, Michael Becke, Mike Bowler, Sam Maloney, Laura Werner, Oleg Kalnichevski

Constructor Summary
HttpClient()
          Creates an instance of HttpClient using default parameter set.
HttpClient(HttpClientParams params)
          Creates an instance of HttpClient using the given parameter set.
HttpClient(HttpClientParams params, HttpConnectionManager httpConnectionManager)
          Creates an instance of HttpClient with a user specified parameter set and HTTP connection manager.
HttpClient(HttpConnectionManager httpConnectionManager)
          Creates an instance of HttpClient with a user specified HTTP connection manager.
 
Method Summary
 int executeMethod(HostConfiguration hostConfiguration, HttpMethod method)
          Executes the given HTTP method using custom host configuration.
 int executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state)
          Executes the given HTTP method using the given custom host configuration with the given custom HTTP state.
 int executeMethod(HttpMethod method)
          Executes the given HTTP method.
 String getHost()
          Deprecated. use #getHostConfiguration()
 HostConfiguration getHostConfiguration()
          Returns the host configuration associated with the HttpClient.
 HttpConnectionManager getHttpConnectionManager()
          Returns the HTTP connection manager associated with the HttpClient.
 HttpClientParams getParams()
          Returns HTTP protocol parameters associated with this HttpClient.
 int getPort()
          Deprecated. use #getHostConfiguration()
 HttpState getState()
          Returns HTTP state associated with the HttpClient.
 boolean isStrictMode()
          Deprecated. Use DefaultHttpParams.getParameter(String) to exercise a more granular control over HTTP protocol strictness.
 void setConnectionTimeout(int newTimeoutInMilliseconds)
          Deprecated. Use HttpConnectionParams.setConnectionTimeout(int), HttpConnectionManager.getParams().
 void setHostConfiguration(HostConfiguration hostConfiguration)
          Assigns the host configuration to use with the HttpClient.
 void setHttpConnectionFactoryTimeout(long timeout)
          Deprecated. Use HttpClientParams.setConnectionManagerTimeout(long), getParams()
 void setHttpConnectionManager(HttpConnectionManager httpConnectionManager)
          Assigns the HTTP connection manager to use with the HttpClient.
 void setParams(HttpClientParams params)
          Assigns HTTP protocol parameters for this HttpClient.
 void setState(HttpState state)
          Assigns HTTP state for the HttpClient.
 void setStrictMode(boolean strictMode)
          Deprecated. Use DefaultHttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.
 void setTimeout(int newTimeoutInMilliseconds)
          Deprecated. Use HttpConnectionParams.setSoTimeout(int), HttpConnectionManager.getParams().
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

HttpClient

public HttpClient()
Creates an instance of HttpClient using default parameter set.

See Also:
HttpClientParams

HttpClient

public HttpClient(HttpClientParams params)
Creates an instance of HttpClient using the given parameter set.

Parameters:
params - The parameters to use.
Since:
3.0
See Also:
HttpClientParams

HttpClient

public HttpClient(HttpClientParams params,
                  HttpConnectionManager httpConnectionManager)
Creates an instance of HttpClient with a user specified parameter set and HTTP connection manager.

Parameters:
params - The parameters to use.
httpConnectionManager - The connection manager to use.
Since:
3.0

HttpClient

public HttpClient(HttpConnectionManager httpConnectionManager)
Creates an instance of HttpClient with a user specified HTTP connection manager.

Parameters:
httpConnectionManager - The connection manager to use.
Since:
2.0
Method Detail

getState

public HttpState getState()
Returns HTTP state associated with the HttpClient.

Returns:
the shared client state
See Also:
setState(HttpState)

setState

public void setState(HttpState state)
Assigns HTTP state for the HttpClient.

Parameters:
state - the new HTTP state for the client
See Also:
getState()

setStrictMode

public void setStrictMode(boolean strictMode)
Deprecated. Use DefaultHttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.

Defines how strictly the method follows the HTTP protocol specification (see RFC 2616 and other relevant RFCs). In the strict mode the method precisely implements the requirements of the specification, whereas in non-strict mode it attempts to mimic the exact behaviour of commonly used HTTP agents, which many HTTP servers expect.

Parameters:
strictMode - true for strict mode, false otherwise
See Also:
isStrictMode()

isStrictMode

public boolean isStrictMode()
Deprecated. Use DefaultHttpParams.getParameter(String) to exercise a more granular control over HTTP protocol strictness.

Returns the value of the strict mode flag.

Returns:
true if strict mode is enabled, false otherwise
See Also:
setStrictMode(boolean)

setTimeout

public void setTimeout(int newTimeoutInMilliseconds)
Deprecated. Use HttpConnectionParams.setSoTimeout(int), HttpConnectionManager.getParams().

Sets the socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout.

Parameters:
newTimeoutInMilliseconds - Timeout in milliseconds

setHttpConnectionFactoryTimeout

public void setHttpConnectionFactoryTimeout(long timeout)
Deprecated. Use HttpClientParams.setConnectionManagerTimeout(long), getParams()

Sets the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.

Parameters:
timeout - the timeout in milliseconds
See Also:
HttpConnectionManager.getConnection(HostConfiguration, long)

setConnectionTimeout

public void setConnectionTimeout(int newTimeoutInMilliseconds)
Deprecated. Use HttpConnectionParams.setConnectionTimeout(int), HttpConnectionManager.getParams().

Sets the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.

Parameters:
newTimeoutInMilliseconds - Timeout in milliseconds.
See Also:
HttpConnection.setConnectionTimeout(int)

executeMethod

public int executeMethod(HttpMethod method)
                  throws IOException,
                         HttpException
Executes the given HTTP method.

Parameters:
method - the HTTP method to execute.
Returns:
the method's response code
Throws:
IOException - If an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - If a protocol exception occurs. Usually protocol exceptions cannot be recovered from.

executeMethod

public int executeMethod(HostConfiguration hostConfiguration,
                         HttpMethod method)
                  throws IOException,
                         HttpException
Executes the given HTTP method using custom host configuration.

Parameters:
hostConfiguration - The host configuration to use. If null, the host configuration returned by getHostConfiguration() will be used.
method - the HTTP method to execute.
Returns:
the method's response code
Throws:
IOException - If an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - If a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
Since:
2.0

executeMethod

public int executeMethod(HostConfiguration hostconfig,
                         HttpMethod method,
                         HttpState state)
                  throws IOException,
                         HttpException
Executes the given HTTP method using the given custom host configuration with the given custom HTTP state.

Parameters:
hostconfig - The host configuration to use. If null, the host configuration returned by getHostConfiguration() will be used.
method - the HTTP method to execute.
state - the HTTP state to use when executing the method. If null, the state returned by getState() will be used.
Returns:
the method's response code
Throws:
IOException - If an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - If a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
Since:
2.0

getHost

public String getHost()
Deprecated. use #getHostConfiguration()

Returns the default host.

Returns:
The default host.

getPort

public int getPort()
Deprecated. use #getHostConfiguration()

Returns the default port.

Returns:
The default port.

getHostConfiguration

public HostConfiguration getHostConfiguration()
Returns the host configuration associated with the HttpClient.

Returns:
host configuration
Since:
2.0

setHostConfiguration

public void setHostConfiguration(HostConfiguration hostConfiguration)
Assigns the host configuration to use with the HttpClient.

Parameters:
hostConfiguration - The host configuration to set
Since:
2.0

getHttpConnectionManager

public HttpConnectionManager getHttpConnectionManager()
Returns the HTTP connection manager associated with the HttpClient.

Returns:
HTTP connection manager
Since:
2.0

setHttpConnectionManager

public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager)
Assigns the HTTP connection manager to use with the HttpClient.

Parameters:
httpConnectionManager - The HTTP connection manager to set
Since:
2.0

getParams

public HttpClientParams getParams()
Returns HTTP protocol parameters associated with this HttpClient.

Since:
3.0
See Also:
HttpClientParams

setParams

public void setParams(HttpClientParams params)
Assigns HTTP protocol parameters for this HttpClient.

Since:
3.0
See Also:
HttpClientParams


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpClientError.html100644 0 0 35365 10661532627 26570 0ustar 0 0 HttpClientError (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpClientError

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Error
          extended by org.apache.commons.httpclient.HttpClientError
All Implemented Interfaces:
Serializable

public class HttpClientError
extends Error

Signals that an error has occurred.

Since:
3.0
Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
Ortwin Gl?ck
See Also:
Serialized Form

Constructor Summary
HttpClientError()
          Creates a new HttpClientError with a null detail message.
HttpClientError(String message)
          Creates a new HttpClientError with the specified detail message.
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

HttpClientError

public HttpClientError()
Creates a new HttpClientError with a null detail message.


HttpClientError

public HttpClientError(String message)
Creates a new HttpClientError with the specified detail message.

Parameters:
message - The error message


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpConnection.html100644 0 0 326327 10661532627 26460 0ustar 0 0 HttpConnection (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpConnection

java.lang.Object
  extended by org.apache.commons.httpclient.HttpConnection

public class HttpConnection
extends Object

An abstraction of an HTTP InputStream and OutputStream pair, together with the relevant attributes.

The following options are set on the socket before getting the input/output streams in the open() method:
Socket Method Sockets Option Configuration
Socket.setTcpNoDelay(boolean) SO_NODELAY HttpConnectionParams.setTcpNoDelay(boolean)
Socket.setSoTimeout(int) SO_TIMEOUT HttpConnectionParams.setSoTimeout(int)
Socket.setSendBufferSize(int) SO_SNDBUF HttpConnectionParams.setSendBufferSize(int)
Socket.setReceiveBufferSize(int) SO_RCVBUF HttpConnectionParams.setReceiveBufferSize(int)

Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
Rod Waldhoff, Sean C. Sullivan, Ortwin Glueck, Jeff Dever, Mike Bowler, Oleg Kalnichevski, Michael Becke, Eric E Johnson, Laura Werner

Field Summary
protected  boolean isOpen
          Whether or not the connection is connected.
 
Constructor Summary
HttpConnection(HostConfiguration hostConfiguration)
          Creates a new HTTP connection for the given host configuration.
HttpConnection(String host, int port)
          Creates a new HTTP connection for the given host and port.
HttpConnection(String host, int port, Protocol protocol)
          Creates a new HTTP connection for the given host and port using the given protocol.
HttpConnection(String proxyHost, int proxyPort, String host, int port)
          Creates a new HTTP connection for the given host and port via the given proxy host and port using the default protocol.
HttpConnection(String proxyHost, int proxyPort, String host, int port, Protocol protocol)
          Creates a new HTTP connection for the given host with the virtual alias and port via the given proxy host and port using the given protocol.
HttpConnection(String proxyHost, int proxyPort, String host, String virtualHost, int port, Protocol protocol)
          Deprecated. use #HttpConnection(String, int, String, int, Protocol)
HttpConnection(String host, String virtualHost, int port, Protocol protocol)
          Creates a new HTTP connection for the given host with the virtual alias and port using given protocol.
 
Method Summary
protected  void assertNotOpen()
          Throws an IllegalStateException if the connection is already open.
protected  void assertOpen()
          Throws an IllegalStateException if the connection is not open.
 void close()
          Closes the socket and streams.
 boolean closeIfStale()
          Closes the connection if stale.
protected  void closeSocketAndStreams()
          Closes everything out.
 void flushRequestOutputStream()
          Flushes the output request stream.
 String getHost()
          Returns the host.
 HttpConnectionManager getHttpConnectionManager()
          Returns the httpConnectionManager.
 InputStream getLastResponseInputStream()
          Returns the stream used to read the last response's body.
 InetAddress getLocalAddress()
          Return the local address used when creating the connection.
 HttpConnectionParams getParams()
          Returns HTTP protocol parameters associated with this method.
 int getPort()
          Returns the port of the host.
 Protocol getProtocol()
          Returns the protocol used to establish the connection.
 String getProxyHost()
          Returns the proxy host.
 int getProxyPort()
          Returns the port of the proxy host.
 OutputStream getRequestOutputStream()
          Returns an OutputStream suitable for writing the request.
 InputStream getResponseInputStream()
          Return a InputStream suitable for reading the response.
 int getSendBufferSize()
          Gets the socket's sendBufferSize.
protected  Socket getSocket()
          Returns the connection socket.
 int getSoTimeout()
          Deprecated. Use HttpConnectionParams.getSoTimeout(), getParams().
 String getVirtualHost()
          Deprecated. no longer applicable
protected  boolean isLocked()
          Tests if the connection is locked.
 boolean isOpen()
          Tests if the connection is open.
 boolean isProxied()
          Returns true if the connection is established via a proxy, false otherwise.
 boolean isResponseAvailable()
          Tests if input data avaialble.
 boolean isResponseAvailable(int timeout)
          Tests if input data becomes available within the given period time in milliseconds.
 boolean isSecure()
          Returns true if the connection is established over a secure protocol.
protected  boolean isStale()
          Determines whether this connection is "stale", which is to say that either it is no longer open, or an attempt to read the connection would fail.
 boolean isStaleCheckingEnabled()
          Deprecated. Use HttpConnectionParams.isStaleCheckingEnabled(), getParams().
 boolean isTransparent()
          Indicates if the connection is completely transparent from end to end.
 void open()
          Establishes a connection to the specified host and port (via a proxy if specified).
 void print(String data)
          Deprecated. Use print(String, String) Writes the specified String (as bytes) to the output stream.
 void print(String data, String charset)
          Writes the specified String (as bytes) to the output stream.
 void printLine()
          Writes "\r\n".getBytes() to the output stream.
 void printLine(String data)
          Deprecated. Use printLine(String, String) Writes the specified String (as bytes), followed by "\r\n".getBytes() to the output stream.
 void printLine(String data, String charset)
          Writes the specified String (as bytes), followed by "\r\n".getBytes() to the output stream.
 String readLine()
          Deprecated. use #readLine(String)
 String readLine(String charset)
          Reads up to "\n" from the (unchunked) input stream.
 void releaseConnection()
          Releases the connection.
 void setConnectionTimeout(int timeout)
          Deprecated. Use HttpConnectionParams.setConnectionTimeout(int), getParams().
 void setHost(String host)
          Sets the host to connect to.
 void setHttpConnectionManager(HttpConnectionManager httpConnectionManager)
          Sets the httpConnectionManager.
 void setLastResponseInputStream(InputStream inStream)
          Set the state to keep track of the last response for the last request.
 void setLocalAddress(InetAddress localAddress)
          Set the local address used when creating the connection.
protected  void setLocked(boolean locked)
          Locks or unlocks the connection.
 void setParams(HttpConnectionParams params)
          Assigns HTTP protocol parameters for this method.
 void setPort(int port)
          Sets the port to connect to.
 void setProtocol(Protocol protocol)
          Sets the protocol used to establish the connection
 void setProxyHost(String host)
          Sets the host to proxy through.
 void setProxyPort(int port)
          Sets the port of the host to proxy through.
 void setSendBufferSize(int sendBufferSize)
          Deprecated. Use HttpConnectionParams.setSendBufferSize(int), getParams().
 void setSocketTimeout(int timeout)
          Sets SO_TIMEOUT value directly on the underlying socket.
 void setSoTimeout(int timeout)
          Deprecated. Use HttpConnectionParams.setSoTimeout(int), getParams().
 void setStaleCheckingEnabled(boolean staleCheckEnabled)
          Deprecated. Use HttpConnectionParams.setStaleCheckingEnabled(boolean), getParams().
 void setVirtualHost(String host)
          Deprecated. no longer applicable
 void shutdownOutput()
          Deprecated. unused
 void tunnelCreated()
          Instructs the proxy to establish a secure tunnel to the host.
 void write(byte[] data)
          Writes the specified bytes to the output stream.
 void write(byte[] data, int offset, int length)
          Writes length bytes in data starting at offset to the output stream.
 void writeLine()
          Writes "\r\n".getBytes() to the output stream.
 void writeLine(byte[] data)
          Writes the specified bytes, followed by "\r\n".getBytes() to the output stream.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

isOpen

protected boolean isOpen
Whether or not the connection is connected.

Constructor Detail

HttpConnection

public HttpConnection(String host,
                      int port)
Creates a new HTTP connection for the given host and port.

Parameters:
host - the host to connect to
port - the port to connect to

HttpConnection

public HttpConnection(String host,
                      int port,
                      Protocol protocol)
Creates a new HTTP connection for the given host and port using the given protocol.

Parameters:
host - the host to connect to
port - the port to connect to
protocol - the protocol to use

HttpConnection

public HttpConnection(String host,
                      String virtualHost,
                      int port,
                      Protocol protocol)
Creates a new HTTP connection for the given host with the virtual alias and port using given protocol.

Parameters:
host - the host to connect to
virtualHost - the virtual host requests will be sent to
port - the port to connect to
protocol - the protocol to use

HttpConnection

public HttpConnection(String proxyHost,
                      int proxyPort,
                      String host,
                      int port)
Creates a new HTTP connection for the given host and port via the given proxy host and port using the default protocol.

Parameters:
proxyHost - the host to proxy via
proxyPort - the port to proxy via
host - the host to connect to
port - the port to connect to

HttpConnection

public HttpConnection(HostConfiguration hostConfiguration)
Creates a new HTTP connection for the given host configuration.

Parameters:
hostConfiguration - the host/proxy/protocol to use

HttpConnection

public HttpConnection(String proxyHost,
                      int proxyPort,
                      String host,
                      String virtualHost,
                      int port,
                      Protocol protocol)
Deprecated. use #HttpConnection(String, int, String, int, Protocol)

Creates a new HTTP connection for the given host with the virtual alias and port via the given proxy host and port using the given protocol.

Parameters:
proxyHost - the host to proxy via
proxyPort - the port to proxy via
host - the host to connect to. Parameter value must be non-null.
virtualHost - No longer applicable.
port - the port to connect to
protocol - The protocol to use. Parameter value must be non-null.

HttpConnection

public HttpConnection(String proxyHost,
                      int proxyPort,
                      String host,
                      int port,
                      Protocol protocol)
Creates a new HTTP connection for the given host with the virtual alias and port via the given proxy host and port using the given protocol.

Parameters:
proxyHost - the host to proxy via
proxyPort - the port to proxy via
host - the host to connect to. Parameter value must be non-null.
port - the port to connect to
protocol - The protocol to use. Parameter value must be non-null.
Method Detail

getSocket

protected Socket getSocket()
Returns the connection socket.

Returns:
the socket.
Since:
3.0

getHost

public String getHost()
Returns the host.

Returns:
the host.

setHost

public void setHost(String host)
             throws IllegalStateException
Sets the host to connect to.

Parameters:
host - the host to connect to. Parameter value must be non-null.
Throws:
IllegalStateException - if the connection is already open

getVirtualHost

public String getVirtualHost()
Deprecated. no longer applicable

Returns the target virtual host.

Returns:
the virtual host.

setVirtualHost

public void setVirtualHost(String host)
                    throws IllegalStateException
Deprecated. no longer applicable

Sets the virtual host to target.

Parameters:
host - the virtual host name that should be used instead of physical host name when sending HTTP requests. Virtual host name can be set to null if virtual host name is not to be used
Throws:
IllegalStateException - if the connection is already open

getPort

public int getPort()
Returns the port of the host. If the port is -1 (or less than 0) the default port for the current protocol is returned.

Returns:
the port.

setPort

public void setPort(int port)
             throws IllegalStateException
Sets the port to connect to.

Parameters:
port - the port to connect to
Throws:
IllegalStateException - if the connection is already open

getProxyHost

public String getProxyHost()
Returns the proxy host.

Returns:
the proxy host.

setProxyHost

public void setProxyHost(String host)
                  throws IllegalStateException
Sets the host to proxy through.

Parameters:
host - the host to proxy through.
Throws:
IllegalStateException - if the connection is already open

getProxyPort

public int getProxyPort()
Returns the port of the proxy host.

Returns:
the proxy port.

setProxyPort

public void setProxyPort(int port)
                  throws IllegalStateException
Sets the port of the host to proxy through.

Parameters:
port - the port of the host to proxy through.
Throws:
IllegalStateException - if the connection is already open

isSecure

public boolean isSecure()
Returns true if the connection is established over a secure protocol.

Returns:
true if connected over a secure protocol.

getProtocol

public Protocol getProtocol()
Returns the protocol used to establish the connection.

Returns:
The protocol

setProtocol

public void setProtocol(Protocol protocol)
Sets the protocol used to establish the connection

Parameters:
protocol - The protocol to use.
Throws:
IllegalStateException - if the connection is already open

getLocalAddress

public InetAddress getLocalAddress()
Return the local address used when creating the connection. If null, the default address is used.

Returns:
InetAddress the local address to be used when creating Sockets

setLocalAddress

public void setLocalAddress(InetAddress localAddress)
Set the local address used when creating the connection. If unset or null, the default address is used.

Parameters:
localAddress - the local address to use

isOpen

public boolean isOpen()
Tests if the connection is open.

Returns:
true if the connection is open

closeIfStale

public boolean closeIfStale()
                     throws IOException
Closes the connection if stale.

Returns:
true if the connection was stale and therefore closed, false otherwise.
Throws:
IOException
Since:
3.0
See Also:
isStale()

isStaleCheckingEnabled

public boolean isStaleCheckingEnabled()
Deprecated. Use HttpConnectionParams.isStaleCheckingEnabled(), getParams().

Tests if stale checking is enabled.

Returns:
true if enabled
See Also:
isStale()

setStaleCheckingEnabled

public void setStaleCheckingEnabled(boolean staleCheckEnabled)
Deprecated. Use HttpConnectionParams.setStaleCheckingEnabled(boolean), getParams().

Sets whether or not isStale() will be called when testing if this connection is open.

Setting this flag to false will increase performance when reusing connections, but it will also make them less reliable. Stale checking ensures that connections are viable before they are used. When set to false some method executions will result in IOExceptions and they will have to be retried.

Parameters:
staleCheckEnabled - true to enable isStale()
See Also:
isStale(), isOpen()

isStale

protected boolean isStale()
                   throws IOException
Determines whether this connection is "stale", which is to say that either it is no longer open, or an attempt to read the connection would fail.

Unfortunately, due to the limitations of the JREs prior to 1.4, it is not possible to test a connection to see if both the read and write channels are open - except by reading and writing. This leads to a difficulty when some connections leave the "write" channel open, but close the read channel and ignore the request. This function attempts to ameliorate that problem by doing a test read, assuming that the caller will be doing a write followed by a read, rather than the other way around.

To avoid side-effects, the underlying connection is wrapped by a BufferedInputStream, so although data might be read, what is visible to clients of the connection will not change with this call.

Returns:
true if the connection is already closed, or a read would fail.
Throws:
IOException - if the stale connection test is interrupted.

isProxied

public boolean isProxied()
Returns true if the connection is established via a proxy, false otherwise.

Returns:
true if a proxy is used to establish the connection, false otherwise.

setLastResponseInputStream

public void setLastResponseInputStream(InputStream inStream)
Set the state to keep track of the last response for the last request.

The connection managers use this to ensure that previous requests are properly closed before a new request is attempted. That way, a GET request need not be read in its entirety before a new request is issued. Instead, this stream can be closed as appropriate.

Parameters:
inStream - The stream associated with an HttpMethod.

getLastResponseInputStream

public InputStream getLastResponseInputStream()
Returns the stream used to read the last response's body.

Clients will generally not need to call this function unless using HttpConnection directly, instead of calling HttpClient.executeMethod(org.apache.commons.httpclient.HttpMethod). For those clients, call this function, and if it returns a non-null stream, close the stream before attempting to execute a method. Note that calling "close" on the stream returned by this function may close the connection if the previous response contained a "Connection: close" header.

Returns:
An InputStream corresponding to the body of the last response.

getParams

public HttpConnectionParams getParams()
Returns HTTP protocol parameters associated with this method.

Returns:
HTTP parameters.
Since:
3.0

setParams

public void setParams(HttpConnectionParams params)
Assigns HTTP protocol parameters for this method.

Since:
3.0
See Also:
HttpConnectionParams

setSoTimeout

public void setSoTimeout(int timeout)
                  throws SocketException,
                         IllegalStateException
Deprecated. Use HttpConnectionParams.setSoTimeout(int), getParams().

Set the Socket's timeout, via Socket.setSoTimeout(int). If the connection is already open, the SO_TIMEOUT is changed. If no connection is open, then subsequent connections will use the timeout value.

Note: This is not a connection timeout but a timeout on network traffic!

Parameters:
timeout - the timeout value
Throws:
SocketException - - if there is an error in the underlying protocol, such as a TCP error.
IllegalStateException

setSocketTimeout

public void setSocketTimeout(int timeout)
                      throws SocketException,
                             IllegalStateException
Sets SO_TIMEOUT value directly on the underlying socket. This method does not change the default read timeout value set via HttpConnectionParams.

Parameters:
timeout - the timeout value
Throws:
SocketException - - if there is an error in the underlying protocol, such as a TCP error.
IllegalStateException - if not connected
Since:
3.0

getSoTimeout

public int getSoTimeout()
                 throws SocketException
Deprecated. Use HttpConnectionParams.getSoTimeout(), getParams().

Returns the Socket's timeout, via Socket.getSoTimeout(), if the connection is already open. If no connection is open, return the value subsequent connection will use.

Note: This is not a connection timeout but a timeout on network traffic!

Returns:
the timeout value
Throws:
SocketException

setConnectionTimeout

public void setConnectionTimeout(int timeout)
Deprecated. Use HttpConnectionParams.setConnectionTimeout(int), getParams().

Sets the connection timeout. This is the maximum time that may be spent until a connection is established. The connection will fail after this amount of time.

Parameters:
timeout - The timeout in milliseconds. 0 means timeout is not used.

open

public void open()
          throws IOException
Establishes a connection to the specified host and port (via a proxy if specified). The underlying socket is created from the ProtocolSocketFactory.

Throws:
IOException - if an attempt to establish the connection results in an I/O error.

tunnelCreated

public void tunnelCreated()
                   throws IllegalStateException,
                          IOException
Instructs the proxy to establish a secure tunnel to the host. The socket will be switched to the secure socket. Subsequent communication is done via the secure socket. The method can only be called once on a proxied secure connection.

Throws:
IllegalStateException - if connection is not secure and proxied or if the socket is already secure.
IOException - if an attempt to establish the secure tunnel results in an I/O error.

isTransparent

public boolean isTransparent()
Indicates if the connection is completely transparent from end to end.

Returns:
true if conncetion is not proxied or tunneled through a transparent proxy; false otherwise.

flushRequestOutputStream

public void flushRequestOutputStream()
                              throws IOException
Flushes the output request stream. This method should be called to ensure that data written to the request OutputStream is sent to the server.

Throws:
IOException - if an I/O problem occurs

getRequestOutputStream

public OutputStream getRequestOutputStream()
                                    throws IOException,
                                           IllegalStateException
Returns an OutputStream suitable for writing the request.

Returns:
a stream to write the request to
Throws:
IllegalStateException - if the connection is not open
IOException - if an I/O problem occurs

getResponseInputStream

public InputStream getResponseInputStream()
                                   throws IOException,
                                          IllegalStateException
Return a InputStream suitable for reading the response.

Returns:
InputStream The response input stream.
Throws:
IOException - If an IO problem occurs
IllegalStateException - If the connection isn't open.

isResponseAvailable

public boolean isResponseAvailable()
                            throws IOException
Tests if input data avaialble. This method returns immediately and does not perform any read operations on the input socket

Returns:
boolean true if input data is available, false otherwise.
Throws:
IOException - If an IO problem occurs
IllegalStateException - If the connection isn't open.

isResponseAvailable

public boolean isResponseAvailable(int timeout)
                            throws IOException
Tests if input data becomes available within the given period time in milliseconds.

Parameters:
timeout - The number milliseconds to wait for input data to become available
Returns:
boolean true if input data is availble, false otherwise.
Throws:
IOException - If an IO problem occurs
IllegalStateException - If the connection isn't open.

write

public void write(byte[] data)
           throws IOException,
                  IllegalStateException
Writes the specified bytes to the output stream.

Parameters:
data - the data to be written
Throws:
IllegalStateException - if not connected
IOException - if an I/O problem occurs
See Also:
write(byte[],int,int)

write

public void write(byte[] data,
                  int offset,
                  int length)
           throws IOException,
                  IllegalStateException
Writes length bytes in data starting at offset to the output stream. The general contract for write(b, off, len) is that some of the bytes in the array b are written to the output stream in order; element b[off] is the first byte written and b[off+len-1] is the last byte written by this operation.

Parameters:
data - array containing the data to be written.
offset - the start offset in the data.
length - the number of bytes to write.
Throws:
IllegalStateException - if not connected
IOException - if an I/O problem occurs

writeLine

public void writeLine(byte[] data)
               throws IOException,
                      IllegalStateException
Writes the specified bytes, followed by "\r\n".getBytes() to the output stream.

Parameters:
data - the bytes to be written
Throws:
IllegalStateException - if the connection is not open
IOException - if an I/O problem occurs

writeLine

public void writeLine()
               throws IOException,
                      IllegalStateException
Writes "\r\n".getBytes() to the output stream.

Throws:
IllegalStateException - if the connection is not open
IOException - if an I/O problem occurs

print

public void print(String data)
           throws IOException,
                  IllegalStateException
Deprecated. Use print(String, String) Writes the specified String (as bytes) to the output stream.

Parameters:
data - the string to be written
Throws:
IllegalStateException - if the connection is not open
IOException - if an I/O problem occurs

print

public void print(String data,
                  String charset)
           throws IOException,
                  IllegalStateException
Writes the specified String (as bytes) to the output stream.

Parameters:
data - the string to be written
charset - the charset to use for writing the data
Throws:
IllegalStateException - if the connection is not open
IOException - if an I/O problem occurs
Since:
3.0

printLine

public void printLine(String data)
               throws IOException,
                      IllegalStateException
Deprecated. Use printLine(String, String) Writes the specified String (as bytes), followed by "\r\n".getBytes() to the output stream.

Parameters:
data - the data to be written
Throws:
IllegalStateException - if the connection is not open
IOException - if an I/O problem occurs

printLine

public void printLine(String data,
                      String charset)
               throws IOException,
                      IllegalStateException
Writes the specified String (as bytes), followed by "\r\n".getBytes() to the output stream.

Parameters:
data - the data to be written
charset - the charset to use for writing the data
Throws:
IllegalStateException - if the connection is not open
IOException - if an I/O problem occurs
Since:
3.0

printLine

public void printLine()
               throws IOException,
                      IllegalStateException
Writes "\r\n".getBytes() to the output stream.

Throws:
IllegalStateException - if the connection is not open
IOException - if an I/O problem occurs

readLine

public String readLine()
                throws IOException,
                       IllegalStateException
Deprecated. use #readLine(String)

Reads up to "\n" from the (unchunked) input stream. If the stream ends before the line terminator is found, the last part of the string will still be returned.

Returns:
a line from the response
Throws:
IllegalStateException - if the connection is not open
IOException - if an I/O problem occurs

readLine

public String readLine(String charset)
                throws IOException,
                       IllegalStateException
Reads up to "\n" from the (unchunked) input stream. If the stream ends before the line terminator is found, the last part of the string will still be returned.

Parameters:
charset - the charset to use for reading the data
Returns:
a line from the response
Throws:
IllegalStateException - if the connection is not open
IOException - if an I/O problem occurs
Since:
3.0

shutdownOutput

public void shutdownOutput()
Deprecated. unused

Attempts to shutdown the Socket's output, via Socket.shutdownOutput() when running on JVM 1.3 or higher.


close

public void close()
Closes the socket and streams.


getHttpConnectionManager

public HttpConnectionManager getHttpConnectionManager()
Returns the httpConnectionManager.

Returns:
HttpConnectionManager

setHttpConnectionManager

public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager)
Sets the httpConnectionManager.

Parameters:
httpConnectionManager - The httpConnectionManager to set

releaseConnection

public void releaseConnection()
Releases the connection. If the connection is locked or does not have a connection manager associated with it, this method has no effect. Note that it is completely safe to call this method multiple times.


isLocked

protected boolean isLocked()
Tests if the connection is locked. Locked connections cannot be released. An attempt to release a locked connection will have no effect.

Returns:
true if the connection is locked, false otherwise.
Since:
3.0

setLocked

protected void setLocked(boolean locked)
Locks or unlocks the connection. Locked connections cannot be released. An attempt to release a locked connection will have no effect.

Parameters:
locked - true to lock the connection, false to unlock the connection.
Since:
3.0

closeSocketAndStreams

protected void closeSocketAndStreams()
Closes everything out.


assertNotOpen

protected void assertNotOpen()
                      throws IllegalStateException
Throws an IllegalStateException if the connection is already open.

Throws:
IllegalStateException - if connected

assertOpen

protected void assertOpen()
                   throws IllegalStateException
Throws an IllegalStateException if the connection is not open.

Throws:
IllegalStateException - if not connected

getSendBufferSize

public int getSendBufferSize()
                      throws SocketException
Gets the socket's sendBufferSize.

Returns:
the size of the buffer for the socket OutputStream, -1 if the value has not been set and the socket has not been opened
Throws:
SocketException - if an error occurs while getting the socket value
See Also:
Socket.getSendBufferSize()

setSendBufferSize

public void setSendBufferSize(int sendBufferSize)
                       throws SocketException
Deprecated. Use HttpConnectionParams.setSendBufferSize(int), getParams().

Sets the socket's sendBufferSize.

Parameters:
sendBufferSize - the size to set for the socket OutputStream
Throws:
SocketException - if an error occurs while setting the socket value
See Also:
Socket.setSendBufferSize(int)


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpConnectionManager.html100644 0 0 52202 10661532627 27717 0ustar 0 0 HttpConnectionManager (HttpClient 3.1 API)

org.apache.commons.httpclient
Interface HttpConnectionManager

All Known Implementing Classes:
MultiThreadedHttpConnectionManager, SimpleHttpConnectionManager

public interface HttpConnectionManager

An interface for classes that manage HttpConnections.

Since:
2.0
Author:
Michael Becke, Mike Bowler, Oleg Kalnichevski
See Also:
HttpConnection, HttpClient.HttpClient(HttpConnectionManager)

Method Summary
 void closeIdleConnections(long idleTimeout)
          Closes connections that have been idle for at least the given amount of time.
 HttpConnection getConnection(HostConfiguration hostConfiguration)
          Gets an HttpConnection for a given host configuration.
 HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout)
          Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
 HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
          Gets an HttpConnection for a given host configuration.
 HttpConnectionManagerParams getParams()
          Returns parameters associated with this connection manager.
 void releaseConnection(HttpConnection conn)
          Releases the given HttpConnection for use by other requests.
 void setParams(HttpConnectionManagerParams params)
          Assigns parameters for this connection manager.
 

Method Detail

getConnection

HttpConnection getConnection(HostConfiguration hostConfiguration)
Gets an HttpConnection for a given host configuration. If a connection is not available this method will block until one is. The connection manager should be registered with any HttpConnection that is created.

Parameters:
hostConfiguration - the host configuration to use to configure the connection
Returns:
an HttpConnection for the given configuration
See Also:
HttpConnection.setHttpConnectionManager(HttpConnectionManager)

getConnection

HttpConnection getConnection(HostConfiguration hostConfiguration,
                             long timeout)
                             throws HttpException
Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)

Gets an HttpConnection for a given host configuration. If a connection is not available, this method will block for at most the specified number of milliseconds or until a connection becomes available. The connection manager should be registered with any HttpConnection that is created.

Parameters:
hostConfiguration - the host configuration to use to configure the connection
timeout - - the time (in milliseconds) to wait for a connection to become available, 0 to specify an infinite timeout
Returns:
an HttpConnection for the given configuraiton
Throws:
HttpException - if no connection becomes available before the timeout expires
See Also:
HttpConnection.setHttpConnectionManager(HttpConnectionManager)

getConnectionWithTimeout

HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration,
                                        long timeout)
                                        throws ConnectionPoolTimeoutException
Gets an HttpConnection for a given host configuration. If a connection is not available, this method will block for at most the specified number of milliseconds or until a connection becomes available. The connection manager should be registered with any HttpConnection that is created.

Parameters:
hostConfiguration - the host configuration to use to configure the connection
timeout - - the time (in milliseconds) to wait for a connection to become available, 0 to specify an infinite timeout
Returns:
an HttpConnection for the given configuraiton
Throws:
ConnectionPoolTimeoutException - if no connection becomes available before the timeout expires
Since:
3.0
See Also:
HttpConnection.setHttpConnectionManager(HttpConnectionManager)

releaseConnection

void releaseConnection(HttpConnection conn)
Releases the given HttpConnection for use by other requests.

Parameters:
conn - - The HttpConnection to make available.

closeIdleConnections

void closeIdleConnections(long idleTimeout)
Closes connections that have been idle for at least the given amount of time. Only connections that are currently owned, not checked out, are subject to idle timeouts.

Parameters:
idleTimeout - the minimum idle time, in milliseconds, for connections to be closed
Since:
3.0

getParams

HttpConnectionManagerParams getParams()
Returns parameters associated with this connection manager.

Since:
3.0
See Also:
HttpConnectionManagerParams

setParams

void setParams(HttpConnectionManagerParams params)
Assigns parameters for this connection manager.

Since:
3.0
See Also:
HttpConnectionManagerParams


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpConstants.html100644 0 0 77733 10661532627 26321 0ustar 0 0 HttpConstants (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpConstants

java.lang.Object
  extended by org.apache.commons.httpclient.HttpConstants

Deprecated. use EncodingUtil class

public class HttpConstants
extends Object

HTTP content conversion routines.

Author:
Oleg Kalnichevski, Mike Bowler

Field Summary
static String DEFAULT_CONTENT_CHARSET
          Deprecated. Default content encoding chatset
static String HTTP_ELEMENT_CHARSET
          Deprecated. Character set used to encode HTTP protocol elements
 
Constructor Summary
HttpConstants()
          Deprecated.  
 
Method Summary
static byte[] getAsciiBytes(String data)
          Deprecated. Converts the specified string to byte array of ASCII characters.
static String getAsciiString(byte[] data)
          Deprecated. Converts the byte array of ASCII characters to a string.
static String getAsciiString(byte[] data, int offset, int length)
          Deprecated. Converts the byte array of ASCII characters to a string.
static byte[] getBytes(String data)
          Deprecated. Converts the specified string to a byte array of HTTP element characters.
static byte[] getContentBytes(String data)
          Deprecated. Converts the specified string to a byte array of HTTP content characters using default HTTP content encoding (ISO-8859-1) This method is to be used when encoding content of HTTP request/response
static byte[] getContentBytes(String data, String charset)
          Deprecated. Converts the specified string to a byte array of HTTP content charachetrs This method is to be used when encoding content of HTTP request/response If the specified charset is not supported, default HTTP content encoding (ISO-8859-1) is applied
static String getContentString(byte[] data)
          Deprecated. Converts the byte array of HTTP content characters to a string using default HTTP content encoding (ISO-8859-1) This method is to be used when decoding content of HTTP request/response
static String getContentString(byte[] data, int offset, int length)
          Deprecated. Converts the byte array of HTTP content characters to a string using default HTTP content encoding (ISO-8859-1) This method is to be used when decoding content of HTTP request/response
static String getContentString(byte[] data, int offset, int length, String charset)
          Deprecated. Converts the byte array of HTTP content characters to a string This method is to be used when decoding content of HTTP request/response If the specified charset is not supported, default HTTP content encoding (ISO-8859-1) is applied
static String getContentString(byte[] data, String charset)
          Deprecated. Converts the byte array of HTTP content characters to a string This method is to be used when decoding content of HTTP request/response If the specified charset is not supported, default HTTP content encoding (ISO-8859-1) is applied
static String getString(byte[] data)
          Deprecated. Converts the byte array of HTTP element characters to a string This method is to be used when decoding content of HTTP elements (such as response headers)
static String getString(byte[] data, int offset, int length)
          Deprecated. Converts the byte array of HTTP element characters to a string This method is to be used when decoding content of HTTP elements (such as response headers)
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

HTTP_ELEMENT_CHARSET

public static final String HTTP_ELEMENT_CHARSET
Deprecated. 
Character set used to encode HTTP protocol elements

See Also:
Constant Field Values

DEFAULT_CONTENT_CHARSET

public static final String DEFAULT_CONTENT_CHARSET
Deprecated. 
Default content encoding chatset

See Also:
Constant Field Values
Constructor Detail

HttpConstants

public HttpConstants()
Deprecated. 
Method Detail

getBytes

public static byte[] getBytes(String data)
Deprecated. 
Converts the specified string to a byte array of HTTP element characters. This method is to be used when encoding content of HTTP elements (such as request headers)

Parameters:
data - the string to be encoded
Returns:
The resulting byte array.

getString

public static String getString(byte[] data,
                               int offset,
                               int length)
Deprecated. 
Converts the byte array of HTTP element characters to a string This method is to be used when decoding content of HTTP elements (such as response headers)

Parameters:
data - the byte array to be encoded
offset - the index of the first byte to encode
length - the number of bytes to encode
Returns:
The resulting string.

getString

public static String getString(byte[] data)
Deprecated. 
Converts the byte array of HTTP element characters to a string This method is to be used when decoding content of HTTP elements (such as response headers)

Parameters:
data - the byte array to be encoded
Returns:
The resulting string.

getContentBytes

public static byte[] getContentBytes(String data,
                                     String charset)
Deprecated. 
Converts the specified string to a byte array of HTTP content charachetrs This method is to be used when encoding content of HTTP request/response If the specified charset is not supported, default HTTP content encoding (ISO-8859-1) is applied

Parameters:
data - the string to be encoded
charset - the desired character encoding
Returns:
The resulting byte array.

getContentString

public static String getContentString(byte[] data,
                                      int offset,
                                      int length,
                                      String charset)
Deprecated. 
Converts the byte array of HTTP content characters to a string This method is to be used when decoding content of HTTP request/response If the specified charset is not supported, default HTTP content encoding (ISO-8859-1) is applied

Parameters:
data - the byte array to be encoded
offset - the index of the first byte to encode
length - the number of bytes to encode
charset - the desired character encoding
Returns:
The result of the conversion.

getContentString

public static String getContentString(byte[] data,
                                      String charset)
Deprecated. 
Converts the byte array of HTTP content characters to a string This method is to be used when decoding content of HTTP request/response If the specified charset is not supported, default HTTP content encoding (ISO-8859-1) is applied

Parameters:
data - the byte array to be encoded
charset - the desired character encoding
Returns:
The result of the conversion.

getContentBytes

public static byte[] getContentBytes(String data)
Deprecated. 
Converts the specified string to a byte array of HTTP content characters using default HTTP content encoding (ISO-8859-1) This method is to be used when encoding content of HTTP request/response

Parameters:
data - the string to be encoded
Returns:
The byte array as above.

getContentString

public static String getContentString(byte[] data,
                                      int offset,
                                      int length)
Deprecated. 
Converts the byte array of HTTP content characters to a string using default HTTP content encoding (ISO-8859-1) This method is to be used when decoding content of HTTP request/response

Parameters:
data - the byte array to be encoded
offset - the index of the first byte to encode
length - the number of bytes to encode
Returns:
The string representation of the byte array.

getContentString

public static String getContentString(byte[] data)
Deprecated. 
Converts the byte array of HTTP content characters to a string using default HTTP content encoding (ISO-8859-1) This method is to be used when decoding content of HTTP request/response

Parameters:
data - the byte array to be encoded
Returns:
The string representation of the byte array.

getAsciiBytes

public static byte[] getAsciiBytes(String data)
Deprecated. 
Converts the specified string to byte array of ASCII characters.

Parameters:
data - the string to be encoded
Returns:
The string as a byte array.

getAsciiString

public static String getAsciiString(byte[] data,
                                    int offset,
                                    int length)
Deprecated. 
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)

Parameters:
data - the byte array to be encoded
offset - the index of the first byte to encode
length - the number of bytes to encode
Returns:
The string representation of the byte array

getAsciiString

public static String getAsciiString(byte[] data)
Deprecated. 
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)

Parameters:
data - the byte array to be encoded
Returns:
The string representation of the byte array


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpContentTooLargeException.html100644 0 0 40546 10661532627 31263 0ustar 0 0 HttpContentTooLargeException (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpContentTooLargeException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.HttpContentTooLargeException
All Implemented Interfaces:
Serializable

public class HttpContentTooLargeException
extends HttpException

Signals that the response content was larger than anticipated.

Author:
Ortwin Gl?ck
See Also:
Serialized Form

Constructor Summary
HttpContentTooLargeException(String message, int maxlen)
           
 
Method Summary
 int getMaxLength()
           
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

HttpContentTooLargeException

public HttpContentTooLargeException(String message,
                                    int maxlen)
Method Detail

getMaxLength

public int getMaxLength()
Returns:
the maximum anticipated content length in bytes.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpException.html100644 0 0 65056 10661532627 26276 0ustar 0 0 HttpException (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
HttpContentTooLargeException, HttpRecoverableException, ProtocolException, URIException

public class HttpException
extends IOException

Signals that an HTTP or HttpClient exception has occurred.

Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
Laura Werner
See Also:
Serialized Form

Constructor Summary
HttpException()
          Creates a new HttpException with a null detail message.
HttpException(String message)
          Creates a new HttpException with the specified detail message.
HttpException(String message, Throwable cause)
          Creates a new HttpException with the specified detail message and cause.
 
Method Summary
 Throwable getCause()
          Return the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable.
 String getReason()
          Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.
 int getReasonCode()
          Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.
 void printStackTrace()
          Print this HttpException and its stack trace to the standard error stream.
 void printStackTrace(PrintStream s)
          Print this HttpException and its stack trace to the specified print stream.
 void printStackTrace(PrintWriter s)
          Print this HttpException and its stack trace to the specified print writer.
 void setReason(String reason)
          Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.
 void setReasonCode(int code)
          Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

HttpException

public HttpException()
Creates a new HttpException with a null detail message.


HttpException

public HttpException(String message)
Creates a new HttpException with the specified detail message.

Parameters:
message - the exception detail message

HttpException

public HttpException(String message,
                     Throwable cause)
Creates a new HttpException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable
Since:
3.0
Method Detail

getCause

public Throwable getCause()
Return the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable.

Overrides:
getCause in class Throwable
Returns:
the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable
Since:
3.0

printStackTrace

public void printStackTrace()
Print this HttpException and its stack trace to the standard error stream.

Overrides:
printStackTrace in class Throwable
Since:
3.0

printStackTrace

public void printStackTrace(PrintStream s)
Print this HttpException and its stack trace to the specified print stream.

Overrides:
printStackTrace in class Throwable
Parameters:
s - the PrintStream to which the exception and its stack trace should be written
Since:
3.0

printStackTrace

public void printStackTrace(PrintWriter s)
Print this HttpException and its stack trace to the specified print writer.

Overrides:
printStackTrace in class Throwable
Parameters:
s - the PrintWriter to which the exception and its stack trace should be written
Since:
3.0

setReason

public void setReason(String reason)
Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.

Sets the text description of the reason for an exception.

Parameters:
reason - The reason for the exception.

getReason

public String getReason()
Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.

Get the text description of the reason for an exception.


setReasonCode

public void setReasonCode(int code)
Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.

Sets the status code description of the reason for an exception.

Parameters:
code - The reason for the exception. This is intended to be an HTTP status code.

getReasonCode

public int getReasonCode()
Deprecated. HttpClient no longer uses this for itself. It is only provided for compatibility with existing clients, and will be removed in a future release.

Get the status code description of the reason for an exception.



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpHost.html100644 0 0 60247 10661532627 25252 0ustar 0 0 HttpHost (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpHost

java.lang.Object
  extended by org.apache.commons.httpclient.HttpHost
All Implemented Interfaces:
Cloneable
Direct Known Subclasses:
ProxyHost

public class HttpHost
extends Object
implements Cloneable

Holds all of the variables needed to describe an HTTP connection to a host. This includes remote host, port and protocol.

Since:
3.0
Author:
Michael Becke, Mike Bowler, Oleg Kalnichevski, Laura Werner

Constructor Summary
HttpHost(HttpHost httphost)
          Copy constructor for HttpHost
HttpHost(String hostname)
          Constructor for HttpHost.
HttpHost(String hostname, int port)
          Constructor for HttpHost.
HttpHost(String hostname, int port, Protocol protocol)
          Constructor for HttpHost.
HttpHost(URI uri)
          URI constructor for HttpHost.
 
Method Summary
 Object clone()
           
 boolean equals(Object o)
           
 String getHostName()
          Returns the host name (IP or DNS name).
 int getPort()
          Returns the port.
 Protocol getProtocol()
          Returns the protocol.
 int hashCode()
           
 String toString()
           
 String toURI()
          Return the host uri.
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

HttpHost

public HttpHost(String hostname,
                int port,
                Protocol protocol)
Constructor for HttpHost.

Parameters:
hostname - the hostname (IP or DNS name). Can be null.
port - the port. Value -1 can be used to set default protocol port
protocol - the protocol. Value null can be used to set default protocol

HttpHost

public HttpHost(String hostname,
                int port)
Constructor for HttpHost.

Parameters:
hostname - the hostname (IP or DNS name). Can be null.
port - the port. Value -1 can be used to set default protocol port

HttpHost

public HttpHost(String hostname)
Constructor for HttpHost.

Parameters:
hostname - the hostname (IP or DNS name). Can be null.

HttpHost

public HttpHost(URI uri)
         throws URIException
URI constructor for HttpHost.

Parameters:
uri - the URI.
Throws:
URIException

HttpHost

public HttpHost(HttpHost httphost)
Copy constructor for HttpHost

Parameters:
httphost - the HTTP host to copy details from
Method Detail

clone

public Object clone()
             throws CloneNotSupportedException
Overrides:
clone in class Object
Throws:
CloneNotSupportedException
See Also:
Object.clone()

getHostName

public String getHostName()
Returns the host name (IP or DNS name).

Returns:
the host name (IP or DNS name), or null if not set

getPort

public int getPort()
Returns the port.

Returns:
the host port, or -1 if not set

getProtocol

public Protocol getProtocol()
Returns the protocol.

Returns:
The protocol.

toURI

public String toURI()
Return the host uri.

Returns:
The host uri.

toString

public String toString()
Overrides:
toString in class Object
See Also:
Object.toString()

equals

public boolean equals(Object o)
Overrides:
equals in class Object
See Also:
Object.equals(java.lang.Object)

hashCode

public int hashCode()
Overrides:
hashCode in class Object
See Also:
Object.hashCode()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpMethod.html100644 0 0 216326 10661532627 25576 0ustar 0 0 HttpMethod (HttpClient 3.1 API)

org.apache.commons.httpclient
Interface HttpMethod

All Known Implementing Classes:
ConnectMethod, DeleteMethod, EntityEnclosingMethod, ExpectContinueMethod, GetMethod, HeadMethod, HttpMethodBase, MultipartPostMethod, OptionsMethod, PostMethod, PutMethod, TraceMethod

public interface HttpMethod

HttpMethod interface represents a request to be sent via a HTTP connection and a corresponding response.

Since:
1.0
Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
Remy Maucherat, Rod Waldhoff, Jeff Dever, Mike Bowler, Oleg Kalnichevski

Method Summary
 void abort()
          Aborts the execution of the HTTP method.
 void addRequestHeader(Header header)
          Adds the specified request header, not overwriting any previous value.
 void addRequestHeader(String headerName, String headerValue)
          Adds the specified request header, not overwriting any previous value.
 void addResponseFooter(Header footer)
          Add a footer to this method's response.
 int execute(HttpState state, HttpConnection connection)
          Executes this method using the specified HttpConnection and HttpState.
 boolean getDoAuthentication()
          Returns true if the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.), false otherwise
 boolean getFollowRedirects()
          Returns true if the HTTP method should automatically follow HTTP redirects (status code 302, etc.), false otherwise.
 AuthState getHostAuthState()
          Returns the target host authentication state
 HostConfiguration getHostConfiguration()
          Deprecated. no longer applicable
 String getName()
          Obtains the name of the HTTP method as used in the HTTP request line, for example "GET" or "POST".
 HttpMethodParams getParams()
          Returns HTTP protocol parameters associated with this method.
 String getPath()
          Returns the path of the HTTP method.
 AuthState getProxyAuthState()
          Returns the proxy authentication state
 String getQueryString()
          Returns the query string of this HTTP method.
 Header getRequestHeader(String headerName)
          Gets the request header with the given name.
 Header[] getRequestHeaders()
          Returns the current request headers for this HTTP method.
 Header[] getRequestHeaders(String headerName)
          Returns the request headers with the given name.
 byte[] getResponseBody()
          Returns the response body of the HTTP method, if any, as an array of bytes.
 InputStream getResponseBodyAsStream()
          Returns the response body of the HTTP method, if any, as an InputStream.
 String getResponseBodyAsString()
          Returns the response body of the HTTP method, if any, as a String.
 Header getResponseFooter(String footerName)
          Return the specified response footer.
 Header[] getResponseFooters()
          Returns the response footers from the most recent execution of this request.
 Header getResponseHeader(String headerName)
          Returns the specified response header.
 Header[] getResponseHeaders()
          Returns the response headers from the most recent execution of this request.
 Header[] getResponseHeaders(String headerName)
          Returns the response headers with the given name.
 int getStatusCode()
          Returns the status code associated with the latest response.
 StatusLine getStatusLine()
          Returns the Status-Line from the most recent response for this method, or null if the method has not been executed.
 String getStatusText()
          Returns the status text (or "reason phrase") associated with the latest response.
 URI getURI()
          Returns the URI for this method.
 boolean hasBeenUsed()
          Returns true if the HTTP method has been already executed, but not recycled.
 boolean isRequestSent()
          Returns true if the HTTP has been transmitted to the target server in its entirety, false otherwise.
 boolean isStrictMode()
          Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.
 void recycle()
          Deprecated. no longer supported and will be removed in the future version of HttpClient
 void releaseConnection()
          Releases the connection being used by this HTTP method.
 void removeRequestHeader(Header header)
          Removes the given request header.
 void removeRequestHeader(String headerName)
          Removes all request headers with the given name.
 void setDoAuthentication(boolean doAuthentication)
          Sets whether or not the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.)
 void setFollowRedirects(boolean followRedirects)
          Sets whether or not the HTTP method should automatically follow HTTP redirects (status code 302, etc.)
 void setParams(HttpMethodParams params)
          Assigns HTTP protocol parameters for this method.
 void setPath(String path)
          Sets the path of the HTTP method.
 void setQueryString(NameValuePair[] params)
          Sets the query string of this HTTP method.
 void setQueryString(String queryString)
          Sets the query string of the HTTP method.
 void setRequestHeader(Header header)
          Sets the specified request header, overwriting any previous value.
 void setRequestHeader(String headerName, String headerValue)
          Sets the specified request header, overwriting any previous value.
 void setStrictMode(boolean strictMode)
          Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.
 void setURI(URI uri)
          Sets the URI for this method.
 boolean validate()
          Returns true the method is ready to execute, false otherwise.
 

Method Detail

getName

String getName()
Obtains the name of the HTTP method as used in the HTTP request line, for example "GET" or "POST".

Returns:
the name of this method

getHostConfiguration

HostConfiguration getHostConfiguration()
Deprecated. no longer applicable

Gets the host configuration for this method. The configuration specifies the server, port, protocol, and proxy server via which this method will send its HTTP request.

Returns:
the HostConfiguration or null if none is set

setPath

void setPath(String path)
Sets the path of the HTTP method. It is responsibility of the caller to ensure that the path is properly encoded (URL safe).

Parameters:
path - The path of the HTTP method. The path is expected to be URL encoded.

getPath

String getPath()
Returns the path of the HTTP method. Calling this method after the request has been executed will return the actual path, following any redirects automatically handled by this HTTP method.

Returns:
the path of the HTTP method, in URL encoded form

getURI

URI getURI()
           throws URIException
Returns the URI for this method. The URI will be absolute if the host configuration has been set and relative otherwise.

Returns:
the URI for this method
Throws:
URIException - if a URI cannot be constructed

setURI

void setURI(URI uri)
            throws URIException
Sets the URI for this method.

Parameters:
uri - URI to be set
Throws:
URIException - if a URI cannot be set
Since:
3.0

setStrictMode

void setStrictMode(boolean strictMode)
Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.

Defines how strictly the method follows the HTTP protocol specification. (See RFC 2616 and other relevant RFCs.) In the strict mode the method precisely implements the requirements of the specification, whereas in non-strict mode it attempts to mimic the exact behaviour of commonly used HTTP agents, which many HTTP servers expect.

Parameters:
strictMode - true for strict mode, false otherwise
See Also:
isStrictMode()

isStrictMode

boolean isStrictMode()
Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.

Returns the value of the strict mode flag.

Returns:
true if strict mode is enabled, false otherwise
See Also:
setStrictMode(boolean)

setRequestHeader

void setRequestHeader(String headerName,
                      String headerValue)
Sets the specified request header, overwriting any previous value. Note that header-name matching is case insensitive.

Parameters:
headerName - the header's name
headerValue - the header's value
See Also:
setRequestHeader(Header), getRequestHeader(String), removeRequestHeader(String)

setRequestHeader

void setRequestHeader(Header header)
Sets the specified request header, overwriting any previous value. Note that header-name matching is case insensitive.

Parameters:
header - the header to be set
See Also:
setRequestHeader(String,String), getRequestHeader(String), removeRequestHeader(String)

addRequestHeader

void addRequestHeader(String headerName,
                      String headerValue)
Adds the specified request header, not overwriting any previous value. If the same header is added multiple times, perhaps with different values, multiple instances of that header will be sent in the HTTP request. Note that header-name matching is case insensitive.

Parameters:
headerName - the header's name
headerValue - the header's value
See Also:
addRequestHeader(Header), getRequestHeader(String), removeRequestHeader(String)

addRequestHeader

void addRequestHeader(Header header)
Adds the specified request header, not overwriting any previous value. If the same header is added multiple times, perhaps with different values, multiple instances of that header will be sent in the HTTP request. Note that header-name matching is case insensitive.

Parameters:
header - the header
See Also:
addRequestHeader(String,String), getRequestHeader(String), removeRequestHeader(String)

getRequestHeader

Header getRequestHeader(String headerName)
Gets the request header with the given name. If there are multiple headers with the same name, there values will be combined with the ',' separator as specified by RFC2616. Note that header-name matching is case insensitive.

Parameters:
headerName - the header name
Returns:
the header

removeRequestHeader

void removeRequestHeader(String headerName)
Removes all request headers with the given name. Note that header-name matching is case insensitive.

Parameters:
headerName - the header name

removeRequestHeader

void removeRequestHeader(Header header)
Removes the given request header.

Parameters:
header - the header
Since:
3.0

getFollowRedirects

boolean getFollowRedirects()
Returns true if the HTTP method should automatically follow HTTP redirects (status code 302, etc.), false otherwise.

Returns:
true if the method will automatically follow HTTP redirects, false otherwise

setFollowRedirects

void setFollowRedirects(boolean followRedirects)
Sets whether or not the HTTP method should automatically follow HTTP redirects (status code 302, etc.)

Parameters:
followRedirects - true if the method will automatically follow redirects, false otherwise.

setQueryString

void setQueryString(String queryString)
Sets the query string of the HTTP method. It is responsibility of the caller to ensure that the path is properly encoded (URL safe). The string must not include an initial '?' character.

Parameters:
queryString - the query to be used in the request, with no leading '?' character
See Also:
getQueryString(), setQueryString(NameValuePair[])

setQueryString

void setQueryString(NameValuePair[] params)
Sets the query string of this HTTP method. The pairs are encoded as UTF-8 characters. To use a different charset the parameters can be encoded manually using EncodingUtil and set as a single String.

Parameters:
params - An array of NameValuePairs to use as the query string. The name/value pairs will be automatically URL encoded and should not have been encoded previously.
See Also:
getQueryString(), setQueryString(String), EncodingUtil.formUrlEncode(NameValuePair[], String)

getQueryString

String getQueryString()
Returns the query string of this HTTP method.

Returns:
the query string in URL encoded form, without a leading '?'.
See Also:
setQueryString(NameValuePair[]), setQueryString(String)

getRequestHeaders

Header[] getRequestHeaders()
Returns the current request headers for this HTTP method. The returned headers will be in the same order that they were added with addRequestHeader. If there are multiple request headers with the same name (e.g. Cookie), they will be returned as multiple entries in the array.

Returns:
an array containing all of the request headers
See Also:
addRequestHeader(Header), addRequestHeader(String,String)

getRequestHeaders

Header[] getRequestHeaders(String headerName)
Returns the request headers with the given name. Note that header-name matching is case insensitive.

Parameters:
headerName - the name of the headers to be returned.
Returns:
an array of zero or more headers
Since:
3.0

validate

boolean validate()
Returns true the method is ready to execute, false otherwise.

Returns:
true if the method is ready to execute, false otherwise.

getStatusCode

int getStatusCode()
Returns the status code associated with the latest response.

Returns:
The status code from the most recent execution of this method. If the method has not yet been executed, the result is undefined.

getStatusText

String getStatusText()
Returns the status text (or "reason phrase") associated with the latest response.

Returns:
The status text from the most recent execution of this method. If the method has not yet been executed, the result is undefined.

getResponseHeaders

Header[] getResponseHeaders()
Returns the response headers from the most recent execution of this request.

Returns:
A newly-created array containing all of the response headers, in the order in which they appeared in the response.

getResponseHeader

Header getResponseHeader(String headerName)
Returns the specified response header. Note that header-name matching is case insensitive.

Parameters:
headerName - The name of the header to be returned.
Returns:
The specified response header. If the repsonse contained multiple instances of the header, its values will be combined using the ',' separator as specified by RFC2616.

getResponseHeaders

Header[] getResponseHeaders(String headerName)
Returns the response headers with the given name. Note that header-name matching is case insensitive.

Parameters:
headerName - the name of the headers to be returned.
Returns:
an array of zero or more headers
Since:
3.0

getResponseFooters

Header[] getResponseFooters()
Returns the response footers from the most recent execution of this request.

Returns:
an array containing the response footers in the order that they appeared in the response. If the response had no footers, an empty array will be returned.

getResponseFooter

Header getResponseFooter(String footerName)
Return the specified response footer. Note that footer-name matching is case insensitive.

Parameters:
footerName - The name of the footer.
Returns:
The response footer.

getResponseBody

byte[] getResponseBody()
                       throws IOException
Returns the response body of the HTTP method, if any, as an array of bytes. If the method has not yet been executed or the response has no body, null is returned. Note that this method does not propagate I/O exceptions. If an error occurs while reading the body, null will be returned.

Returns:
The response body, or null if the body is not available.
Throws:
IOException - if an I/O (transport) problem occurs

getResponseBodyAsString

String getResponseBodyAsString()
                               throws IOException
Returns the response body of the HTTP method, if any, as a String. If response body is not available or cannot be read, null is returned. The raw bytes in the body are converted to a String using the character encoding specified in the response's Content-Type header, or ISO-8859-1 if the response did not specify a character set.

Note that this method does not propagate I/O exceptions. If an error occurs while reading the body, null will be returned.

Returns:
The response body converted to a String, or null if the body is not available.
Throws:
IOException - if an I/O (transport) problem occurs

getResponseBodyAsStream

InputStream getResponseBodyAsStream()
                                    throws IOException
Returns the response body of the HTTP method, if any, as an InputStream. If the response had no body or the method has not yet been executed, null is returned. Additionally, null may be returned if releaseConnection() has been called or if this method was called previously and the resulting stream was closed.

Returns:
The response body, or null if it is not available
Throws:
IOException - if an I/O (transport) problem occurs

hasBeenUsed

boolean hasBeenUsed()
Returns true if the HTTP method has been already executed, but not recycled.

Returns:
true if the method has been executed, false otherwise

execute

int execute(HttpState state,
            HttpConnection connection)
            throws HttpException,
                   IOException
Executes this method using the specified HttpConnection and HttpState.

Parameters:
state - the state information to associate with this method
connection - the connection used to execute this HTTP method
Returns:
the integer status code if one was obtained, or -1
Throws:
IOException - If an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - If a protocol exception occurs. Usually protocol exceptions cannot be recovered from.

abort

void abort()
Aborts the execution of the HTTP method.

Since:
3.0
See Also:
execute(HttpState, HttpConnection)

recycle

void recycle()
Deprecated. no longer supported and will be removed in the future version of HttpClient

Recycles the HTTP method so that it can be used again. Note that all of the instance variables will be reset once this method has been called. This method will also release the connection being used by this HTTP method.

See Also:
releaseConnection()

releaseConnection

void releaseConnection()
Releases the connection being used by this HTTP method. In particular the connection is used to read the response (if there is one) and will be held until the response has been read. If the connection can be reused by other HTTP methods it is NOT closed at this point.

After this method is called, getResponseBodyAsStream() will return null, and getResponseBody() and getResponseBodyAsString() may return null.


addResponseFooter

void addResponseFooter(Header footer)
Add a footer to this method's response.

Note: This method is for internal use only and should not be called by external clients.

Parameters:
footer - the footer to add
Since:
2.0

getStatusLine

StatusLine getStatusLine()
Returns the Status-Line from the most recent response for this method, or null if the method has not been executed.

Returns:
the status line, or null if the method has not been executed
Since:
2.0

getDoAuthentication

boolean getDoAuthentication()
Returns true if the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.), false otherwise

Returns:
true if authentication challenges will be processed automatically, false otherwise.
Since:
2.0
See Also:
setDoAuthentication(boolean)

setDoAuthentication

void setDoAuthentication(boolean doAuthentication)
Sets whether or not the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.)

Parameters:
doAuthentication - true to process authentication challenges automatically, false otherwise.
Since:
2.0
See Also:
getDoAuthentication()

getParams

HttpMethodParams getParams()
Returns HTTP protocol parameters associated with this method.

Since:
3.0
See Also:
HttpMethodParams

setParams

void setParams(HttpMethodParams params)
Assigns HTTP protocol parameters for this method.

Since:
3.0
See Also:
HttpMethodParams

getHostAuthState

AuthState getHostAuthState()
Returns the target host authentication state

Returns:
host authentication state
Since:
3.0

getProxyAuthState

AuthState getProxyAuthState()
Returns the proxy authentication state

Returns:
host authentication state
Since:
3.0

isRequestSent

boolean isRequestSent()
Returns true if the HTTP has been transmitted to the target server in its entirety, false otherwise. This flag can be useful for recovery logic. If the request has not been transmitted in its entirety, it is safe to retry the failed method.

Returns:
true if the request has been sent, false otherwise


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpMethodBase.html100644 0 0 601545 10661532627 26372 0ustar 0 0 HttpMethodBase (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpMethodBase

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
All Implemented Interfaces:
HttpMethod
Direct Known Subclasses:
ConnectMethod, DeleteMethod, ExpectContinueMethod, GetMethod, HeadMethod, OptionsMethod, TraceMethod

public abstract class HttpMethodBase
extends Object
implements HttpMethod

An abstract base implementation of HttpMethod.

At minimum, subclasses will need to override:

  • getName() to return the approriate name for this method

When a method requires additional request headers, subclasses will typically want to override:

When a method expects specific response headers, subclasses may want to override:

Version:
$Revision: 539441 $ $Date: 2007-05-18 14:56:55 +0200 (Fri, 18 May 2007) $
Author:
Remy Maucherat, Rodney Waldhoff, Sean C. Sullivan, dIon Gillard, Jeff Dever, Davanum Srinivas, Ortwin Glueck, Eric Johnson, Michael Becke, Oleg Kalnichevski, Mike Bowler, Gary Gregory, Christian Kohlschuetter

Field Summary
protected  HttpVersion effectiveVersion
          HTTP protocol version used for execution of this method.
protected  StatusLine statusLine
          The Status-Line from the response.
 
Constructor Summary
HttpMethodBase()
          No-arg constructor.
HttpMethodBase(String uri)
          Constructor specifying a URI.
 
Method Summary
 void abort()
          Aborts the execution of this method.
protected  void addCookieRequestHeader(HttpState state, HttpConnection conn)
          Generates Cookie request headers for those cookies that match the given host, port and path.
protected  void addHostRequestHeader(HttpState state, HttpConnection conn)
          Generates Host request header, as long as no Host request header already exists.
protected  void addProxyConnectionHeader(HttpState state, HttpConnection conn)
          Generates Proxy-Connection: Keep-Alive request header when communicating via a proxy server.
 void addRequestHeader(Header header)
          Adds the specified request header, NOT overwriting any previous value.
 void addRequestHeader(String headerName, String headerValue)
          Adds the specified request header, NOT overwriting any previous value.
protected  void addRequestHeaders(HttpState state, HttpConnection conn)
          Generates all the required request headers to be submitted via the given connection.
 void addResponseFooter(Header footer)
          Use this method internally to add footers.
protected  void addUserAgentRequestHeader(HttpState state, HttpConnection conn)
          Generates default User-Agent request header, as long as no User-Agent request header already exists.
protected  void checkNotUsed()
          Throws an IllegalStateException if the HTTP method has been already executed, but not recycled.
protected  void checkUsed()
          Throws an IllegalStateException if the HTTP method has not been executed since last recycle.
 int execute(HttpState state, HttpConnection conn)
          Executes this method using the specified HttpConnection and HttpState.
protected static String generateRequestLine(HttpConnection connection, String name, String requestPath, String query, String version)
          Generates HTTP request line according to the specified attributes.
 String getAuthenticationRealm()
          Deprecated. use #getHostAuthState()
protected  String getContentCharSet(Header contentheader)
          Returns the character set from the Content-Type header.
 boolean getDoAuthentication()
          Returns true if the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.), false otherwise
 HttpVersion getEffectiveVersion()
          Returns the HTTP version used with this method (may be null if undefined, that is, the method has not been executed)
 boolean getFollowRedirects()
          Returns true if the HTTP method should automatically follow HTTP redirects (status code 302, etc.), false otherwise.
 AuthState getHostAuthState()
          Returns the target host authentication state
 HostConfiguration getHostConfiguration()
          Deprecated. no longer applicable
 MethodRetryHandler getMethodRetryHandler()
          Deprecated. use HttpMethodParams
abstract  String getName()
          Obtains the name of the HTTP method as used in the HTTP request line, for example "GET" or "POST".
 HttpMethodParams getParams()
          Returns HTTP protocol parameters associated with this method.
 String getPath()
          Gets the path of this HTTP method.
 String getProxyAuthenticationRealm()
          Deprecated. use #getProxyAuthState()
 AuthState getProxyAuthState()
          Returns the proxy authentication state
 String getQueryString()
          Gets the query string of this HTTP method.
 int getRecoverableExceptionCount()
          Deprecated. no longer used Returns the number of "recoverable" exceptions thrown and handled, to allow for monitoring the quality of the connection.
 String getRequestCharSet()
          Returns the character encoding of the request from the Content-Type header.
 Header getRequestHeader(String headerName)
          Returns the specified request header.
protected  HeaderGroup getRequestHeaderGroup()
          Gets the header group storing the request headers.
 Header[] getRequestHeaders()
          Returns an array of the requests headers that the HTTP method currently has
 Header[] getRequestHeaders(String headerName)
          Returns the request headers with the given name.
 byte[] getResponseBody()
          Returns the response body of the HTTP method, if any, as an array of bytes.
 byte[] getResponseBody(int maxlen)
          Returns the response body of the HTTP method, if any, as an array of bytes.
 InputStream getResponseBodyAsStream()
          Returns the response body of the HTTP method, if any, as an InputStream.
 String getResponseBodyAsString()
          Returns the response body of the HTTP method, if any, as a String.
 String getResponseBodyAsString(int maxlen)
          Returns the response body of the HTTP method, if any, as a String.
 String getResponseCharSet()
          Returns the character encoding of the response from the Content-Type header.
 long getResponseContentLength()
          Return the length (in bytes) of the response body, as specified in a Content-Length header.
 Header getResponseFooter(String footerName)
          Gets the response footer associated with the given name.
 Header[] getResponseFooters()
          Returns an array of the response footers that the HTTP method currently has in the order in which they were read.
 Header getResponseHeader(String headerName)
          Gets the response header associated with the given name.
protected  HeaderGroup getResponseHeaderGroup()
          Gets the header group storing the response headers.
 Header[] getResponseHeaders()
          Returns an array of the response headers that the HTTP method currently has in the order in which they were read.
 Header[] getResponseHeaders(String headerName)
          Returns the response headers with the given name.
protected  InputStream getResponseStream()
          Returns a stream from which the body of the current response may be read.
protected  HeaderGroup getResponseTrailerHeaderGroup()
          Gets the header group storing the response trailer headers as per RFC 2616 section 3.6.1.
 int getStatusCode()
          Returns the response status code.
 StatusLine getStatusLine()
          Provides access to the response status line.
 String getStatusText()
          Returns the status text (or "reason phrase") associated with the latest response.
 URI getURI()
          Returns the URI of the HTTP method
 boolean hasBeenUsed()
          Returns true if the HTTP method has been already executed, but not recycled.
 boolean isAborted()
          Tests whether the execution of this method has been aborted
protected  boolean isConnectionCloseForced()
          Tests if the connection should be force-closed when no longer needed.
 boolean isHttp11()
          Deprecated. Use HttpMethodParams.getVersion()
 boolean isRequestSent()
          Returns true if the HTTP has been transmitted to the target server in its entirety, false otherwise.
 boolean isStrictMode()
          Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.
protected  void processCookieHeaders(CookieSpec parser, Header[] headers, HttpState state, HttpConnection conn)
          This method processes the specified cookie headers.
protected  void processResponseBody(HttpState state, HttpConnection conn)
          This method is invoked immediately after readResponseBody(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom body processing.
protected  void processResponseHeaders(HttpState state, HttpConnection conn)
          This method is invoked immediately after readResponseHeaders(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom response headers processing.
protected  void processStatusLine(HttpState state, HttpConnection conn)
          This method is invoked immediately after readStatusLine(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom response status line processing.
protected  void readResponse(HttpState state, HttpConnection conn)
          Reads the response from the given connection.
protected  void readResponseBody(HttpState state, HttpConnection conn)
          Read the response body from the given HttpConnection.
protected  void readResponseHeaders(HttpState state, HttpConnection conn)
          Reads the response headers from the given connection.
protected  void readStatusLine(HttpState state, HttpConnection conn)
          Read the status line from the given HttpConnection, setting my status code and status text.
 void recycle()
          Deprecated. no longer supported and will be removed in the future version of HttpClient
 void releaseConnection()
          Releases the connection being used by this HTTP method.
 void removeRequestHeader(Header header)
          Removes the given request header.
 void removeRequestHeader(String headerName)
          Remove the request header associated with the given name.
protected  void responseBodyConsumed()
          A response has been consumed.
protected  void setConnectionCloseForced(boolean b)
          Sets whether or not the connection should be force-closed when no longer needed.
 void setDoAuthentication(boolean doAuthentication)
          Sets whether or not the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.)
 void setFollowRedirects(boolean followRedirects)
          Sets whether or not the HTTP method should automatically follow HTTP redirects (status code 302, etc.)
 void setHostConfiguration(HostConfiguration hostconfig)
          Deprecated. no longer applicable
 void setHttp11(boolean http11)
          Deprecated. Use HttpMethodParams.setVersion(HttpVersion)
 void setMethodRetryHandler(MethodRetryHandler handler)
          Deprecated. use HttpMethodParams
 void setParams(HttpMethodParams params)
          Assigns HTTP protocol parameters for this method.
 void setPath(String path)
          Sets the path of the HTTP method.
 void setQueryString(NameValuePair[] params)
          Sets the query string of this HTTP method.
 void setQueryString(String queryString)
          Sets the query string of this HTTP method.
 void setRequestHeader(Header header)
          Sets the specified request header, overwriting any previous value.
 void setRequestHeader(String headerName, String headerValue)
          Set the specified request header, overwriting any previous value.
protected  void setResponseStream(InputStream responseStream)
          Sets the response stream.
 void setStrictMode(boolean strictMode)
          Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.
 void setURI(URI uri)
          Sets the URI for this method.
protected  boolean shouldCloseConnection(HttpConnection conn)
          Tests if the connection should be closed after the method has been executed.
 boolean validate()
          Returns true the method is ready to execute, false otherwise.
protected  void writeRequest(HttpState state, HttpConnection conn)
           Sends the request via the given connection.
protected  boolean writeRequestBody(HttpState state, HttpConnection conn)
          Writes the request body to the given connection.
protected  void writeRequestHeaders(HttpState state, HttpConnection conn)
          Writes the request headers to the given connection.
protected  void writeRequestLine(HttpState state, HttpConnection conn)
          Writes the request line to the given connection.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

statusLine

protected StatusLine statusLine
The Status-Line from the response.


effectiveVersion

protected HttpVersion effectiveVersion
HTTP protocol version used for execution of this method.

Constructor Detail

HttpMethodBase

public HttpMethodBase()
No-arg constructor.


HttpMethodBase

public HttpMethodBase(String uri)
               throws IllegalArgumentException,
                      IllegalStateException
Constructor specifying a URI. It is responsibility of the caller to ensure that URI elements (path & query parameters) are properly encoded (URL safe).

Parameters:
uri - either an absolute or relative URI. The URI is expected to be URL-encoded
Throws:
IllegalArgumentException - when URI is invalid
IllegalStateException - when protocol of the absolute URI is not recognised
Method Detail

getName

public abstract String getName()
Obtains the name of the HTTP method as used in the HTTP request line, for example "GET" or "POST".

Specified by:
getName in interface HttpMethod
Returns:
the name of this method

getURI

public URI getURI()
           throws URIException
Returns the URI of the HTTP method

Specified by:
getURI in interface HttpMethod
Returns:
The URI
Throws:
URIException - If the URI cannot be created.
See Also:
HttpMethod.getURI()

setURI

public void setURI(URI uri)
            throws URIException
Sets the URI for this method.

Specified by:
setURI in interface HttpMethod
Parameters:
uri - URI to be set
Throws:
URIException - if a URI cannot be set
Since:
3.0

setFollowRedirects

public void setFollowRedirects(boolean followRedirects)
Sets whether or not the HTTP method should automatically follow HTTP redirects (status code 302, etc.)

Specified by:
setFollowRedirects in interface HttpMethod
Parameters:
followRedirects - true if the method will automatically follow redirects, false otherwise.

getFollowRedirects

public boolean getFollowRedirects()
Returns true if the HTTP method should automatically follow HTTP redirects (status code 302, etc.), false otherwise.

Specified by:
getFollowRedirects in interface HttpMethod
Returns:
true if the method will automatically follow HTTP redirects, false otherwise.

setHttp11

public void setHttp11(boolean http11)
Deprecated. Use HttpMethodParams.setVersion(HttpVersion)

Sets whether version 1.1 of the HTTP protocol should be used per default.

Parameters:
http11 - true to use HTTP/1.1, false to use 1.0

getDoAuthentication

public boolean getDoAuthentication()
Returns true if the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.), false otherwise

Specified by:
getDoAuthentication in interface HttpMethod
Returns:
true if authentication challenges will be processed automatically, false otherwise.
Since:
2.0
See Also:
HttpMethod.setDoAuthentication(boolean)

setDoAuthentication

public void setDoAuthentication(boolean doAuthentication)
Sets whether or not the HTTP method should automatically handle HTTP authentication challenges (status code 401, etc.)

Specified by:
setDoAuthentication in interface HttpMethod
Parameters:
doAuthentication - true to process authentication challenges authomatically, false otherwise.
Since:
2.0
See Also:
HttpMethod.getDoAuthentication()

isHttp11

public boolean isHttp11()
Deprecated. Use HttpMethodParams.getVersion()

Returns true if version 1.1 of the HTTP protocol should be used per default, false if version 1.0 should be used.

Returns:
true to use HTTP/1.1, false to use 1.0

setPath

public void setPath(String path)
Sets the path of the HTTP method. It is responsibility of the caller to ensure that the path is properly encoded (URL safe).

Specified by:
setPath in interface HttpMethod
Parameters:
path - the path of the HTTP method. The path is expected to be URL-encoded

addRequestHeader

public void addRequestHeader(Header header)
Adds the specified request header, NOT overwriting any previous value. Note that header-name matching is case insensitive.

Specified by:
addRequestHeader in interface HttpMethod
Parameters:
header - the header to add to the request
See Also:
HttpMethod.addRequestHeader(String,String), HttpMethod.getRequestHeader(String), HttpMethod.removeRequestHeader(String)

addResponseFooter

public void addResponseFooter(Header footer)
Use this method internally to add footers.

Specified by:
addResponseFooter in interface HttpMethod
Parameters:
footer - The footer to add.

getPath

public String getPath()
Gets the path of this HTTP method. Calling this method after the request has been executed will return the actual path, following any redirects automatically handled by this HTTP method.

Specified by:
getPath in interface HttpMethod
Returns:
the path to request or "/" if the path is blank.

setQueryString

public void setQueryString(String queryString)
Sets the query string of this HTTP method. The caller must ensure that the string is properly URL encoded. The query string should not start with the question mark character.

Specified by:
setQueryString in interface HttpMethod
Parameters:
queryString - the query string
See Also:
EncodingUtil.formUrlEncode(NameValuePair[], String)

setQueryString

public void setQueryString(NameValuePair[] params)
Sets the query string of this HTTP method. The pairs are encoded as UTF-8 characters. To use a different charset the parameters can be encoded manually using EncodingUtil and set as a single String.

Specified by:
setQueryString in interface HttpMethod
Parameters:
params - an array of NameValuePairs to add as query string parameters. The name/value pairs will be automcatically URL encoded
See Also:
EncodingUtil.formUrlEncode(NameValuePair[], String), setQueryString(String)

getQueryString

public String getQueryString()
Gets the query string of this HTTP method.

Specified by:
getQueryString in interface HttpMethod
Returns:
The query string
See Also:
HttpMethod.setQueryString(NameValuePair[]), HttpMethod.setQueryString(String)

setRequestHeader

public void setRequestHeader(String headerName,
                             String headerValue)
Set the specified request header, overwriting any previous value. Note that header-name matching is case-insensitive.

Specified by:
setRequestHeader in interface HttpMethod
Parameters:
headerName - the header's name
headerValue - the header's value
See Also:
HttpMethod.setRequestHeader(Header), HttpMethod.getRequestHeader(String), HttpMethod.removeRequestHeader(String)

setRequestHeader

public void setRequestHeader(Header header)
Sets the specified request header, overwriting any previous value. Note that header-name matching is case insensitive.

Specified by:
setRequestHeader in interface HttpMethod
Parameters:
header - the header
See Also:
HttpMethod.setRequestHeader(String,String), HttpMethod.getRequestHeader(String), HttpMethod.removeRequestHeader(String)

getRequestHeader

public Header getRequestHeader(String headerName)
Returns the specified request header. Note that header-name matching is case insensitive. null will be returned if either headerName is null or there is no matching header for headerName.

Specified by:
getRequestHeader in interface HttpMethod
Parameters:
headerName - The name of the header to be returned.
Returns:
The specified request header.
Since:
3.0

getRequestHeaders

public Header[] getRequestHeaders()
Returns an array of the requests headers that the HTTP method currently has

Specified by:
getRequestHeaders in interface HttpMethod
Returns:
an array of my request headers.
See Also:
HttpMethod.addRequestHeader(Header), HttpMethod.addRequestHeader(String,String)

getRequestHeaders

public Header[] getRequestHeaders(String headerName)
Description copied from interface: HttpMethod
Returns the request headers with the given name. Note that header-name matching is case insensitive.

Specified by:
getRequestHeaders in interface HttpMethod
Parameters:
headerName - the name of the headers to be returned.
Returns:
an array of zero or more headers
See Also:
HttpMethod.getRequestHeaders(java.lang.String)

getRequestHeaderGroup

protected HeaderGroup getRequestHeaderGroup()
Gets the header group storing the request headers.

Returns:
a HeaderGroup
Since:
2.0beta1

getResponseTrailerHeaderGroup

protected HeaderGroup getResponseTrailerHeaderGroup()
Gets the header group storing the response trailer headers as per RFC 2616 section 3.6.1.

Returns:
a HeaderGroup
Since:
2.0beta1

getResponseHeaderGroup

protected HeaderGroup getResponseHeaderGroup()
Gets the header group storing the response headers.

Returns:
a HeaderGroup
Since:
2.0beta1

getResponseHeaders

public Header[] getResponseHeaders(String headerName)
Description copied from interface: HttpMethod
Returns the response headers with the given name. Note that header-name matching is case insensitive.

Specified by:
getResponseHeaders in interface HttpMethod
Parameters:
headerName - the name of the headers to be returned.
Returns:
an array of zero or more headers
Since:
3.0
See Also:
HttpMethod.getResponseHeaders(java.lang.String)

getStatusCode

public int getStatusCode()
Returns the response status code.

Specified by:
getStatusCode in interface HttpMethod
Returns:
the status code associated with the latest response.

getStatusLine

public StatusLine getStatusLine()
Provides access to the response status line.

Specified by:
getStatusLine in interface HttpMethod
Returns:
the status line object from the latest response.
Since:
2.0

getResponseHeaders

public Header[] getResponseHeaders()
Returns an array of the response headers that the HTTP method currently has in the order in which they were read.

Specified by:
getResponseHeaders in interface HttpMethod
Returns:
an array of response headers.

getResponseHeader

public Header getResponseHeader(String headerName)
Gets the response header associated with the given name. Header name matching is case insensitive. null will be returned if either headerName is null or there is no matching header for headerName.

Specified by:
getResponseHeader in interface HttpMethod
Parameters:
headerName - the header name to match
Returns:
the matching header

getResponseContentLength

public long getResponseContentLength()
Return the length (in bytes) of the response body, as specified in a Content-Length header.

Return -1 when the content-length is unknown.

Returns:
content length, if Content-Length header is available. 0 indicates that the request has no body. If Content-Length header is not present, the method returns -1.

getResponseBody

public byte[] getResponseBody()
                       throws IOException
Returns the response body of the HTTP method, if any, as an array of bytes. If response body is not available or cannot be read, returns null. Buffers the response and this method can be called several times yielding the same result each time. Note: This will cause the entire response body to be buffered in memory. A malicious server may easily exhaust all the VM memory. It is strongly recommended, to use getResponseAsStream if the content length of the response is unknown or resonably large.

Specified by:
getResponseBody in interface HttpMethod
Returns:
The response body.
Throws:
IOException - If an I/O (transport) problem occurs while obtaining the response body.

getResponseBody

public byte[] getResponseBody(int maxlen)
                       throws IOException
Returns the response body of the HTTP method, if any, as an array of bytes. If response body is not available or cannot be read, returns null. Buffers the response and this method can be called several times yielding the same result each time. Note: This will cause the entire response body to be buffered in memory. This method is safe if the content length of the response is unknown, because the amount of memory used is limited.

If the response is large this method involves lots of array copying and many object allocations, which makes it unsuitable for high-performance / low-footprint applications. Those applications should use getResponseBodyAsStream().

Parameters:
maxlen - the maximum content length to accept (number of bytes).
Returns:
The response body.
Throws:
IOException - If an I/O (transport) problem occurs while obtaining the response body.

getResponseBodyAsStream

public InputStream getResponseBodyAsStream()
                                    throws IOException
Returns the response body of the HTTP method, if any, as an InputStream. If response body is not available, returns null. If the response has been buffered this method returns a new stream object on every call. If the response has not been buffered the returned stream can only be read once.

Specified by:
getResponseBodyAsStream in interface HttpMethod
Returns:
The response body or null.
Throws:
IOException - If an I/O (transport) problem occurs while obtaining the response body.

getResponseBodyAsString

public String getResponseBodyAsString()
                               throws IOException
Returns the response body of the HTTP method, if any, as a String. If response body is not available or cannot be read, returns null The string conversion on the data is done using the character encoding specified in Content-Type header. Buffers the response and this method can be called several times yielding the same result each time. Note: This will cause the entire response body to be buffered in memory. A malicious server may easily exhaust all the VM memory. It is strongly recommended, to use getResponseAsStream if the content length of the response is unknown or resonably large.

Specified by:
getResponseBodyAsString in interface HttpMethod
Returns:
The response body or null.
Throws:
IOException - If an I/O (transport) problem occurs while obtaining the response body.

getResponseBodyAsString

public String getResponseBodyAsString(int maxlen)
                               throws IOException
Returns the response body of the HTTP method, if any, as a String. If response body is not available or cannot be read, returns null The string conversion on the data is done using the character encoding specified in Content-Type header. Buffers the response and this method can be called several times yielding the same result each time.

Note: This will cause the entire response body to be buffered in memory. This method is safe if the content length of the response is unknown, because the amount of memory used is limited.

If the response is large this method involves lots of array copying and many object allocations, which makes it unsuitable for high-performance / low-footprint applications. Those applications should use getResponseBodyAsStream().

Parameters:
maxlen - the maximum content length to accept (number of bytes). Note that, depending on the encoding, this is not equal to the number of characters.
Returns:
The response body or null.
Throws:
IOException - If an I/O (transport) problem occurs while obtaining the response body.

getResponseFooters

public Header[] getResponseFooters()
Returns an array of the response footers that the HTTP method currently has in the order in which they were read.

Specified by:
getResponseFooters in interface HttpMethod
Returns:
an array of footers

getResponseFooter

public Header getResponseFooter(String footerName)
Gets the response footer associated with the given name. Footer name matching is case insensitive. null will be returned if either footerName is null or there is no matching footer for footerName or there are no footers available. If there are multiple footers with the same name, there values will be combined with the ',' separator as specified by RFC2616.

Specified by:
getResponseFooter in interface HttpMethod
Parameters:
footerName - the footer name to match
Returns:
the matching footer

setResponseStream

protected void setResponseStream(InputStream responseStream)
Sets the response stream.

Parameters:
responseStream - The new response stream.

getResponseStream

protected InputStream getResponseStream()
Returns a stream from which the body of the current response may be read. If the method has not yet been executed, if responseBodyConsumed has been called, or if the stream returned by a previous call has been closed, null will be returned.

Returns:
the current response stream

getStatusText

public String getStatusText()
Returns the status text (or "reason phrase") associated with the latest response.

Specified by:
getStatusText in interface HttpMethod
Returns:
The status text.

setStrictMode

public void setStrictMode(boolean strictMode)
Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.

Defines how strictly HttpClient follows the HTTP protocol specification (RFC 2616 and other relevant RFCs). In the strict mode HttpClient precisely implements the requirements of the specification, whereas in non-strict mode it attempts to mimic the exact behaviour of commonly used HTTP agents, which many HTTP servers expect.

Specified by:
setStrictMode in interface HttpMethod
Parameters:
strictMode - true for strict mode, false otherwise
See Also:
HttpMethod.isStrictMode()

isStrictMode

public boolean isStrictMode()
Deprecated. Use HttpParams.setParameter(String, Object) to exercise a more granular control over HTTP protocol strictness.

Description copied from interface: HttpMethod
Returns the value of the strict mode flag.

Specified by:
isStrictMode in interface HttpMethod
Returns:
false
See Also:
HttpMethod.setStrictMode(boolean)

addRequestHeader

public void addRequestHeader(String headerName,
                             String headerValue)
Adds the specified request header, NOT overwriting any previous value. Note that header-name matching is case insensitive.

Specified by:
addRequestHeader in interface HttpMethod
Parameters:
headerName - the header's name
headerValue - the header's value
See Also:
HttpMethod.addRequestHeader(Header), HttpMethod.getRequestHeader(String), HttpMethod.removeRequestHeader(String)

isConnectionCloseForced

protected boolean isConnectionCloseForced()
Tests if the connection should be force-closed when no longer needed.

Returns:
true if the connection must be closed

setConnectionCloseForced

protected void setConnectionCloseForced(boolean b)
Sets whether or not the connection should be force-closed when no longer needed. This value should only be set to true in abnormal circumstances, such as HTTP protocol violations.

Parameters:
b - true if the connection must be closed, false otherwise.

shouldCloseConnection

protected boolean shouldCloseConnection(HttpConnection conn)
Tests if the connection should be closed after the method has been executed. The connection will be left open when using HTTP/1.1 or if Connection: keep-alive header was sent.

Parameters:
conn - the connection in question
Returns:
boolean true if we should close the connection.

execute

public int execute(HttpState state,
                   HttpConnection conn)
            throws HttpException,
                   IOException
Executes this method using the specified HttpConnection and HttpState.

Specified by:
execute in interface HttpMethod
Parameters:
state - state information to associate with this request. Must be non-null.
conn - the connection to used to execute this HTTP method. Must be non-null.
Returns:
the integer status code if one was obtained, or -1
Throws:
IOException - if an I/O (transport) error occurs
HttpException - if a protocol exception occurs.

abort

public void abort()
Aborts the execution of this method.

Specified by:
abort in interface HttpMethod
Since:
3.0
See Also:
HttpMethod.execute(HttpState, HttpConnection)

hasBeenUsed

public boolean hasBeenUsed()
Returns true if the HTTP method has been already executed, but not recycled.

Specified by:
hasBeenUsed in interface HttpMethod
Returns:
true if the method has been executed, false otherwise

recycle

public void recycle()
Deprecated. no longer supported and will be removed in the future version of HttpClient

Recycles the HTTP method so that it can be used again. Note that all of the instance variables will be reset once this method has been called. This method will also release the connection being used by this HTTP method.

Specified by:
recycle in interface HttpMethod
See Also:
releaseConnection()

releaseConnection

public void releaseConnection()
Releases the connection being used by this HTTP method. In particular the connection is used to read the response(if there is one) and will be held until the response has been read. If the connection can be reused by other HTTP methods it is NOT closed at this point.

Specified by:
releaseConnection in interface HttpMethod
Since:
2.0

removeRequestHeader

public void removeRequestHeader(String headerName)
Remove the request header associated with the given name. Note that header-name matching is case insensitive.

Specified by:
removeRequestHeader in interface HttpMethod
Parameters:
headerName - the header name

removeRequestHeader

public void removeRequestHeader(Header header)
Removes the given request header.

Specified by:
removeRequestHeader in interface HttpMethod
Parameters:
header - the header

validate

public boolean validate()
Returns true the method is ready to execute, false otherwise.

Specified by:
validate in interface HttpMethod
Returns:
This implementation always returns true.

addCookieRequestHeader

protected void addCookieRequestHeader(HttpState state,
                                      HttpConnection conn)
                               throws IOException,
                                      HttpException
Generates Cookie request headers for those cookies that match the given host, port and path.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.

addHostRequestHeader

protected void addHostRequestHeader(HttpState state,
                                    HttpConnection conn)
                             throws IOException,
                                    HttpException
Generates Host request header, as long as no Host request header already exists.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.

addProxyConnectionHeader

protected void addProxyConnectionHeader(HttpState state,
                                        HttpConnection conn)
                                 throws IOException,
                                        HttpException
Generates Proxy-Connection: Keep-Alive request header when communicating via a proxy server.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.

addRequestHeaders

protected void addRequestHeaders(HttpState state,
                                 HttpConnection conn)
                          throws IOException,
                                 HttpException
Generates all the required request headers to be submitted via the given connection.

This implementation adds User-Agent, Host, Cookie, Authorization, Proxy-Authorization and Proxy-Connection headers, when appropriate.

Subclasses may want to override this method to to add additional headers, and may choose to invoke this implementation (via super) to add the "standard" headers.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
See Also:
writeRequestHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)

addUserAgentRequestHeader

protected void addUserAgentRequestHeader(HttpState state,
                                         HttpConnection conn)
                                  throws IOException,
                                         HttpException
Generates default User-Agent request header, as long as no User-Agent request header already exists.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.

checkNotUsed

protected void checkNotUsed()
                     throws IllegalStateException
Throws an IllegalStateException if the HTTP method has been already executed, but not recycled.

Throws:
IllegalStateException - if the method has been used and not recycled

checkUsed

protected void checkUsed()
                  throws IllegalStateException
Throws an IllegalStateException if the HTTP method has not been executed since last recycle.

Throws:
IllegalStateException - if not used

generateRequestLine

protected static String generateRequestLine(HttpConnection connection,
                                            String name,
                                            String requestPath,
                                            String query,
                                            String version)
Generates HTTP request line according to the specified attributes.

Parameters:
connection - the connection used to execute this HTTP method
name - the method name generate a request for
requestPath - the path string for the request
query - the query string for the request
version - the protocol version to use (e.g. HTTP/1.0)
Returns:
HTTP request line

processResponseBody

protected void processResponseBody(HttpState state,
                                   HttpConnection conn)
This method is invoked immediately after readResponseBody(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom body processing.

This implementation does nothing.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
See Also:
readResponse(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection), readResponseBody(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)

processResponseHeaders

protected void processResponseHeaders(HttpState state,
                                      HttpConnection conn)
This method is invoked immediately after readResponseHeaders(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom response headers processing.

This implementation will handle the Set-Cookie and Set-Cookie2 headers, if any, adding the relevant cookies to the given HttpState.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
See Also:
readResponse(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection), readResponseHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)

processCookieHeaders

protected void processCookieHeaders(CookieSpec parser,
                                    Header[] headers,
                                    HttpState state,
                                    HttpConnection conn)
This method processes the specified cookie headers. It is invoked from within processResponseHeaders(HttpState,HttpConnection)

Parameters:
headers - cookie Headers to be processed
state - the state information associated with this HTTP method
conn - the connection used to execute this HTTP method

processStatusLine

protected void processStatusLine(HttpState state,
                                 HttpConnection conn)
This method is invoked immediately after readStatusLine(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom response status line processing.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
See Also:
readResponse(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection), readStatusLine(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)

readResponse

protected void readResponse(HttpState state,
                            HttpConnection conn)
                     throws IOException,
                            HttpException
Reads the response from the given connection.

The response is processed as the following sequence of actions:

  1. readStatusLine(HttpState,HttpConnection) is invoked to read the request line.
  2. processStatusLine(HttpState,HttpConnection) is invoked, allowing the method to process the status line if desired.
  3. readResponseHeaders(HttpState,HttpConnection) is invoked to read the associated headers.
  4. processResponseHeaders(HttpState,HttpConnection) is invoked, allowing the method to process the headers if desired.
  5. readResponseBody(HttpState,HttpConnection) is invoked to read the associated body (if any).
  6. processResponseBody(HttpState,HttpConnection) is invoked, allowing the method to process the response body if desired.
Subclasses may want to override one or more of the above methods to to customize the processing. (Or they may choose to override this method if dramatically different processing is required.)

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.

readResponseBody

protected void readResponseBody(HttpState state,
                                HttpConnection conn)
                         throws IOException,
                                HttpException
Read the response body from the given HttpConnection.

The current implementation wraps the socket level stream with an appropriate stream for the type of response (chunked, content-length, or auto-close). If there is no response body, the connection associated with the request will be returned to the connection manager.

Subclasses may want to override this method to to customize the processing.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
See Also:
readResponse(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection), processResponseBody(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)

readResponseHeaders

protected void readResponseHeaders(HttpState state,
                                   HttpConnection conn)
                            throws IOException,
                                   HttpException
Reads the response headers from the given connection.

Subclasses may want to override this method to to customize the processing.

"It must be possible to combine the multiple header fields into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field-value to the first, each separated by a comma." - HTTP/1.0 (4.3)

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
See Also:
readResponse(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection), processResponseHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)

readStatusLine

protected void readStatusLine(HttpState state,
                              HttpConnection conn)
                       throws IOException,
                              HttpException
Read the status line from the given HttpConnection, setting my status code and status text.

Subclasses may want to override this method to to customize the processing.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
See Also:
StatusLine

writeRequest

protected void writeRequest(HttpState state,
                            HttpConnection conn)
                     throws IOException,
                            HttpException

Sends the request via the given connection.

The request is written as the following sequence of actions:

  1. writeRequestLine(HttpState, HttpConnection) is invoked to write the request line.
  2. writeRequestHeaders(HttpState, HttpConnection) is invoked to write the associated headers.
  3. \r\n is sent to close the head part of the request.
  4. writeRequestBody(HttpState, HttpConnection) is invoked to write the body part of the request.

Subclasses may want to override one or more of the above methods to to customize the processing. (Or they may choose to override this method if dramatically different processing is required.)

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.

writeRequestBody

protected boolean writeRequestBody(HttpState state,
                                   HttpConnection conn)
                            throws IOException,
                                   HttpException
Writes the request body to the given connection.

This method should return true if the request body was actually sent (or is empty), or false if it could not be sent for some reason.

This implementation writes nothing and returns true.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Returns:
true
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.

writeRequestHeaders

protected void writeRequestHeaders(HttpState state,
                                   HttpConnection conn)
                            throws IOException,
                                   HttpException
Writes the request headers to the given connection.

This implementation invokes addRequestHeaders(HttpState,HttpConnection), and then writes each header to the request stream.

Subclasses may want to override this method to to customize the processing.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
See Also:
addRequestHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection), getRequestHeaders()

writeRequestLine

protected void writeRequestLine(HttpState state,
                                HttpConnection conn)
                         throws IOException,
                                HttpException
Writes the request line to the given connection.

Subclasses may want to override this method to to customize the processing.

Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
See Also:
generateRequestLine(org.apache.commons.httpclient.HttpConnection, java.lang.String, java.lang.String, java.lang.String, java.lang.String)

getParams

public HttpMethodParams getParams()
Returns HTTP protocol parameters associated with this method.

Specified by:
getParams in interface HttpMethod
Returns:
HTTP parameters.
Since:
3.0
See Also:
HttpMethodParams

setParams

public void setParams(HttpMethodParams params)
Assigns HTTP protocol parameters for this method.

Specified by:
setParams in interface HttpMethod
Since:
3.0
See Also:
HttpMethodParams

getEffectiveVersion

public HttpVersion getEffectiveVersion()
Returns the HTTP version used with this method (may be null if undefined, that is, the method has not been executed)

Returns:
HTTP version.
Since:
3.0

getProxyAuthenticationRealm

public String getProxyAuthenticationRealm()
Deprecated. use #getProxyAuthState()

Returns proxy authentication realm, if it has been used during authentication process. Otherwise returns null.

Returns:
proxy authentication realm

getAuthenticationRealm

public String getAuthenticationRealm()
Deprecated. use #getHostAuthState()

Returns authentication realm, if it has been used during authentication process. Otherwise returns null.

Returns:
authentication realm

getContentCharSet

protected String getContentCharSet(Header contentheader)
Returns the character set from the Content-Type header.

Parameters:
contentheader - The content header.
Returns:
String The character set.

getRequestCharSet

public String getRequestCharSet()
Returns the character encoding of the request from the Content-Type header.

Returns:
String The character set.

getResponseCharSet

public String getResponseCharSet()
Returns the character encoding of the response from the Content-Type header.

Returns:
String The character set.

getRecoverableExceptionCount

public int getRecoverableExceptionCount()
Deprecated. no longer used Returns the number of "recoverable" exceptions thrown and handled, to allow for monitoring the quality of the connection.

Returns:
The number of recoverable exceptions handled by the method.

responseBodyConsumed

protected void responseBodyConsumed()
A response has been consumed.

The default behavior for this class is to check to see if the connection should be closed, and close if need be, and to ensure that the connection is returned to the connection manager - if and only if we are not still inside the execute call.


getHostConfiguration

public HostConfiguration getHostConfiguration()
Deprecated. no longer applicable

Returns the host configuration.

Specified by:
getHostConfiguration in interface HttpMethod
Returns:
the host configuration

setHostConfiguration

public void setHostConfiguration(HostConfiguration hostconfig)
Deprecated. no longer applicable

Sets the host configuration.

Parameters:
hostconfig - The hostConfiguration to set

getMethodRetryHandler

public MethodRetryHandler getMethodRetryHandler()
Deprecated. use HttpMethodParams

Returns the retry handler for this HTTP method

Returns:
the methodRetryHandler

setMethodRetryHandler

public void setMethodRetryHandler(MethodRetryHandler handler)
Deprecated. use HttpMethodParams

Sets the retry handler for this HTTP method

Parameters:
handler - the methodRetryHandler to use when this method executed

getHostAuthState

public AuthState getHostAuthState()
Returns the target host authentication state

Specified by:
getHostAuthState in interface HttpMethod
Returns:
host authentication state
Since:
3.0

getProxyAuthState

public AuthState getProxyAuthState()
Returns the proxy authentication state

Specified by:
getProxyAuthState in interface HttpMethod
Returns:
host authentication state
Since:
3.0

isAborted

public boolean isAborted()
Tests whether the execution of this method has been aborted

Returns:
true if the execution of this method has been aborted, false otherwise
Since:
3.0

isRequestSent

public boolean isRequestSent()
Returns true if the HTTP has been transmitted to the target server in its entirety, false otherwise. This flag can be useful for recovery logic. If the request has not been transmitted in its entirety, it is safe to retry the failed method.

Specified by:
isRequestSent in interface HttpMethod
Returns:
true if the request has been sent, false otherwise


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpMethodRetryHandler.html100644 0 0 24507 10661532627 30100 0ustar 0 0 HttpMethodRetryHandler (HttpClient 3.1 API)

org.apache.commons.httpclient
Interface HttpMethodRetryHandler

All Known Implementing Classes:
DefaultHttpMethodRetryHandler

public interface HttpMethodRetryHandler

A handler for determining if an HttpMethod should be retried after a recoverable exception during execution.

Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads

Author:
Michael Becke, Oleg Kalnichevski
See Also:
HttpMethod.execute(HttpState, HttpConnection)

Method Summary
 boolean retryMethod(HttpMethod method, IOException exception, int executionCount)
          Determines if a method should be retried after an HttpRecoverableException occurs during execution.
 

Method Detail

retryMethod

boolean retryMethod(HttpMethod method,
                    IOException exception,
                    int executionCount)
Determines if a method should be retried after an HttpRecoverableException occurs during execution.

Parameters:
method - the method being executed
exception - the exception that occurred
executionCount - the number of times this method has been unsuccessfully executed
Returns:
true if the method should be retried, false otherwise


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpParser.html100644 0 0 50662 10661532627 25571 0ustar 0 0 HttpParser (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpParser

java.lang.Object
  extended by org.apache.commons.httpclient.HttpParser

public class HttpParser
extends Object

A utility class for parsing http header values according to RFC-2616 Section 4 and 19.3.

Since:
2.0beta1
Author:
Michael Becke, Oleg Kalnichevski

Method Summary
static Header[] parseHeaders(InputStream is)
          Deprecated. use #parseHeaders(InputStream, String)
static Header[] parseHeaders(InputStream is, String charset)
          Parses headers from the given stream.
static String readLine(InputStream inputStream)
          Deprecated. use #readLine(InputStream, String)
static String readLine(InputStream inputStream, String charset)
          Read up to "\n" from an (unchunked) input stream.
static byte[] readRawLine(InputStream inputStream)
          Return byte array from an (unchunked) input stream.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

readRawLine

public static byte[] readRawLine(InputStream inputStream)
                          throws IOException
Return byte array from an (unchunked) input stream. Stop reading when "\n" terminator encountered If the stream ends before the line terminator is found, the last part of the string will still be returned. If no input data available, null is returned.

Parameters:
inputStream - the stream to read from
Returns:
a byte array from the stream
Throws:
IOException - if an I/O problem occurs

readLine

public static String readLine(InputStream inputStream,
                              String charset)
                       throws IOException
Read up to "\n" from an (unchunked) input stream. If the stream ends before the line terminator is found, the last part of the string will still be returned. If no input data available, null is returned.

Parameters:
inputStream - the stream to read from
charset - charset of HTTP protocol elements
Returns:
a line from the stream
Throws:
IOException - if an I/O problem occurs
Since:
3.0

readLine

public static String readLine(InputStream inputStream)
                       throws IOException
Deprecated. use #readLine(InputStream, String)

Read up to "\n" from an (unchunked) input stream. If the stream ends before the line terminator is found, the last part of the string will still be returned. If no input data available, null is returned

Parameters:
inputStream - the stream to read from
Returns:
a line from the stream
Throws:
IOException - if an I/O problem occurs

parseHeaders

public static Header[] parseHeaders(InputStream is,
                                    String charset)
                             throws IOException,
                                    HttpException
Parses headers from the given stream. Headers with the same name are not combined.

Parameters:
is - the stream to read headers from
charset - the charset to use for reading the data
Returns:
an array of headers in the order in which they were parsed
Throws:
IOException - if an IO error occurs while reading from the stream
HttpException - if there is an error parsing a header value
Since:
3.0

parseHeaders

public static Header[] parseHeaders(InputStream is)
                             throws IOException,
                                    HttpException
Deprecated. use #parseHeaders(InputStream, String)

Parses headers from the given stream. Headers with the same name are not combined.

Parameters:
is - the stream to read headers from
Returns:
an array of headers in the order in which they were parsed
Throws:
IOException - if an IO error occurs while reading from the stream
HttpException - if there is an error parsing a header value


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpRecoverableException.html100644 0 0 41341 10661532627 30437 0ustar 0 0 HttpRecoverableException (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpRecoverableException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.HttpRecoverableException
All Implemented Interfaces:
Serializable

Deprecated. no longer used

public class HttpRecoverableException
extends HttpException

Signals that an HTTP or HttpClient exception has occurred. This exception may have been caused by a transient error and the request may be retried. It may be possible to retrieve the underlying transient error via the inherited HttpException.getCause() method.

Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
Unascribed
See Also:
Serialized Form

Constructor Summary
HttpRecoverableException()
          Deprecated. Creates a new HttpRecoverableException with a null detail message.
HttpRecoverableException(String message)
          Deprecated. Creates a new HttpRecoverableException with the specified detail message.
 
Method Summary
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

HttpRecoverableException

public HttpRecoverableException()
Deprecated. 
Creates a new HttpRecoverableException with a null detail message.


HttpRecoverableException

public HttpRecoverableException(String message)
Deprecated. 
Creates a new HttpRecoverableException with the specified detail message.

Parameters:
message - exception message


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpState.html100644 0 0 167027 10661532627 25441 0ustar 0 0 HttpState (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpState

java.lang.Object
  extended by org.apache.commons.httpclient.HttpState

public class HttpState
extends Object

A container for HTTP attributes that may persist from request to request, such as cookies and authentication credentials.

Version:
$Revision: 561099 $ $Date: 2007-07-30 21:41:17 +0200 (Mon, 30 Jul 2007) $
Author:
Remy Maucherat, Rodney Waldhoff, Jeff Dever, Sean C. Sullivan, Michael Becke, Oleg Kalnichevski, Mike Bowler, Adrian Sutton

Field Summary
protected  ArrayList cookies
          Array of cookies that this HTTP state contains.
protected  HashMap credMap
          Map of credentials by realm that this HTTP state contains.
static String PREEMPTIVE_DEFAULT
          Deprecated. This field and feature will be removed following HttpClient 3.0.
static String PREEMPTIVE_PROPERTY
          Deprecated. This field and feature will be removed following HttpClient 3.0.
protected  HashMap proxyCred
          Map of proxy credentials by realm that this HTTP state contains
 
Constructor Summary
HttpState()
          Default constructor.
 
Method Summary
 void addCookie(Cookie cookie)
          Adds an HTTP cookie, replacing any existing equivalent cookies.
 void addCookies(Cookie[] cookies)
          Adds an array of HTTP cookies.
 void clear()
          Clears the state information (all cookies, credentials and proxy credentials).
 void clearCookies()
          Clears all cookies.
 void clearCredentials()
          Clears all credentials.
 void clearProxyCredentials()
          Clears all proxy credentials.
 int getCookiePolicy()
          Deprecated. Use HttpMethodParams.getCookiePolicy(), HttpMethod.getParams().
 Cookie[] getCookies()
          Returns an array of cookies that this HTTP state currently contains.
 Cookie[] getCookies(String domain, int port, String path, boolean secure)
          Deprecated. use CookieSpec#match(String, int, String, boolean, Cookie)
 Credentials getCredentials(AuthScope authscope)
          Get the credentials for the given authentication scope.
 Credentials getCredentials(String realm, String host)
          Deprecated. use #getCredentials(AuthScope)
 Credentials getProxyCredentials(AuthScope authscope)
          Get the proxy credentials for the given authentication scope.
 Credentials getProxyCredentials(String realm, String proxyHost)
          Deprecated. use #getProxyCredentials(AuthScope)
 boolean isAuthenticationPreemptive()
          Deprecated. Use HttpClientParams.isAuthenticationPreemptive(), HttpClient.getParams().
 boolean purgeExpiredCookies()
          Removes all of cookies in this HTTP state that have expired according to the current system time.
 boolean purgeExpiredCookies(Date date)
          Removes all of cookies in this HTTP state that have expired by the specified date.
 void setAuthenticationPreemptive(boolean value)
          Deprecated. Use HttpClientParams.setAuthenticationPreemptive(boolean), HttpClient.getParams().
 void setCookiePolicy(int policy)
          Deprecated. Use HttpMethodParams.setCookiePolicy(String), HttpMethod.getParams().
 void setCredentials(AuthScope authscope, Credentials credentials)
          Sets the credentials for the given authentication scope.
 void setCredentials(String realm, String host, Credentials credentials)
          Deprecated. use #setCredentials(AuthScope, Credentials)
 void setProxyCredentials(AuthScope authscope, Credentials credentials)
          Sets the proxy credentials for the given authentication realm.
 void setProxyCredentials(String realm, String proxyHost, Credentials credentials)
          Deprecated. use #setProxyCredentials(AuthScope, Credentials)
 String toString()
          Returns a string representation of this HTTP state.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

credMap

protected HashMap credMap
Map of credentials by realm that this HTTP state contains.


proxyCred

protected HashMap proxyCred
Map of proxy credentials by realm that this HTTP state contains


cookies

protected ArrayList cookies
Array of cookies that this HTTP state contains.


PREEMPTIVE_PROPERTY

public static final String PREEMPTIVE_PROPERTY
Deprecated. This field and feature will be removed following HttpClient 3.0.
The boolean system property name to turn on preemptive authentication.

See Also:
Constant Field Values

PREEMPTIVE_DEFAULT

public static final String PREEMPTIVE_DEFAULT
Deprecated. This field and feature will be removed following HttpClient 3.0.
The default value for PREEMPTIVE_PROPERTY.

See Also:
Constant Field Values
Constructor Detail

HttpState

public HttpState()
Default constructor.

Method Detail

addCookie

public void addCookie(Cookie cookie)
Adds an HTTP cookie, replacing any existing equivalent cookies. If the given cookie has already expired it will not be added, but existing values will still be removed.

Parameters:
cookie - the cookie to be added
See Also:
addCookies(Cookie[])

addCookies

public void addCookies(Cookie[] cookies)
Adds an array of HTTP cookies. Cookies are added individually and in the given array order. If any of the given cookies has already expired it will not be added, but existing values will still be removed.

Parameters:
cookies - the cookies to be added
See Also:
addCookie(Cookie)

getCookies

public Cookie[] getCookies()
Returns an array of cookies that this HTTP state currently contains.

Returns:
an array of cookies.
See Also:
getCookies(String, int, String, boolean)

getCookies

public Cookie[] getCookies(String domain,
                           int port,
                           String path,
                           boolean secure)
Deprecated. use CookieSpec#match(String, int, String, boolean, Cookie)

Returns an array of cookies in this HTTP state that match the given request parameters.

Parameters:
domain - the request domain
port - the request port
path - the request path
secure - true when using HTTPS
Returns:
an array of cookies.
See Also:
getCookies()

purgeExpiredCookies

public boolean purgeExpiredCookies()
Removes all of cookies in this HTTP state that have expired according to the current system time.

See Also:
purgeExpiredCookies(java.util.Date)

purgeExpiredCookies

public boolean purgeExpiredCookies(Date date)
Removes all of cookies in this HTTP state that have expired by the specified date.

Parameters:
date - The date to compare against.
Returns:
true if any cookies were purged.
See Also:
Cookie.isExpired(java.util.Date), purgeExpiredCookies()

getCookiePolicy

public int getCookiePolicy()
Deprecated. Use HttpMethodParams.getCookiePolicy(), HttpMethod.getParams().

Returns the current cookie policy for this HTTP state.

Returns:
The cookie policy.

setAuthenticationPreemptive

public void setAuthenticationPreemptive(boolean value)
Deprecated. Use HttpClientParams.setAuthenticationPreemptive(boolean), HttpClient.getParams().

Defines whether preemptive authentication should be attempted.

Parameters:
value - true if preemptive authentication should be attempted, false otherwise.

isAuthenticationPreemptive

public boolean isAuthenticationPreemptive()
Deprecated. Use HttpClientParams.isAuthenticationPreemptive(), HttpClient.getParams().

Returns true if preemptive authentication should be attempted, false otherwise.

Returns:
boolean flag.

setCookiePolicy

public void setCookiePolicy(int policy)
Deprecated. Use HttpMethodParams.setCookiePolicy(String), HttpMethod.getParams().

Sets the current cookie policy for this HTTP state to one of the following supported policies: CookiePolicy.COMPATIBILITY, CookiePolicy.NETSCAPE_DRAFT or CookiePolicy.RFC2109.

Parameters:
policy - new cookie policy

setCredentials

public void setCredentials(String realm,
                           String host,
                           Credentials credentials)
Deprecated. use #setCredentials(AuthScope, Credentials)

Sets the credentials for the given authentication realm on the given host. The null realm signifies default credentials for the given host, which should be used when no credentials have been explictly supplied for the challenging realm. The null host signifies default credentials, which should be used when no credentials have been explictly supplied for the challenging host. Any previous credentials for the given realm on the given host will be overwritten.

Parameters:
realm - the authentication realm
host - the host the realm belongs to
credentials - the authentication credentials for the given realm.
See Also:
getCredentials(String, String), setProxyCredentials(String, String, Credentials)

setCredentials

public void setCredentials(AuthScope authscope,
                           Credentials credentials)
Sets the credentials for the given authentication scope. Any previous credentials for the given scope will be overwritten.

Parameters:
authscope - the authentication scope
credentials - the authentication credentials for the given scope.
Since:
3.0
See Also:
getCredentials(AuthScope), setProxyCredentials(AuthScope, Credentials)

getCredentials

public Credentials getCredentials(String realm,
                                  String host)
Deprecated. use #getCredentials(AuthScope)

Get the credentials for the given authentication scope on the given host. If the realm exists on host, return the coresponding credentials. If the host exists with a null realm, return the corresponding credentials. If the realm exists with a null host, return the corresponding credentials. If the realm does not exist, return the default Credentials. If there are no default credentials, return null.

Parameters:
realm - the authentication realm
host - the host the realm is on
Returns:
the credentials
See Also:
setCredentials(String, String, Credentials)

getCredentials

public Credentials getCredentials(AuthScope authscope)
Get the credentials for the given authentication scope.

Parameters:
authscope - the authentication scope
Returns:
the credentials
Since:
3.0
See Also:
setCredentials(AuthScope, Credentials)

setProxyCredentials

public void setProxyCredentials(String realm,
                                String proxyHost,
                                Credentials credentials)
Deprecated. use #setProxyCredentials(AuthScope, Credentials)

Sets the credentials for the given proxy authentication realm on the given proxy host. The null proxy realm signifies default credentials for the given proxy host, which should be used when no credentials have been explictly supplied for the challenging proxy realm. The null proxy host signifies default credentials, which should be used when no credentials have been explictly supplied for the challenging proxy host. Any previous credentials for the given proxy realm on the given proxy host will be overwritten.

Parameters:
realm - the authentication realm
proxyHost - the proxy host
credentials - the authentication credentials for the given realm
See Also:
getProxyCredentials(AuthScope), setCredentials(AuthScope, Credentials)

setProxyCredentials

public void setProxyCredentials(AuthScope authscope,
                                Credentials credentials)
Sets the proxy credentials for the given authentication realm. Any previous credentials for the given realm will be overwritten.

Parameters:
authscope - the authentication scope
credentials - the authentication credentials for the given realm.
Since:
3.0
See Also:
getProxyCredentials(AuthScope), setCredentials(AuthScope, Credentials)

getProxyCredentials

public Credentials getProxyCredentials(String realm,
                                       String proxyHost)
Deprecated. use #getProxyCredentials(AuthScope)

Get the credentials for the proxy host with the given authentication scope. If the realm exists on host, return the coresponding credentials. If the host exists with a null realm, return the corresponding credentials. If the realm exists with a null host, return the corresponding credentials. If the realm does not exist, return the default Credentials. If there are no default credentials, return null.

Parameters:
realm - the authentication realm
proxyHost - the proxy host the realm is on
Returns:
the credentials
See Also:
setProxyCredentials(String, String, Credentials)

getProxyCredentials

public Credentials getProxyCredentials(AuthScope authscope)
Get the proxy credentials for the given authentication scope.

Parameters:
authscope - the authentication scope
Returns:
the credentials
Since:
3.0
See Also:
setProxyCredentials(AuthScope, Credentials)

toString

public String toString()
Returns a string representation of this HTTP state.

Overrides:
toString in class Object
Returns:
The string representation of the HTTP state.
See Also:
Object.toString()

clearCredentials

public void clearCredentials()
Clears all credentials.


clearProxyCredentials

public void clearProxyCredentials()
Clears all proxy credentials.


clearCookies

public void clearCookies()
Clears all cookies.


clear

public void clear()
Clears the state information (all cookies, credentials and proxy credentials).



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpStatus.html100644 0 0 144411 10661532627 25634 0ustar 0 0 HttpStatus (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpStatus

java.lang.Object
  extended by org.apache.commons.httpclient.HttpStatus

public class HttpStatus
extends Object

Constants enumerating the HTTP status codes. All status codes defined in RFC1945 (HTTP/1.0, RFC2616 (HTTP/1.1), and RFC2518 (WebDAV) are supported.

Version:
$Id: HttpStatus.java 480424 2006-11-29 05:56:49Z bayard $
Author:
Unascribed, Mike Bowler, Jeff Dever TODO: Internationalization of reason phrases
See Also:
StatusLine

Field Summary
static int SC_ACCEPTED
          202 Accepted (HTTP/1.0 - RFC 1945)
static int SC_BAD_GATEWAY
          502 Bad Gateway (HTTP/1.0 - RFC 1945)
static int SC_BAD_REQUEST
          400 Bad Request (HTTP/1.1 - RFC 2616)
static int SC_CONFLICT
          409 Conflict (HTTP/1.1 - RFC 2616)
static int SC_CONTINUE
          100 Continue (HTTP/1.1 - RFC 2616)
static int SC_CREATED
          201 Created (HTTP/1.0 - RFC 1945)
static int SC_EXPECTATION_FAILED
          417 Expectation Failed (HTTP/1.1 - RFC 2616)
static int SC_FAILED_DEPENDENCY
          424 Failed Dependency (WebDAV - RFC 2518)
static int SC_FORBIDDEN
          403 Forbidden (HTTP/1.0 - RFC 1945)
static int SC_GATEWAY_TIMEOUT
          504 Gateway Timeout (HTTP/1.1 - RFC 2616)
static int SC_GONE
          410 Gone (HTTP/1.1 - RFC 2616)
static int SC_HTTP_VERSION_NOT_SUPPORTED
          505 HTTP Version Not Supported (HTTP/1.1 - RFC 2616)
static int SC_INSUFFICIENT_SPACE_ON_RESOURCE
          Static constant for a 419 error.
static int SC_INSUFFICIENT_STORAGE
          507 Insufficient Storage (WebDAV - RFC 2518)
static int SC_INTERNAL_SERVER_ERROR
          500 Server Error (HTTP/1.0 - RFC 1945)
static int SC_LENGTH_REQUIRED
          411 Length Required (HTTP/1.1 - RFC 2616)
static int SC_LOCKED
          423 Locked (WebDAV - RFC 2518)
static int SC_METHOD_FAILURE
          Static constant for a 420 error.
static int SC_METHOD_NOT_ALLOWED
          405 Method Not Allowed (HTTP/1.1 - RFC 2616)
static int SC_MOVED_PERMANENTLY
          301 Moved Permanently (HTTP/1.0 - RFC 1945)
static int SC_MOVED_TEMPORARILY
          302 Moved Temporarily (Sometimes Found) (HTTP/1.0 - RFC 1945)
static int SC_MULTI_STATUS
          207 Multi-Status (WebDAV - RFC 2518) or 207 Partial Update OK (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?)
static int SC_MULTIPLE_CHOICES
          300 Mutliple Choices (HTTP/1.1 - RFC 2616)
static int SC_NO_CONTENT
          204 No Content (HTTP/1.0 - RFC 1945)
static int SC_NON_AUTHORITATIVE_INFORMATION
          203 Non Authoritative Information (HTTP/1.1 - RFC 2616)
static int SC_NOT_ACCEPTABLE
          406 Not Acceptable (HTTP/1.1 - RFC 2616)
static int SC_NOT_FOUND
          404 Not Found (HTTP/1.0 - RFC 1945)
static int SC_NOT_IMPLEMENTED
          501 Not Implemented (HTTP/1.0 - RFC 1945)
static int SC_NOT_MODIFIED
          304 Not Modified (HTTP/1.0 - RFC 1945)
static int SC_OK
          200 OK (HTTP/1.0 - RFC 1945)
static int SC_PARTIAL_CONTENT
          206 Partial Content (HTTP/1.1 - RFC 2616)
static int SC_PAYMENT_REQUIRED
          402 Payment Required (HTTP/1.1 - RFC 2616)
static int SC_PRECONDITION_FAILED
          412 Precondition Failed (HTTP/1.1 - RFC 2616)
static int SC_PROCESSING
          102 Processing (WebDAV - RFC 2518)
static int SC_PROXY_AUTHENTICATION_REQUIRED
          407 Proxy Authentication Required (HTTP/1.1 - RFC 2616)
static int SC_REQUEST_TIMEOUT
          408 Request Timeout (HTTP/1.1 - RFC 2616)
static int SC_REQUEST_TOO_LONG
          413 Request Entity Too Large (HTTP/1.1 - RFC 2616)
static int SC_REQUEST_URI_TOO_LONG
          414 Request-URI Too Long (HTTP/1.1 - RFC 2616)
static int SC_REQUESTED_RANGE_NOT_SATISFIABLE
          416 Requested Range Not Satisfiable (HTTP/1.1 - RFC 2616)
static int SC_RESET_CONTENT
          205 Reset Content (HTTP/1.1 - RFC 2616)
static int SC_SEE_OTHER
          303 See Other (HTTP/1.1 - RFC 2616)
static int SC_SERVICE_UNAVAILABLE
          503 Service Unavailable (HTTP/1.0 - RFC 1945)
static int SC_SWITCHING_PROTOCOLS
          101 Switching Protocols (HTTP/1.1 - RFC 2616)
static int SC_TEMPORARY_REDIRECT
          307 Temporary Redirect (HTTP/1.1 - RFC 2616)
static int SC_UNAUTHORIZED
          401 Unauthorized (HTTP/1.0 - RFC 1945)
static int SC_UNPROCESSABLE_ENTITY
          422 Unprocessable Entity (WebDAV - RFC 2518)
static int SC_UNSUPPORTED_MEDIA_TYPE
          415 Unsupported Media Type (HTTP/1.1 - RFC 2616)
static int SC_USE_PROXY
          305 Use Proxy (HTTP/1.1 - RFC 2616)
 
Constructor Summary
HttpStatus()
           
 
Method Summary
static String getStatusText(int statusCode)
          Get the reason phrase for a particular status code.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SC_CONTINUE

public static final int SC_CONTINUE
100 Continue (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_SWITCHING_PROTOCOLS

public static final int SC_SWITCHING_PROTOCOLS
101 Switching Protocols (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_PROCESSING

public static final int SC_PROCESSING
102 Processing (WebDAV - RFC 2518)

See Also:
Constant Field Values

SC_OK

public static final int SC_OK
200 OK (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_CREATED

public static final int SC_CREATED
201 Created (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_ACCEPTED

public static final int SC_ACCEPTED
202 Accepted (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_NON_AUTHORITATIVE_INFORMATION

public static final int SC_NON_AUTHORITATIVE_INFORMATION
203 Non Authoritative Information (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_NO_CONTENT

public static final int SC_NO_CONTENT
204 No Content (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_RESET_CONTENT

public static final int SC_RESET_CONTENT
205 Reset Content (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_PARTIAL_CONTENT

public static final int SC_PARTIAL_CONTENT
206 Partial Content (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_MULTI_STATUS

public static final int SC_MULTI_STATUS
207 Multi-Status (WebDAV - RFC 2518) or 207 Partial Update OK (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?)

See Also:
Constant Field Values

SC_MULTIPLE_CHOICES

public static final int SC_MULTIPLE_CHOICES
300 Mutliple Choices (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_MOVED_PERMANENTLY

public static final int SC_MOVED_PERMANENTLY
301 Moved Permanently (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_MOVED_TEMPORARILY

public static final int SC_MOVED_TEMPORARILY
302 Moved Temporarily (Sometimes Found) (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_SEE_OTHER

public static final int SC_SEE_OTHER
303 See Other (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_NOT_MODIFIED

public static final int SC_NOT_MODIFIED
304 Not Modified (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_USE_PROXY

public static final int SC_USE_PROXY
305 Use Proxy (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_TEMPORARY_REDIRECT

public static final int SC_TEMPORARY_REDIRECT
307 Temporary Redirect (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_BAD_REQUEST

public static final int SC_BAD_REQUEST
400 Bad Request (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_UNAUTHORIZED

public static final int SC_UNAUTHORIZED
401 Unauthorized (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_PAYMENT_REQUIRED

public static final int SC_PAYMENT_REQUIRED
402 Payment Required (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_FORBIDDEN

public static final int SC_FORBIDDEN
403 Forbidden (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_NOT_FOUND

public static final int SC_NOT_FOUND
404 Not Found (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_METHOD_NOT_ALLOWED

public static final int SC_METHOD_NOT_ALLOWED
405 Method Not Allowed (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_NOT_ACCEPTABLE

public static final int SC_NOT_ACCEPTABLE
406 Not Acceptable (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_PROXY_AUTHENTICATION_REQUIRED

public static final int SC_PROXY_AUTHENTICATION_REQUIRED
407 Proxy Authentication Required (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_REQUEST_TIMEOUT

public static final int SC_REQUEST_TIMEOUT
408 Request Timeout (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_CONFLICT

public static final int SC_CONFLICT
409 Conflict (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_GONE

public static final int SC_GONE
410 Gone (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_LENGTH_REQUIRED

public static final int SC_LENGTH_REQUIRED
411 Length Required (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_PRECONDITION_FAILED

public static final int SC_PRECONDITION_FAILED
412 Precondition Failed (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_REQUEST_TOO_LONG

public static final int SC_REQUEST_TOO_LONG
413 Request Entity Too Large (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_REQUEST_URI_TOO_LONG

public static final int SC_REQUEST_URI_TOO_LONG
414 Request-URI Too Long (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_UNSUPPORTED_MEDIA_TYPE

public static final int SC_UNSUPPORTED_MEDIA_TYPE
415 Unsupported Media Type (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_REQUESTED_RANGE_NOT_SATISFIABLE

public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE
416 Requested Range Not Satisfiable (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_EXPECTATION_FAILED

public static final int SC_EXPECTATION_FAILED
417 Expectation Failed (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_INSUFFICIENT_SPACE_ON_RESOURCE

public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE
Static constant for a 419 error. 419 Insufficient Space on Resource (WebDAV - draft-ietf-webdav-protocol-05?) or 419 Proxy Reauthentication Required (HTTP/1.1 drafts?)

See Also:
Constant Field Values

SC_METHOD_FAILURE

public static final int SC_METHOD_FAILURE
Static constant for a 420 error. 420 Method Failure (WebDAV - draft-ietf-webdav-protocol-05?)

See Also:
Constant Field Values

SC_UNPROCESSABLE_ENTITY

public static final int SC_UNPROCESSABLE_ENTITY
422 Unprocessable Entity (WebDAV - RFC 2518)

See Also:
Constant Field Values

SC_LOCKED

public static final int SC_LOCKED
423 Locked (WebDAV - RFC 2518)

See Also:
Constant Field Values

SC_FAILED_DEPENDENCY

public static final int SC_FAILED_DEPENDENCY
424 Failed Dependency (WebDAV - RFC 2518)

See Also:
Constant Field Values

SC_INTERNAL_SERVER_ERROR

public static final int SC_INTERNAL_SERVER_ERROR
500 Server Error (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_NOT_IMPLEMENTED

public static final int SC_NOT_IMPLEMENTED
501 Not Implemented (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_BAD_GATEWAY

public static final int SC_BAD_GATEWAY
502 Bad Gateway (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_SERVICE_UNAVAILABLE

public static final int SC_SERVICE_UNAVAILABLE
503 Service Unavailable (HTTP/1.0 - RFC 1945)

See Also:
Constant Field Values

SC_GATEWAY_TIMEOUT

public static final int SC_GATEWAY_TIMEOUT
504 Gateway Timeout (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_HTTP_VERSION_NOT_SUPPORTED

public static final int SC_HTTP_VERSION_NOT_SUPPORTED
505 HTTP Version Not Supported (HTTP/1.1 - RFC 2616)

See Also:
Constant Field Values

SC_INSUFFICIENT_STORAGE

public static final int SC_INSUFFICIENT_STORAGE
507 Insufficient Storage (WebDAV - RFC 2518)

See Also:
Constant Field Values
Constructor Detail

HttpStatus

public HttpStatus()
Method Detail

getStatusText

public static String getStatusText(int statusCode)
Get the reason phrase for a particular status code. This method always returns the English text as specified in the relevent RFCs and is not internationalized.

Parameters:
statusCode - the numeric status code
Returns:
the reason phrase associated with the given status code or null if the status code is not recognized. TODO: getStatusText should be called getReasonPhrase to match RFC


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpURL.html100644 0 0 334450 10661532627 25017 0ustar 0 0 HttpURL (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpURL

java.lang.Object
  extended by org.apache.commons.httpclient.URI
      extended by org.apache.commons.httpclient.HttpURL
All Implemented Interfaces:
Serializable, Cloneable, Comparable
Direct Known Subclasses:
HttpsURL

public class HttpURL
extends URI

The HTTP URL.

Author:
Sung-Gu, Mike Bowler
See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class org.apache.commons.httpclient.URI
URI.DefaultCharsetChanged, URI.LocaleToCharsetMap
 
Field Summary
static int _default_port
          Deprecated. Use DEFAULT_PORT instead. This one doesn't conform to the project naming conventions.
static char[] _default_scheme
          Deprecated. Use DEFAULT_SCHEME instead. This one doesn't conform to the project naming conventions.
static int DEFAULT_PORT
          Default port for HTTP URL.
static char[] DEFAULT_SCHEME
          Default scheme for HTTP URL.
 
Fields inherited from class org.apache.commons.httpclient.URI
_authority, _fragment, _host, _is_abs_path, _is_hier_part, _is_hostname, _is_IPv4address, _is_IPv6reference, _is_net_path, _is_opaque_part, _is_reg_name, _is_rel_path, _is_server, _opaque, _path, _port, _query, _scheme, _uri, _userinfo, abs_path, absoluteURI, allowed_abs_path, allowed_authority, allowed_fragment, allowed_host, allowed_IPv6reference, allowed_opaque_part, allowed_query, allowed_reg_name, allowed_rel_path, allowed_userinfo, allowed_within_authority, allowed_within_path, allowed_within_query, allowed_within_userinfo, alpha, alphanum, authority, control, defaultDocumentCharset, defaultDocumentCharsetByLocale, defaultDocumentCharsetByPlatform, defaultProtocolCharset, delims, digit, disallowed_opaque_part, disallowed_rel_path, domainlabel, escaped, fragment, hash, hex, hier_part, host, hostname, hostport, IPv4address, IPv6address, IPv6reference, mark, net_path, opaque_part, param, path, path_segments, pchar, percent, port, protocolCharset, query, reg_name, rel_path, rel_segment, relativeURI, reserved, rootPath, scheme, segment, server, space, toplabel, unreserved, unwise, URI_reference, uric, uric_no_slash, userinfo, within_userinfo
 
Constructor Summary
protected HttpURL()
          Create an instance as an internal use.
  HttpURL(char[] escaped)
          Construct a HTTP URL as an escaped form of a character array.
  HttpURL(char[] escaped, String charset)
          Construct a HTTP URL as an escaped form of a character array with the given charset to do escape encoding.
  HttpURL(HttpURL base, HttpURL relative)
          Construct a HTTP URL with a given relative URL.
  HttpURL(HttpURL base, String relative)
          Construct a HTTP URL with a given relative URL string.
  HttpURL(String original)
          Construct a HTTP URL from a given string.
  HttpURL(String host, int port, String path)
          Construct a HTTP URL from given components.
  HttpURL(String host, int port, String path, String query)
          Construct a HTTP URL from given components.
  HttpURL(String original, String charset)
          Construct a HTTP URL from a given string with the given charset to do escape encoding.
  HttpURL(String userinfo, String host, int port, String path)
          Construct a HTTP URL from given components.
  HttpURL(String userinfo, String host, int port, String path, String query)
          Construct a HTTP URL from given components.
  HttpURL(String userinfo, String host, int port, String path, String query, String fragment)
          Construct a HTTP URL from given components.
  HttpURL(String user, String password, String host)
          Construct a HTTP URL from given components.
  HttpURL(String user, String password, String host, int port)
          Construct a HTTP URL from given components.
  HttpURL(String user, String password, String host, int port, String path)
          Construct a HTTP URL from given components.
  HttpURL(String user, String password, String host, int port, String path, String query)
          Construct a HTTP URL from given components.
  HttpURL(String user, String password, String host, int port, String path, String query, String fragment)
          Construct a HTTP URL from given components.
  HttpURL(String host, String path, String query, String fragment)
          Construct a HTTP URL from given components.
  HttpURL(String userinfo, String host, String path, String query, String fragment)
          Construct a HTTP URL from given components.
 
Method Summary
protected  void checkValid()
          Verify the valid class use for construction.
 String getEscapedPassword()
          Get the escaped password.
 String getEscapedUser()
          Get the escaped user
 String getPassword()
          Get the password.
 int getPort()
          Get the port number.
 char[] getRawAboveHierPath()
          Get the level above the this hierarchy level.
 char[] getRawCurrentHierPath()
          Get the raw-escaped current hierarchy level.
 char[] getRawPassword()
          Get the raw-escaped password.
 char[] getRawPath()
          Get the raw escaped path.
 char[] getRawScheme()
          Get the scheme.
 char[] getRawUser()
          Get the raw-escaped user.
 String getScheme()
          Get the scheme.
 String getUser()
          Get the user.
 void setEscapedPassword(String escapedPassword)
          Set the escaped password string.
 void setEscapedUser(String escapedUser)
          Set the escaped user string.
 void setEscapedUserinfo(String escapedUser, String escapedPassword)
          Set the raw-escaped user and password.
 void setPassword(String password)
          Set the password string.
 void setQuery(String[] queryName, String[] queryValue)
          Set the query as the name and value pairs.
 void setQuery(String queryName, String queryValue)
          Set the query as the name and value pair.
 void setRawPassword(char[] escapedPassword)
          Set the raw-escaped password.
 void setRawUser(char[] escapedUser)
          Set the raw-escaped user.
 void setRawUserinfo(char[] escapedUser, char[] escapedPassword)
          Set the raw-escaped user and password.
protected  void setURI()
          Once it's parsed successfully, set this URI.
 void setUser(String user)
          Set the user string.
 void setUserinfo(String user, String password)
          Set the user and password.
protected static String toUserinfo(String user, String password)
           
 
Methods inherited from class org.apache.commons.httpclient.URI
clone, compareTo, decode, decode, encode, equals, equals, getAboveHierPath, getAuthority, getCurrentHierPath, getDefaultDocumentCharset, getDefaultDocumentCharsetByLocale, getDefaultDocumentCharsetByPlatform, getDefaultProtocolCharset, getEscapedAboveHierPath, getEscapedAuthority, getEscapedCurrentHierPath, getEscapedFragment, getEscapedName, getEscapedPath, getEscapedPathQuery, getEscapedQuery, getEscapedURI, getEscapedURIReference, getEscapedUserinfo, getFragment, getHost, getName, getPath, getPathQuery, getProtocolCharset, getQuery, getRawAuthority, getRawCurrentHierPath, getRawFragment, getRawHost, getRawName, getRawPathQuery, getRawQuery, getRawURI, getRawURIReference, getRawUserinfo, getURI, getURIReference, getUserinfo, hasAuthority, hasFragment, hashCode, hasQuery, hasUserinfo, indexFirstOf, indexFirstOf, indexFirstOf, indexFirstOf, isAbsoluteURI, isAbsPath, isHierPart, isHostname, isIPv4address, isIPv6reference, isNetPath, isOpaquePart, isRegName, isRelativeURI, isRelPath, isServer, normalize, normalize, parseAuthority, parseUriReference, prevalidate, removeFragmentIdentifier, resolvePath, setDefaultDocumentCharset, setDefaultProtocolCharset, setEscapedAuthority, setEscapedFragment, setEscapedPath, setEscapedQuery, setFragment, setPath, setQuery, setRawAuthority, setRawFragment, setRawPath, setRawQuery, toString, validate, validate
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

DEFAULT_SCHEME

public static final char[] DEFAULT_SCHEME
Default scheme for HTTP URL.


_default_scheme

public static final char[] _default_scheme
Deprecated. Use DEFAULT_SCHEME instead. This one doesn't conform to the project naming conventions.
Default scheme for HTTP URL.


DEFAULT_PORT

public static final int DEFAULT_PORT
Default port for HTTP URL.

See Also:
Constant Field Values

_default_port

public static final int _default_port
Deprecated. Use DEFAULT_PORT instead. This one doesn't conform to the project naming conventions.
Default port for HTTP URL.

See Also:
Constant Field Values
Constructor Detail

HttpURL

protected HttpURL()
Create an instance as an internal use.


HttpURL

public HttpURL(char[] escaped,
               String charset)
        throws URIException,
               NullPointerException
Construct a HTTP URL as an escaped form of a character array with the given charset to do escape encoding.

Parameters:
escaped - the HTTP URL character sequence
charset - the charset string to do escape encoding
Throws:
URIException - If checkValid() fails
NullPointerException - if escaped is null
See Also:
URI.getProtocolCharset()

HttpURL

public HttpURL(char[] escaped)
        throws URIException,
               NullPointerException
Construct a HTTP URL as an escaped form of a character array.

Parameters:
escaped - the HTTP URL character sequence
Throws:
URIException - If checkValid() fails
NullPointerException - if escaped is null
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String original,
               String charset)
        throws URIException
Construct a HTTP URL from a given string with the given charset to do escape encoding.

Parameters:
original - the HTTP URL string
charset - the charset string to do escape encoding
Throws:
URIException - If checkValid() fails
See Also:
URI.getProtocolCharset()

HttpURL

public HttpURL(String original)
        throws URIException
Construct a HTTP URL from a given string.

Parameters:
original - the HTTP URL string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String host,
               int port,
               String path)
        throws URIException
Construct a HTTP URL from given components.

Parameters:
host - the host string
port - the port number
path - the path string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String host,
               int port,
               String path,
               String query)
        throws URIException
Construct a HTTP URL from given components.

Parameters:
host - the host string
port - the port number
path - the path string
query - the query string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String user,
               String password,
               String host)
        throws URIException
Construct a HTTP URL from given components.

Parameters:
user - the user name
password - his or her password
host - the host string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String user,
               String password,
               String host,
               int port)
        throws URIException
Construct a HTTP URL from given components.

Parameters:
user - the user name
password - his or her password
host - the host string
port - the port number
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String user,
               String password,
               String host,
               int port,
               String path)
        throws URIException
Construct a HTTP URL from given components.

Parameters:
user - the user name
password - his or her password
host - the host string
port - the port number
path - the path string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String user,
               String password,
               String host,
               int port,
               String path,
               String query)
        throws URIException
Construct a HTTP URL from given components.

Parameters:
user - the user name
password - his or her password
host - the host string
port - the port number
path - the path string
query - The query string.
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String host,
               String path,
               String query,
               String fragment)
        throws URIException
Construct a HTTP URL from given components.

Parameters:
host - the host string
path - the path string
query - the query string
fragment - the fragment string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String userinfo,
               String host,
               String path,
               String query,
               String fragment)
        throws URIException
Construct a HTTP URL from given components. Note: The userinfo format is normally <username>:<password> where username and password must both be URL escaped.

Parameters:
userinfo - the userinfo string whose parts are URL escaped
host - the host string
path - the path string
query - the query string
fragment - the fragment string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String userinfo,
               String host,
               int port,
               String path)
        throws URIException
Construct a HTTP URL from given components. Note: The userinfo format is normally <username>:<password> where username and password must both be URL escaped.

Parameters:
userinfo - the userinfo string whose parts are URL escaped
host - the host string
port - the port number
path - the path string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String userinfo,
               String host,
               int port,
               String path,
               String query)
        throws URIException
Construct a HTTP URL from given components. Note: The userinfo format is normally <username>:<password> where username and password must both be URL escaped.

Parameters:
userinfo - the userinfo string whose parts are URL escaped
host - the host string
port - the port number
path - the path string
query - the query string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String userinfo,
               String host,
               int port,
               String path,
               String query,
               String fragment)
        throws URIException
Construct a HTTP URL from given components. Note: The userinfo format is normally <username>:<password> where username and password must both be URL escaped.

Parameters:
userinfo - the userinfo string whose parts are URL escaped
host - the host string
port - the port number
path - the path string
query - the query string
fragment - the fragment string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(String user,
               String password,
               String host,
               int port,
               String path,
               String query,
               String fragment)
        throws URIException
Construct a HTTP URL from given components.

Parameters:
user - the user name
password - his or her password
host - the host string
port - the port number
path - the path string
query - the query string
fragment - the fragment string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpURL

public HttpURL(HttpURL base,
               String relative)
        throws URIException
Construct a HTTP URL with a given relative URL string.

Parameters:
base - the base HttpURL
relative - the relative HTTP URL string
Throws:
URIException - If checkValid() fails

HttpURL

public HttpURL(HttpURL base,
               HttpURL relative)
        throws URIException
Construct a HTTP URL with a given relative URL.

Parameters:
base - the base HttpURL
relative - the relative HttpURL
Throws:
URIException - If checkValid() fails
Method Detail

toUserinfo

protected static String toUserinfo(String user,
                                   String password)
                            throws URIException
Throws:
URIException

getRawScheme

public char[] getRawScheme()
Get the scheme. You can get the scheme explicitly.

Overrides:
getRawScheme in class URI
Returns:
the scheme

getScheme

public String getScheme()
Get the scheme. You can get the scheme explicitly.

Overrides:
getScheme in class URI
Returns:
the scheme null if empty or undefined

getPort

public int getPort()
Get the port number.

Overrides:
getPort in class URI
Returns:
the port number

setRawUserinfo

public void setRawUserinfo(char[] escapedUser,
                           char[] escapedPassword)
                    throws URIException
Set the raw-escaped user and password.

Parameters:
escapedUser - the raw-escaped user
escapedPassword - the raw-escaped password; could be null
Throws:
URIException - escaped user not valid or user required; escaped password not valid or username missed

setEscapedUserinfo

public void setEscapedUserinfo(String escapedUser,
                               String escapedPassword)
                        throws URIException,
                               NullPointerException
Set the raw-escaped user and password.

Parameters:
escapedUser - the escaped user
escapedPassword - the escaped password; could be null
Throws:
URIException - escaped user not valid or user required; escaped password not valid or username missed
NullPointerException - null user

setUserinfo

public void setUserinfo(String user,
                        String password)
                 throws URIException,
                        NullPointerException
Set the user and password.

Parameters:
user - the user
password - the password; could be null
Throws:
URIException - encoding error or username missed
NullPointerException - null user

setRawUser

public void setRawUser(char[] escapedUser)
                throws URIException
Set the raw-escaped user.

Parameters:
escapedUser - the raw-escaped user
Throws:
URIException - escaped user not valid or user required

setEscapedUser

public void setEscapedUser(String escapedUser)
                    throws URIException,
                           NullPointerException
Set the escaped user string.

Parameters:
escapedUser - the escaped user string
Throws:
URIException - escaped user not valid
NullPointerException - null user

setUser

public void setUser(String user)
             throws URIException,
                    NullPointerException
Set the user string.

Parameters:
user - the user string
Throws:
URIException - user encoding error
NullPointerException - null user

getRawUser

public char[] getRawUser()
Get the raw-escaped user.

Returns:
the raw-escaped user

getEscapedUser

public String getEscapedUser()
Get the escaped user

Returns:
the escaped user

getUser

public String getUser()
               throws URIException
Get the user.

Returns:
the user name
Throws:
URIException - If URI.decode(char[], java.lang.String) fails

setRawPassword

public void setRawPassword(char[] escapedPassword)
                    throws URIException
Set the raw-escaped password.

Parameters:
escapedPassword - the raw-escaped password; could be null
Throws:
URIException - escaped password not valid or username missed

setEscapedPassword

public void setEscapedPassword(String escapedPassword)
                        throws URIException
Set the escaped password string.

Parameters:
escapedPassword - the escaped password string; could be null
Throws:
URIException - escaped password not valid or username missed

setPassword

public void setPassword(String password)
                 throws URIException
Set the password string.

Parameters:
password - the password string; could be null
Throws:
URIException - encoding error or username missed

getRawPassword

public char[] getRawPassword()
Get the raw-escaped password.

Returns:
the raw-escaped password

getEscapedPassword

public String getEscapedPassword()
Get the escaped password.

Returns:
the escaped password

getPassword

public String getPassword()
                   throws URIException
Get the password.

Returns:
the password
Throws:
URIException - If URI.decode(char[],String) fails.

getRawCurrentHierPath

public char[] getRawCurrentHierPath()
                             throws URIException
Get the raw-escaped current hierarchy level.

Overrides:
getRawCurrentHierPath in class URI
Returns:
the raw-escaped current hierarchy level
Throws:
URIException - If URI.getRawCurrentHierPath(char[]) fails.

getRawAboveHierPath

public char[] getRawAboveHierPath()
                           throws URIException
Get the level above the this hierarchy level.

Overrides:
getRawAboveHierPath in class URI
Returns:
the raw above hierarchy level
Throws:
URIException - If URI.getRawCurrentHierPath(char[]) fails.

getRawPath

public char[] getRawPath()
Get the raw escaped path.

Overrides:
getRawPath in class URI
Returns:
the path '/' if empty or undefined

setQuery

public void setQuery(String queryName,
                     String queryValue)
              throws URIException,
                     NullPointerException
Set the query as the name and value pair.

Parameters:
queryName - the query string.
queryValue - the query string.
Throws:
URIException - incomplete trailing escape pattern Or unsupported character encoding
NullPointerException - null query
See Also:
URI.encode(java.lang.String, java.util.BitSet, java.lang.String)

setQuery

public void setQuery(String[] queryName,
                     String[] queryValue)
              throws URIException,
                     NullPointerException
Set the query as the name and value pairs.

Parameters:
queryName - the array of the query string.
queryValue - the array of the query string.
Throws:
URIException - incomplete trailing escape pattern, unsupported character encoding or wrong array size
NullPointerException - null query
See Also:
URI.encode(java.lang.String, java.util.BitSet, java.lang.String)

checkValid

protected void checkValid()
                   throws URIException
Verify the valid class use for construction.

Throws:
URIException - the wrong scheme use

setURI

protected void setURI()
Once it's parsed successfully, set this URI.

Overrides:
setURI in class URI
See Also:
URI.getRawURI()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpVersion.html100644 0 0 70611 10661532627 25756 0ustar 0 0 HttpVersion (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpVersion

java.lang.Object
  extended by org.apache.commons.httpclient.HttpVersion
All Implemented Interfaces:
Comparable

public class HttpVersion
extends Object
implements Comparable

HTTP version, as specified in RFC 2616.

HTTP uses a "<major>.<minor>" numbering scheme to indicate versions of the protocol. The protocol versioning policy is intended to allow the sender to indicate the format of a message and its capacity for understanding further HTTP communication, rather than the features obtained via that communication. No change is made to the version number for the addition of message components which do not affect communication behavior or which only add to extensible field values. The <minor> number is incremented when the changes made to the protocol add features which do not change the general message parsing algorithm, but which may add to the message semantics and imply additional capabilities of the sender. The <major> number is incremented when the format of a message within the protocol is changed. See RFC 2145 [36] for a fuller explanation.

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
  

Note that the major and minor numbers MUST be treated as separate integers and that each MAY be incremented higher than a single digit. Thus, HTTP/2.4 is a lower version than HTTP/2.13, which in turn is lower than HTTP/12.3. Leading zeros MUST be ignored by recipients and MUST NOT be sent.

Since:
3.0
Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
Oleg Kalnichevski

Field Summary
static HttpVersion HTTP_0_9
          HTTP protocol version 0.9
static HttpVersion HTTP_1_0
          HTTP protocol version 1.0
static HttpVersion HTTP_1_1
          HTTP protocol version 1.1
 
Constructor Summary
HttpVersion(int major, int minor)
          Create an HTTP protocol version designator.
 
Method Summary
 int compareTo(HttpVersion anotherVer)
          Compares this HTTP protocol version with another one.
 int compareTo(Object o)
           
 boolean equals(HttpVersion version)
          Test if the HTTP protocol version is equal to the given number.
 boolean equals(Object obj)
           
 int getMajor()
          Returns the major version number of the HTTP protocol.
 int getMinor()
          Returns the minor version number of the HTTP protocol.
 boolean greaterEquals(HttpVersion version)
          Test if the HTTP protocol version is greater or equal to the given number.
 int hashCode()
           
 boolean lessEquals(HttpVersion version)
          Test if the HTTP protocol version is less or equal to the given number.
static HttpVersion parse(String s)
          Parses the textual representation of the given HTTP protocol version.
 String toString()
           
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

HTTP_0_9

public static final HttpVersion HTTP_0_9
HTTP protocol version 0.9


HTTP_1_0

public static final HttpVersion HTTP_1_0
HTTP protocol version 1.0


HTTP_1_1

public static final HttpVersion HTTP_1_1
HTTP protocol version 1.1

Constructor Detail

HttpVersion

public HttpVersion(int major,
                   int minor)
Create an HTTP protocol version designator.

Parameters:
major - the major version number of the HTTP protocol
minor - the minor version number of the HTTP protocol
Throws:
IllegalArgumentException - if either major or minor version number is negative
Method Detail

getMajor

public int getMajor()
Returns the major version number of the HTTP protocol.

Returns:
the major version number.

getMinor

public int getMinor()
Returns the minor version number of the HTTP protocol.

Returns:
the minor version number.

hashCode

public int hashCode()
Overrides:
hashCode in class Object
See Also:
Object.hashCode()

equals

public boolean equals(Object obj)
Overrides:
equals in class Object
See Also:
Object.equals(java.lang.Object)

compareTo

public int compareTo(HttpVersion anotherVer)
Compares this HTTP protocol version with another one.

Parameters:
anotherVer - the version to be compared with.
Returns:
a negative integer, zero, or a positive integer as this version is less than, equal to, or greater than the specified version.

compareTo

public int compareTo(Object o)
Specified by:
compareTo in interface Comparable
See Also:
Comparable.compareTo(java.lang.Object)

equals

public boolean equals(HttpVersion version)
Test if the HTTP protocol version is equal to the given number.

Returns:
true if HTTP protocol version is given to the given number, false otherwise.

greaterEquals

public boolean greaterEquals(HttpVersion version)
Test if the HTTP protocol version is greater or equal to the given number.

Returns:
true if HTTP protocol version is greater or equal given to the given number, false otherwise.

lessEquals

public boolean lessEquals(HttpVersion version)
Test if the HTTP protocol version is less or equal to the given number.

Returns:
true if HTTP protocol version is less or equal to given to the given number, false otherwise.

toString

public String toString()
Overrides:
toString in class Object
See Also:
Object.toString()

parse

public static HttpVersion parse(String s)
                         throws ProtocolException
Parses the textual representation of the given HTTP protocol version.

Returns:
HTTP protocol version.
Throws:
ProtocolException - if the string is not a valid HTTP protocol version.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/HttpsURL.html100644 0 0 250671 10661532627 25204 0ustar 0 0 HttpsURL (HttpClient 3.1 API)

org.apache.commons.httpclient
Class HttpsURL

java.lang.Object
  extended by org.apache.commons.httpclient.URI
      extended by org.apache.commons.httpclient.HttpURL
          extended by org.apache.commons.httpclient.HttpsURL
All Implemented Interfaces:
Serializable, Cloneable, Comparable

public class HttpsURL
extends HttpURL

The HTTPS URL.

Author:
Sung-Gu, Mike Bowler
See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class org.apache.commons.httpclient.URI
URI.DefaultCharsetChanged, URI.LocaleToCharsetMap
 
Field Summary
static int _default_port
          Deprecated. Use DEFAULT_PORT instead. This one doesn't conform to the project naming conventions.
static char[] _default_scheme
          Deprecated. Use DEFAULT_SCHEME instead. This one doesn't conform to the project naming conventions.
static int DEFAULT_PORT
          Default port for HTTPS URL.
static char[] DEFAULT_SCHEME
          Default scheme for HTTPS URL.
 
Fields inherited from class org.apache.commons.httpclient.URI
_authority, _fragment, _host, _is_abs_path, _is_hier_part, _is_hostname, _is_IPv4address, _is_IPv6reference, _is_net_path, _is_opaque_part, _is_reg_name, _is_rel_path, _is_server, _opaque, _path, _port, _query, _scheme, _uri, _userinfo, abs_path, absoluteURI, allowed_abs_path, allowed_authority, allowed_fragment, allowed_host, allowed_IPv6reference, allowed_opaque_part, allowed_query, allowed_reg_name, allowed_rel_path, allowed_userinfo, allowed_within_authority, allowed_within_path, allowed_within_query, allowed_within_userinfo, alpha, alphanum, authority, control, defaultDocumentCharset, defaultDocumentCharsetByLocale, defaultDocumentCharsetByPlatform, defaultProtocolCharset, delims, digit, disallowed_opaque_part, disallowed_rel_path, domainlabel, escaped, fragment, hash, hex, hier_part, host, hostname, hostport, IPv4address, IPv6address, IPv6reference, mark, net_path, opaque_part, param, path, path_segments, pchar, percent, port, protocolCharset, query, reg_name, rel_path, rel_segment, relativeURI, reserved, rootPath, scheme, segment, server, space, toplabel, unreserved, unwise, URI_reference, uric, uric_no_slash, userinfo, within_userinfo
 
Constructor Summary
protected HttpsURL()
          Create an instance as an internal use.
  HttpsURL(char[] escaped)
          Construct a HTTPS URL as an escaped form of a character array.
  HttpsURL(char[] escaped, String charset)
          Construct a HTTPS URL as an escaped form of a character array with the given charset to do escape encoding.
  HttpsURL(HttpsURL base, HttpsURL relative)
          Construct a HTTPS URL with a given relative URL.
  HttpsURL(HttpsURL base, String relative)
          Construct a HTTPS URL with a given relative HTTPS URL string.
  HttpsURL(String original)
          Construct a HTTPS URL from a given string.
  HttpsURL(String host, int port, String path)
          Construct a HTTPS URL from given components.
  HttpsURL(String host, int port, String path, String query)
          Construct a HTTPS URL from given components.
  HttpsURL(String original, String charset)
          Construct a HTTPS URL from a given string with the given charset to do escape encoding.
  HttpsURL(String userinfo, String host, int port, String path)
          Construct a HTTPS URL from given components.
  HttpsURL(String userinfo, String host, int port, String path, String query)
          Construct a HTTPS URL from given components.
  HttpsURL(String userinfo, String host, int port, String path, String query, String fragment)
          Construct a HTTPS URL from given components.
  HttpsURL(String user, String password, String host)
          Construct a HTTPS URL from given components.
  HttpsURL(String user, String password, String host, int port)
          Construct a HTTPS URL from given components.
  HttpsURL(String user, String password, String host, int port, String path)
          Construct a HTTPS URL from given components.
  HttpsURL(String user, String password, String host, int port, String path, String query)
          Construct a HTTPS URL from given components.
  HttpsURL(String user, String password, String host, int port, String path, String query, String fragment)
          Construct a HTTP URL from given components.
  HttpsURL(String host, String path, String query, String fragment)
          Construct a HTTPS URL from given components.
  HttpsURL(String userinfo, String host, String path, String query, String fragment)
          Construct a HTTPS URL from given components.
 
Method Summary
protected  void checkValid()
          Verify the valid class use for construction.
 int getPort()
          Get the port number.
 char[] getRawScheme()
          Get the scheme.
 String getScheme()
          Get the scheme.
 
Methods inherited from class org.apache.commons.httpclient.HttpURL
getEscapedPassword, getEscapedUser, getPassword, getRawAboveHierPath, getRawCurrentHierPath, getRawPassword, getRawPath, getRawUser, getUser, setEscapedPassword, setEscapedUser, setEscapedUserinfo, setPassword, setQuery, setQuery, setRawPassword, setRawUser, setRawUserinfo, setURI, setUser, setUserinfo, toUserinfo
 
Methods inherited from class org.apache.commons.httpclient.URI
clone, compareTo, decode, decode, encode, equals, equals, getAboveHierPath, getAuthority, getCurrentHierPath, getDefaultDocumentCharset, getDefaultDocumentCharsetByLocale, getDefaultDocumentCharsetByPlatform, getDefaultProtocolCharset, getEscapedAboveHierPath, getEscapedAuthority, getEscapedCurrentHierPath, getEscapedFragment, getEscapedName, getEscapedPath, getEscapedPathQuery, getEscapedQuery, getEscapedURI, getEscapedURIReference, getEscapedUserinfo, getFragment, getHost, getName, getPath, getPathQuery, getProtocolCharset, getQuery, getRawAuthority, getRawCurrentHierPath, getRawFragment, getRawHost, getRawName, getRawPathQuery, getRawQuery, getRawURI, getRawURIReference, getRawUserinfo, getURI, getURIReference, getUserinfo, hasAuthority, hasFragment, hashCode, hasQuery, hasUserinfo, indexFirstOf, indexFirstOf, indexFirstOf, indexFirstOf, isAbsoluteURI, isAbsPath, isHierPart, isHostname, isIPv4address, isIPv6reference, isNetPath, isOpaquePart, isRegName, isRelativeURI, isRelPath, isServer, normalize, normalize, parseAuthority, parseUriReference, prevalidate, removeFragmentIdentifier, resolvePath, setDefaultDocumentCharset, setDefaultProtocolCharset, setEscapedAuthority, setEscapedFragment, setEscapedPath, setEscapedQuery, setFragment, setPath, setQuery, setRawAuthority, setRawFragment, setRawPath, setRawQuery, toString, validate, validate
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

DEFAULT_SCHEME

public static final char[] DEFAULT_SCHEME
Default scheme for HTTPS URL.


_default_scheme

public static final char[] _default_scheme
Deprecated. Use DEFAULT_SCHEME instead. This one doesn't conform to the project naming conventions.
Default scheme for HTTPS URL.


DEFAULT_PORT

public static final int DEFAULT_PORT
Default port for HTTPS URL.

See Also:
Constant Field Values

_default_port

public static final int _default_port
Deprecated. Use DEFAULT_PORT instead. This one doesn't conform to the project naming conventions.
Default port for HTTPS URL.

See Also:
Constant Field Values
Constructor Detail

HttpsURL

protected HttpsURL()
Create an instance as an internal use.


HttpsURL

public HttpsURL(char[] escaped,
                String charset)
         throws URIException,
                NullPointerException
Construct a HTTPS URL as an escaped form of a character array with the given charset to do escape encoding.

Parameters:
escaped - the HTTPS URL character sequence
charset - the charset to do escape encoding
Throws:
URIException - If checkValid() fails
NullPointerException - if escaped is null
See Also:
URI.getProtocolCharset()

HttpsURL

public HttpsURL(char[] escaped)
         throws URIException,
                NullPointerException
Construct a HTTPS URL as an escaped form of a character array.

Parameters:
escaped - the HTTPS URL character sequence
Throws:
URIException - If checkValid() fails
NullPointerException - if escaped is null
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String original,
                String charset)
         throws URIException
Construct a HTTPS URL from a given string with the given charset to do escape encoding.

Parameters:
original - the HTTPS URL string
charset - the charset to do escape encoding
Throws:
URIException - If checkValid() fails
See Also:
URI.getProtocolCharset()

HttpsURL

public HttpsURL(String original)
         throws URIException
Construct a HTTPS URL from a given string.

Parameters:
original - the HTTPS URL string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String host,
                int port,
                String path)
         throws URIException
Construct a HTTPS URL from given components.

Parameters:
host - the host string
port - the port number
path - the path string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String host,
                int port,
                String path,
                String query)
         throws URIException
Construct a HTTPS URL from given components.

Parameters:
host - the host string
port - the port number
path - the path string
query - the query string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String user,
                String password,
                String host)
         throws URIException
Construct a HTTPS URL from given components.

Parameters:
user - the user name
password - his or her password
host - the host string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String user,
                String password,
                String host,
                int port)
         throws URIException
Construct a HTTPS URL from given components.

Parameters:
user - the user name
password - his or her password
host - the host string
port - the port number
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String user,
                String password,
                String host,
                int port,
                String path)
         throws URIException
Construct a HTTPS URL from given components.

Parameters:
user - the user name
password - his or her password
host - the host string
port - the port number
path - the path string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String user,
                String password,
                String host,
                int port,
                String path,
                String query)
         throws URIException
Construct a HTTPS URL from given components.

Parameters:
user - the user name
password - his or her password
host - the host string
port - the port number
path - the path string
query - The query string.
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String host,
                String path,
                String query,
                String fragment)
         throws URIException
Construct a HTTPS URL from given components.

Parameters:
host - the host string
path - the path string
query - the query string
fragment - the fragment string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String userinfo,
                String host,
                String path,
                String query,
                String fragment)
         throws URIException
Construct a HTTPS URL from given components. Note: The userinfo format is normally <username>:<password> where username and password must both be URL escaped.

Parameters:
userinfo - the userinfo string whose parts are URL escaped
host - the host string
path - the path string
query - the query string
fragment - the fragment string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String userinfo,
                String host,
                int port,
                String path)
         throws URIException
Construct a HTTPS URL from given components. Note: The userinfo format is normally <username>:<password> where username and password must both be URL escaped.

Parameters:
userinfo - the userinfo string whose parts are URL escaped
host - the host string
port - the port number
path - the path string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String userinfo,
                String host,
                int port,
                String path,
                String query)
         throws URIException
Construct a HTTPS URL from given components. Note: The userinfo format is normally <username>:<password> where username and password must both be URL escaped.

Parameters:
userinfo - the userinfo string whose parts are URL escaped
host - the host string
port - the port number
path - the path string
query - the query string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String userinfo,
                String host,
                int port,
                String path,
                String query,
                String fragment)
         throws URIException
Construct a HTTPS URL from given components. Note: The userinfo format is normally <username>:<password> where username and password must both be URL escaped.

Parameters:
userinfo - the userinfo string whose parts are URL escaped
host - the host string
port - the port number
path - the path string
query - the query string
fragment - the fragment string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(String user,
                String password,
                String host,
                int port,
                String path,
                String query,
                String fragment)
         throws URIException
Construct a HTTP URL from given components.

Parameters:
user - the user name
password - his or her password
host - the host string
port - the port number
path - the path string
query - the query string
fragment - the fragment string
Throws:
URIException - If checkValid() fails
See Also:
URI.getDefaultProtocolCharset()

HttpsURL

public HttpsURL(HttpsURL base,
                String relative)
         throws URIException
Construct a HTTPS URL with a given relative HTTPS URL string.

Parameters:
base - the base HttpsURL
relative - the relative HTTPS URL string
Throws:
URIException - If checkValid() fails

HttpsURL

public HttpsURL(HttpsURL base,
                HttpsURL relative)
         throws URIException
Construct a HTTPS URL with a given relative URL.

Parameters:
base - the base HttpsURL
relative - the relative HttpsURL
Throws:
URIException - If checkValid() fails
Method Detail

getRawScheme

public char[] getRawScheme()
Get the scheme. You can get the scheme explicitly.

Overrides:
getRawScheme in class HttpURL
Returns:
the scheme

getScheme

public String getScheme()
Get the scheme. You can get the scheme explicitly.

Overrides:
getScheme in class HttpURL
Returns:
the scheme null if empty or undefined

getPort

public int getPort()
Get the port number.

Overrides:
getPort in class HttpURL
Returns:
the port number

checkValid

protected void checkValid()
                   throws URIException
Verify the valid class use for construction.

Overrides:
checkValid in class HttpURL
Throws:
URIException - the wrong scheme use


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/InvalidRedirectLocationException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/InvalidRedirectLocationException.h100644 0 0 47400 10661532627 31374 0ustar 0 0 InvalidRedirectLocationException (HttpClient 3.1 API)

org.apache.commons.httpclient
Class InvalidRedirectLocationException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.ProtocolException
                      extended by org.apache.commons.httpclient.RedirectException
                          extended by org.apache.commons.httpclient.InvalidRedirectLocationException
All Implemented Interfaces:
Serializable

public class InvalidRedirectLocationException
extends RedirectException

Signals violation of HTTP specification caused by an invalid redirect location

Since:
3.1
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
InvalidRedirectLocationException(String message, String location)
          Creates a new InvalidRedirectLocationException with the specified detail message.
InvalidRedirectLocationException(String message, String location, Throwable cause)
          Creates a new RedirectException with the specified detail message and cause.
 
Method Summary
 String getLocation()
           
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

InvalidRedirectLocationException

public InvalidRedirectLocationException(String message,
                                        String location)
Creates a new InvalidRedirectLocationException with the specified detail message.

Parameters:
message - the exception detail message
location - redirect location

InvalidRedirectLocationException

public InvalidRedirectLocationException(String message,
                                        String location,
                                        Throwable cause)
Creates a new RedirectException with the specified detail message and cause.

Parameters:
message - the exception detail message
location - redirect location
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable
Method Detail

getLocation

public String getLocation()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/MethodRetryHandler.html100644 0 0 27052 10661532627 27236 0ustar 0 0 MethodRetryHandler (HttpClient 3.1 API)

org.apache.commons.httpclient
Interface MethodRetryHandler

All Known Implementing Classes:
DefaultMethodRetryHandler

Deprecated. use HttpMethodRetryHandler

public interface MethodRetryHandler

A handler for determining if an HttpMethod should be retried after a recoverable exception during execution.

Author:
Michael Becke
See Also:
HttpMethod.execute(HttpState, HttpConnection), HttpRecoverableException

Method Summary
 boolean retryMethod(HttpMethod method, HttpConnection connection, HttpRecoverableException recoverableException, int executionCount, boolean requestSent)
          Deprecated. Determines if a method should be retried after an HttpRecoverableException occurs during execution.
 

Method Detail

retryMethod

boolean retryMethod(HttpMethod method,
                    HttpConnection connection,
                    HttpRecoverableException recoverableException,
                    int executionCount,
                    boolean requestSent)
Deprecated. 
Determines if a method should be retried after an HttpRecoverableException occurs during execution.

Parameters:
method - the method being executed
connection - the connection the method is using
recoverableException - the exception that occurred
executionCount - the number of times this method has been unsuccessfully executed
requestSent - this argument is unused and will be removed in the future. HttpMethod.isRequestSent() should be used instead
Returns:
true if the method should be retried, false otherwise


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager100644 0 0 141320 10661532627 31450 0ustar 0 0 MultiThreadedHttpConnectionManager (HttpClient 3.1 API)

org.apache.commons.httpclient
Class MultiThreadedHttpConnectionManager

java.lang.Object
  extended by org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
All Implemented Interfaces:
HttpConnectionManager

public class MultiThreadedHttpConnectionManager
extends Object
implements HttpConnectionManager

Manages a set of HttpConnections for various HostConfigurations.

Since:
2.0
Author:
Michael Becke, Eric Johnson, Mike Bowler, Carl A. Dunham

Field Summary
static int DEFAULT_MAX_HOST_CONNECTIONS
          The default maximum number of connections allowed per host
static int DEFAULT_MAX_TOTAL_CONNECTIONS
          The default maximum number of connections allowed overall
 
Constructor Summary
MultiThreadedHttpConnectionManager()
          No-args constructor
 
Method Summary
 void closeIdleConnections(long idleTimeout)
          Closes connections that have been idle for at least the given amount of time.
 void deleteClosedConnections()
          Deletes all closed connections.
 HttpConnection getConnection(HostConfiguration hostConfiguration)
          Gets an HttpConnection for a given host configuration.
 HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout)
          Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
 int getConnectionsInPool()
          Gets the total number of pooled connections.
 int getConnectionsInPool(HostConfiguration hostConfiguration)
          Gets the total number of pooled connections for the given host configuration.
 int getConnectionsInUse()
          Deprecated. Use getConnectionsInPool()
 int getConnectionsInUse(HostConfiguration hostConfiguration)
          Deprecated. Use getConnectionsInPool(HostConfiguration)
 HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
          Gets a connection or waits if one is not available.
 int getMaxConnectionsPerHost()
          Deprecated. Use HttpConnectionManagerParams.getDefaultMaxConnectionsPerHost(), HttpConnectionManager.getParams().
 int getMaxTotalConnections()
          Deprecated. Use HttpConnectionManagerParams.getMaxTotalConnections(), HttpConnectionManager.getParams().
 HttpConnectionManagerParams getParams()
          Returns parameters associated with this connection manager.
 boolean isConnectionStaleCheckingEnabled()
          Deprecated. Use HttpConnectionParams.isStaleCheckingEnabled(), HttpConnectionManager.getParams().
 void releaseConnection(HttpConnection conn)
          Make the given HttpConnection available for use by other requests.
 void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled)
          Deprecated. Use HttpConnectionParams.setStaleCheckingEnabled(boolean), HttpConnectionManager.getParams().
 void setMaxConnectionsPerHost(int maxHostConnections)
          Deprecated. Use HttpConnectionManagerParams.setDefaultMaxConnectionsPerHost(int), HttpConnectionManager.getParams().
 void setMaxTotalConnections(int maxTotalConnections)
          Deprecated. Use HttpConnectionManagerParams.setMaxTotalConnections(int), HttpConnectionManager.getParams().
 void setParams(HttpConnectionManagerParams params)
          Assigns parameters for this connection manager.
 void shutdown()
          Shuts down the connection manager and releases all resources.
static void shutdownAll()
          Shuts down and cleans up resources used by all instances of MultiThreadedHttpConnectionManager.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DEFAULT_MAX_HOST_CONNECTIONS

public static final int DEFAULT_MAX_HOST_CONNECTIONS
The default maximum number of connections allowed per host

See Also:
Constant Field Values

DEFAULT_MAX_TOTAL_CONNECTIONS

public static final int DEFAULT_MAX_TOTAL_CONNECTIONS
The default maximum number of connections allowed overall

See Also:
Constant Field Values
Constructor Detail

MultiThreadedHttpConnectionManager

public MultiThreadedHttpConnectionManager()
No-args constructor

Method Detail

shutdownAll

public static void shutdownAll()
Shuts down and cleans up resources used by all instances of MultiThreadedHttpConnectionManager. All static resources are released, all threads are stopped, and shutdown() is called on all live instances of MultiThreadedHttpConnectionManager.

See Also:
shutdown()

shutdown

public void shutdown()
Shuts down the connection manager and releases all resources. All connections associated with this class will be closed and released.

The connection manager can no longer be used once shut down.

Calling this method more than once will have no effect.


isConnectionStaleCheckingEnabled

public boolean isConnectionStaleCheckingEnabled()
Deprecated. Use HttpConnectionParams.isStaleCheckingEnabled(), HttpConnectionManager.getParams().

Gets the staleCheckingEnabled value to be set on HttpConnections that are created.

Returns:
true if stale checking will be enabled on HttpConnections
See Also:
HttpConnection.isStaleCheckingEnabled()

setConnectionStaleCheckingEnabled

public void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled)
Deprecated. Use HttpConnectionParams.setStaleCheckingEnabled(boolean), HttpConnectionManager.getParams().

Sets the staleCheckingEnabled value to be set on HttpConnections that are created.

Parameters:
connectionStaleCheckingEnabled - true if stale checking will be enabled on HttpConnections
See Also:
HttpConnection.setStaleCheckingEnabled(boolean)

setMaxConnectionsPerHost

public void setMaxConnectionsPerHost(int maxHostConnections)
Deprecated. Use HttpConnectionManagerParams.setDefaultMaxConnectionsPerHost(int), HttpConnectionManager.getParams().

Sets the maximum number of connections allowed for a given HostConfiguration. Per RFC 2616 section 8.1.4, this value defaults to 2.

Parameters:
maxHostConnections - the number of connections allowed for each hostConfiguration

getMaxConnectionsPerHost

public int getMaxConnectionsPerHost()
Deprecated. Use HttpConnectionManagerParams.getDefaultMaxConnectionsPerHost(), HttpConnectionManager.getParams().

Gets the maximum number of connections allowed for a given hostConfiguration.

Returns:
The maximum number of connections allowed for a given hostConfiguration.

setMaxTotalConnections

public void setMaxTotalConnections(int maxTotalConnections)
Deprecated. Use HttpConnectionManagerParams.setMaxTotalConnections(int), HttpConnectionManager.getParams().

Sets the maximum number of connections allowed for this connection manager.

Parameters:
maxTotalConnections - the maximum number of connections allowed

getMaxTotalConnections

public int getMaxTotalConnections()
Deprecated. Use HttpConnectionManagerParams.getMaxTotalConnections(), HttpConnectionManager.getParams().

Gets the maximum number of connections allowed for this connection manager.

Returns:
The maximum number of connections allowed

getConnection

public HttpConnection getConnection(HostConfiguration hostConfiguration)
Description copied from interface: HttpConnectionManager
Gets an HttpConnection for a given host configuration. If a connection is not available this method will block until one is. The connection manager should be registered with any HttpConnection that is created.

Specified by:
getConnection in interface HttpConnectionManager
Parameters:
hostConfiguration - the host configuration to use to configure the connection
Returns:
an HttpConnection for the given configuration
See Also:
HttpConnectionManager.getConnection(HostConfiguration)

getConnectionWithTimeout

public HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration,
                                               long timeout)
                                        throws ConnectionPoolTimeoutException
Gets a connection or waits if one is not available. A connection is available if one exists that is not being used or if fewer than maxHostConnections have been created in the connectionPool, and fewer than maxTotalConnections have been created in all connectionPools.

Specified by:
getConnectionWithTimeout in interface HttpConnectionManager
Parameters:
hostConfiguration - The host configuration specifying the connection details.
timeout - the number of milliseconds to wait for a connection, 0 to wait indefinitely
Returns:
HttpConnection an available connection
Throws:
HttpException - if a connection does not become available in 'timeout' milliseconds
ConnectionPoolTimeoutException - if no connection becomes available before the timeout expires
Since:
3.0
See Also:
HttpConnection.setHttpConnectionManager(HttpConnectionManager)

getConnection

public HttpConnection getConnection(HostConfiguration hostConfiguration,
                                    long timeout)
                             throws HttpException
Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)

Description copied from interface: HttpConnectionManager
Gets an HttpConnection for a given host configuration. If a connection is not available, this method will block for at most the specified number of milliseconds or until a connection becomes available. The connection manager should be registered with any HttpConnection that is created.

Specified by:
getConnection in interface HttpConnectionManager
Parameters:
hostConfiguration - the host configuration to use to configure the connection
timeout - - the time (in milliseconds) to wait for a connection to become available, 0 to specify an infinite timeout
Returns:
an HttpConnection for the given configuraiton
Throws:
HttpException - if no connection becomes available before the timeout expires
See Also:
HttpConnectionManager.getConnection(HostConfiguration, long)

getConnectionsInPool

public int getConnectionsInPool(HostConfiguration hostConfiguration)
Gets the total number of pooled connections for the given host configuration. This is the total number of connections that have been created and are still in use by this connection manager for the host configuration. This value will not exceed the maximum number of connections per host.

Parameters:
hostConfiguration - The host configuration
Returns:
The total number of pooled connections

getConnectionsInPool

public int getConnectionsInPool()
Gets the total number of pooled connections. This is the total number of connections that have been created and are still in use by this connection manager. This value will not exceed the maximum number of connections.

Returns:
the total number of pooled connections

getConnectionsInUse

public int getConnectionsInUse(HostConfiguration hostConfiguration)
Deprecated. Use getConnectionsInPool(HostConfiguration)

Gets the number of connections in use for this configuration.

Parameters:
hostConfiguration - the key that connections are tracked on
Returns:
the number of connections in use

getConnectionsInUse

public int getConnectionsInUse()
Deprecated. Use getConnectionsInPool()

Gets the total number of connections in use.

Returns:
the total number of connections in use

deleteClosedConnections

public void deleteClosedConnections()
Deletes all closed connections. Only connections currently owned by the connection manager are processed.

Since:
3.0
See Also:
HttpConnection.isOpen()

closeIdleConnections

public void closeIdleConnections(long idleTimeout)
Description copied from interface: HttpConnectionManager
Closes connections that have been idle for at least the given amount of time. Only connections that are currently owned, not checked out, are subject to idle timeouts.

Specified by:
closeIdleConnections in interface HttpConnectionManager
Parameters:
idleTimeout - the minimum idle time, in milliseconds, for connections to be closed
Since:
3.0

releaseConnection

public void releaseConnection(HttpConnection conn)
Make the given HttpConnection available for use by other requests. If another thread is blocked in getConnection() that could use this connection, it will be woken up.

Specified by:
releaseConnection in interface HttpConnectionManager
Parameters:
conn - the HttpConnection to make available.

getParams

public HttpConnectionManagerParams getParams()
Returns parameters associated with this connection manager.

Specified by:
getParams in interface HttpConnectionManager
Since:
3.0
See Also:
HttpConnectionManagerParams

setParams

public void setParams(HttpConnectionManagerParams params)
Assigns parameters for this connection manager.

Specified by:
setParams in interface HttpConnectionManager
Since:
3.0
See Also:
HttpConnectionManagerParams


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/NTCredentials.html100644 0 0 55555 10661532627 26202 0ustar 0 0 NTCredentials (HttpClient 3.1 API)

org.apache.commons.httpclient
Class NTCredentials

java.lang.Object
  extended by org.apache.commons.httpclient.UsernamePasswordCredentials
      extended by org.apache.commons.httpclient.NTCredentials
All Implemented Interfaces:
Credentials

public class NTCredentials
extends UsernamePasswordCredentials

Credentials for use with the NTLM authentication scheme which requires additional information.

Since:
2.0
Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
Adrian Sutton, Mike Bowler

Constructor Summary
NTCredentials()
          Deprecated. Do not use. Null user name, domain & host no longer allowed
NTCredentials(String userName, String password, String host, String domain)
          Constructor.
 
Method Summary
 boolean equals(Object o)
          Performs a case-sensitive check to see if the components of the credentials are the same.
 String getDomain()
          Retrieves the name to authenticate with.
 String getHost()
          Retrieves the host name of the computer originating the request.
 int hashCode()
          Computes a hash code based on all the case-sensitive parts of the credentials object.
 void setDomain(String domain)
          Deprecated. Do not use. The NTCredentials objects should be immutable
 void setHost(String host)
          Deprecated. Do not use. The NTCredentials objects should be immutable
 String toString()
          Return a string representation of this object.
 
Methods inherited from class org.apache.commons.httpclient.UsernamePasswordCredentials
getPassword, getUserName, setPassword, setUserName
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NTCredentials

public NTCredentials()
Deprecated. Do not use. Null user name, domain & host no longer allowed

Default constructor.


NTCredentials

public NTCredentials(String userName,
                     String password,
                     String host,
                     String domain)
Constructor.

Parameters:
userName - The user name. This should not include the domain to authenticate with. For example: "user" is correct whereas "DOMAIN\\user" is not.
password - The password.
host - The host the authentication request is originating from. Essentially, the computer name for this machine.
domain - The domain to authenticate within.
Method Detail

setDomain

public void setDomain(String domain)
Deprecated. Do not use. The NTCredentials objects should be immutable

Sets the domain to authenticate with. The domain may not be null.

Parameters:
domain - the NT domain to authenticate in.
See Also:
getDomain()

getDomain

public String getDomain()
Retrieves the name to authenticate with.

Returns:
String the domain these credentials are intended to authenticate with.
See Also:
setDomain(String)

setHost

public void setHost(String host)
Deprecated. Do not use. The NTCredentials objects should be immutable

Sets the host name of the computer originating the request. The host name may not be null.

Parameters:
host - the Host the user is logged into.

getHost

public String getHost()
Retrieves the host name of the computer originating the request.

Returns:
String the host the user is logged into.

toString

public String toString()
Return a string representation of this object.

Overrides:
toString in class UsernamePasswordCredentials
Returns:
A string represenation of this object.

hashCode

public int hashCode()
Computes a hash code based on all the case-sensitive parts of the credentials object.

Overrides:
hashCode in class UsernamePasswordCredentials
Returns:
The hash code for the credentials.

equals

public boolean equals(Object o)
Performs a case-sensitive check to see if the components of the credentials are the same.

Overrides:
equals in class UsernamePasswordCredentials
Parameters:
o - The object to match.
Returns:
true if all of the credentials match.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/NameValuePair.html100644 0 0 47252 10661532627 26167 0ustar 0 0 NameValuePair (HttpClient 3.1 API)

org.apache.commons.httpclient
Class NameValuePair

java.lang.Object
  extended by org.apache.commons.httpclient.NameValuePair
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
Cookie, Header, HeaderElement

public class NameValuePair
extends Object
implements Serializable

A simple class encapsulating a name/value pair.

Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
B.C. Holmes, Sean C. Sullivan, Mike Bowler
See Also:
Serialized Form

Constructor Summary
NameValuePair()
          Default constructor.
NameValuePair(String name, String value)
          Constructor.
 
Method Summary
 boolean equals(Object object)
           
 String getName()
          Return the name.
 String getValue()
          Return the current value.
 int hashCode()
           
 void setName(String name)
          Set the name.
 void setValue(String value)
          Set the value.
 String toString()
          Get a String representation of this pair.
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NameValuePair

public NameValuePair()
Default constructor.


NameValuePair

public NameValuePair(String name,
                     String value)
Constructor.

Parameters:
name - The name.
value - The value.
Method Detail

setName

public void setName(String name)
Set the name.

Parameters:
name - The new name
See Also:
getName()

getName

public String getName()
Return the name.

Returns:
String name The name
See Also:
setName(String)

setValue

public void setValue(String value)
Set the value.

Parameters:
value - The new value.

getValue

public String getValue()
Return the current value.

Returns:
String value The current value.

toString

public String toString()
Get a String representation of this pair.

Overrides:
toString in class Object
Returns:
A string representation.

equals

public boolean equals(Object object)
Overrides:
equals in class Object

hashCode

public int hashCode()
Overrides:
hashCode in class Object


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/NoHttpResponseException.html100644 0 0 41360 10661532627 30302 0ustar 0 0 NoHttpResponseException (HttpClient 3.1 API)

org.apache.commons.httpclient
Class NoHttpResponseException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.NoHttpResponseException
All Implemented Interfaces:
Serializable

public class NoHttpResponseException
extends IOException

Signals that the target server failed to respond with a valid HTTP response.

Version:
$Revision: 480424 $
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
NoHttpResponseException()
          Creates a new NoHttpResponseException with a null detail message.
NoHttpResponseException(String message)
          Creates a new NoHttpResponseException with the specified detail message.
NoHttpResponseException(String message, Throwable cause)
          Creates a new NoHttpResponseException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

NoHttpResponseException

public NoHttpResponseException()
Creates a new NoHttpResponseException with a null detail message.


NoHttpResponseException

public NoHttpResponseException(String message)
Creates a new NoHttpResponseException with the specified detail message.

Parameters:
message - exception message

NoHttpResponseException

public NoHttpResponseException(String message,
                               Throwable cause)
Creates a new NoHttpResponseException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ProtocolException.html100644 0 0 44441 10661532627 27153 0ustar 0 0 ProtocolException (HttpClient 3.1 API)

org.apache.commons.httpclient
Class ProtocolException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.ProtocolException
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
AuthenticationException, MalformedChallengeException, MalformedCookieException, RedirectException

public class ProtocolException
extends HttpException

Signals that an HTTP protocol violation has occurred. For example, HttpClient detected a malformed status line or headers, a missing message body, etc.

Since:
3.0
Author:
Laura Werner
See Also:
Serialized Form

Constructor Summary
ProtocolException()
          Creates a new ProtocolException with a null detail message.
ProtocolException(String message)
          Creates a new ProtocolException with the specified detail message.
ProtocolException(String message, Throwable cause)
          Creates a new ProtocolException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ProtocolException

public ProtocolException()
Creates a new ProtocolException with a null detail message.


ProtocolException

public ProtocolException(String message)
Creates a new ProtocolException with the specified detail message.

Parameters:
message - The exception detail message

ProtocolException

public ProtocolException(String message,
                         Throwable cause)
Creates a new ProtocolException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ProxyClient.ConnectResponse.html100644 0 0 30633 10661532627 31060 0ustar 0 0 ProxyClient.ConnectResponse (HttpClient 3.1 API)

org.apache.commons.httpclient
Class ProxyClient.ConnectResponse

java.lang.Object
  extended by org.apache.commons.httpclient.ProxyClient.ConnectResponse
Enclosing class:
ProxyClient

public static class ProxyClient.ConnectResponse
extends Object

Contains the method used to execute the connect along with the created socket.


Method Summary
 ConnectMethod getConnectMethod()
          Gets the method that was used to execute the connect.
 Socket getSocket()
          Gets the socket connected and authenticated (if appropriate) to the configured HTTP proxy, or null if a connection could not be made.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

getConnectMethod

public ConnectMethod getConnectMethod()
Gets the method that was used to execute the connect. This method is useful for analyzing the proxy's response when a connect fails.

Returns:
the connectMethod.

getSocket

public Socket getSocket()
Gets the socket connected and authenticated (if appropriate) to the configured HTTP proxy, or null if a connection could not be made. It is the responsibility of the user to close this socket when it is no longer needed.

Returns:
the socket.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ProxyClient.html100644 0 0 62502 10661532627 25751 0ustar 0 0 ProxyClient (HttpClient 3.1 API)

org.apache.commons.httpclient
Class ProxyClient

java.lang.Object
  extended by org.apache.commons.httpclient.ProxyClient

public class ProxyClient
extends Object

A client that provides sockets for communicating through HTTP proxies via the HTTP CONNECT method. This is primarily needed for non-HTTP protocols that wish to communicate via an HTTP proxy.

Since:
3.0
Version:
$Revision: 480424 $
Author:
Oleg Kalnichevski, Michael Becke

Nested Class Summary
static class ProxyClient.ConnectResponse
          Contains the method used to execute the connect along with the created socket.
 
Constructor Summary
ProxyClient()
          Creates an instance of ProxyClient using default parameter set.
ProxyClient(HttpClientParams params)
          Creates an instance of ProxyClient using the given parameter set.
 
Method Summary
 ProxyClient.ConnectResponse connect()
          Creates a socket that is connected, via the HTTP CONNECT method, to a proxy.
 HostConfiguration getHostConfiguration()
          Returns the host configuration associated with the ProxyClient.
 HttpClientParams getParams()
          Returns HTTP protocol parameters associated with this ProxyClient.
 HttpState getState()
          Returns HTTP state associated with the ProxyClient.
 void setHostConfiguration(HostConfiguration hostConfiguration)
          Assigns the host configuration to use with the ProxyClient.
 void setParams(HttpClientParams params)
          Assigns HTTP protocol parameters for this ProxyClient.
 void setState(HttpState state)
          Assigns HTTP state for the ProxyClient.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ProxyClient

public ProxyClient()
Creates an instance of ProxyClient using default parameter set.

See Also:
HttpClientParams

ProxyClient

public ProxyClient(HttpClientParams params)
Creates an instance of ProxyClient using the given parameter set.

Parameters:
params - The parameters to use.
See Also:
HttpClientParams
Method Detail

getState

public HttpState getState()
Returns HTTP state associated with the ProxyClient.

Returns:
the shared client state
See Also:
setState(HttpState)

setState

public void setState(HttpState state)
Assigns HTTP state for the ProxyClient.

Parameters:
state - the new HTTP state for the client
See Also:
getState()

getHostConfiguration

public HostConfiguration getHostConfiguration()
Returns the host configuration associated with the ProxyClient.

Returns:
host configuration

setHostConfiguration

public void setHostConfiguration(HostConfiguration hostConfiguration)
Assigns the host configuration to use with the ProxyClient.

Parameters:
hostConfiguration - The host configuration to set

getParams

public HttpClientParams getParams()
Returns HTTP protocol parameters associated with this ProxyClient.

See Also:
HttpClientParams

setParams

public void setParams(HttpClientParams params)
Assigns HTTP protocol parameters for this ProxyClient.

See Also:
HttpClientParams

connect

public ProxyClient.ConnectResponse connect()
                                    throws IOException,
                                           HttpException
Creates a socket that is connected, via the HTTP CONNECT method, to a proxy.

Even though HTTP CONNECT proxying is generally used for HTTPS tunneling, the returned socket will not have been wrapped in an SSL socket.

Both the proxy and destination hosts must be set via the host configuration prior to calling this method.

Returns:
the connect response
Throws:
IOException
HttpException
See Also:
getHostConfiguration()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/ProxyHost.html100644 0 0 40267 10661532627 25454 0ustar 0 0 ProxyHost (HttpClient 3.1 API)

org.apache.commons.httpclient
Class ProxyHost

java.lang.Object
  extended by org.apache.commons.httpclient.HttpHost
      extended by org.apache.commons.httpclient.ProxyHost
All Implemented Interfaces:
Cloneable

public class ProxyHost
extends HttpHost

Holds all of the variables needed to describe an HTTP connection to a proxy. Proxy hosts always use plain HTTP connection when communicating with clients.

Since:
3.0
Author:
Michael Becke, Mike Bowler, Oleg Kalnichevski, Laura Werner

Constructor Summary
ProxyHost(ProxyHost httpproxy)
          Copy constructor for HttpHost
ProxyHost(String hostname)
          Constructor for HttpHost.
ProxyHost(String hostname, int port)
          Constructor for ProxyHost.
 
Method Summary
 Object clone()
           
 
Methods inherited from class org.apache.commons.httpclient.HttpHost
equals, getHostName, getPort, getProtocol, hashCode, toString, toURI
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

ProxyHost

public ProxyHost(ProxyHost httpproxy)
Copy constructor for HttpHost

Parameters:
httpproxy - the HTTP host to copy details from

ProxyHost

public ProxyHost(String hostname,
                 int port)
Constructor for ProxyHost.

Parameters:
hostname - the hostname (IP or DNS name). Can be null.
port - the port. Value -1 can be used to set default protocol port

ProxyHost

public ProxyHost(String hostname)
Constructor for HttpHost.

Parameters:
hostname - the hostname (IP or DNS name). Can be null.
Method Detail

clone

public Object clone()
             throws CloneNotSupportedException
Overrides:
clone in class HttpHost
Throws:
CloneNotSupportedException
See Also:
Object.clone()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/RedirectException.html100644 0 0 44255 10661532627 27116 0ustar 0 0 RedirectException (HttpClient 3.1 API)

org.apache.commons.httpclient
Class RedirectException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.ProtocolException
                      extended by org.apache.commons.httpclient.RedirectException
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
CircularRedirectException, InvalidRedirectLocationException

public class RedirectException
extends ProtocolException

Signals violation of HTTP specification caused by an invalid redirect

Since:
3.0
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
RedirectException()
          Creates a new RedirectException with a null detail message.
RedirectException(String message)
          Creates a new RedirectException with the specified detail message.
RedirectException(String message, Throwable cause)
          Creates a new RedirectException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

RedirectException

public RedirectException()
Creates a new RedirectException with a null detail message.


RedirectException

public RedirectException(String message)
Creates a new RedirectException with the specified detail message.

Parameters:
message - The exception detail message

RedirectException

public RedirectException(String message,
                         Throwable cause)
Creates a new RedirectException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/SimpleHttpConnectionManager.html100644 0 0 104546 10661532627 31122 0ustar 0 0 SimpleHttpConnectionManager (HttpClient 3.1 API)

org.apache.commons.httpclient
Class SimpleHttpConnectionManager

java.lang.Object
  extended by org.apache.commons.httpclient.SimpleHttpConnectionManager
All Implemented Interfaces:
HttpConnectionManager

public class SimpleHttpConnectionManager
extends Object
implements HttpConnectionManager

A connection manager that provides access to a single HttpConnection. This manager makes no attempt to provide exclusive access to the contained HttpConnection.

Since:
2.0
Author:
Michael Becke, Eric Johnson, Mike Bowler, Oleg Kalnichevski, Laura Werner

Field Summary
protected  HttpConnection httpConnection
          The http connection
 
Constructor Summary
SimpleHttpConnectionManager()
          The connection manager created with this constructor will always try to keep the connection open (alive) between consecutive requests.
SimpleHttpConnectionManager(boolean alwaysClose)
          The connection manager created with this constructor will try to keep the connection open (alive) between consecutive requests if the alwaysClose parameter is set to false.
 
Method Summary
 void closeIdleConnections(long idleTimeout)
          Closes connections that have been idle for at least the given amount of time.
 HttpConnection getConnection(HostConfiguration hostConfiguration)
          Gets an HttpConnection for a given host configuration.
 HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout)
          Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
 HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
          This method always returns the same connection object.
 HttpConnectionManagerParams getParams()
          Returns parameters associated with this connection manager.
 boolean isConnectionStaleCheckingEnabled()
          Deprecated. Use HttpConnectionParams.isStaleCheckingEnabled(), HttpConnectionManager.getParams().
 void releaseConnection(HttpConnection conn)
          Releases the given HttpConnection for use by other requests.
 void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled)
          Deprecated. Use HttpConnectionParams.setStaleCheckingEnabled(boolean), HttpConnectionManager.getParams().
 void setParams(HttpConnectionManagerParams params)
          Assigns parameters for this connection manager.
 void shutdown()
          since 3.1
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

httpConnection

protected HttpConnection httpConnection
The http connection

Constructor Detail

SimpleHttpConnectionManager

public SimpleHttpConnectionManager(boolean alwaysClose)
The connection manager created with this constructor will try to keep the connection open (alive) between consecutive requests if the alwaysClose parameter is set to false. Otherwise the connection manager will always close connections upon release.

Parameters:
alwaysClose - if set true, the connection manager will always close connections upon release.

SimpleHttpConnectionManager

public SimpleHttpConnectionManager()
The connection manager created with this constructor will always try to keep the connection open (alive) between consecutive requests.

Method Detail

getConnection

public HttpConnection getConnection(HostConfiguration hostConfiguration)
Description copied from interface: HttpConnectionManager
Gets an HttpConnection for a given host configuration. If a connection is not available this method will block until one is. The connection manager should be registered with any HttpConnection that is created.

Specified by:
getConnection in interface HttpConnectionManager
Parameters:
hostConfiguration - the host configuration to use to configure the connection
Returns:
an HttpConnection for the given configuration
See Also:
HttpConnectionManager.getConnection(HostConfiguration)

isConnectionStaleCheckingEnabled

public boolean isConnectionStaleCheckingEnabled()
Deprecated. Use HttpConnectionParams.isStaleCheckingEnabled(), HttpConnectionManager.getParams().

Gets the staleCheckingEnabled value to be set on HttpConnections that are created.

Returns:
true if stale checking will be enabled on HttpConections
See Also:
HttpConnection.isStaleCheckingEnabled()

setConnectionStaleCheckingEnabled

public void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled)
Deprecated. Use HttpConnectionParams.setStaleCheckingEnabled(boolean), HttpConnectionManager.getParams().

Sets the staleCheckingEnabled value to be set on HttpConnections that are created.

Parameters:
connectionStaleCheckingEnabled - true if stale checking will be enabled on HttpConections
See Also:
HttpConnection.setStaleCheckingEnabled(boolean)

getConnectionWithTimeout

public HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration,
                                               long timeout)
This method always returns the same connection object. If the connection is already open, it will be closed and the new host configuration will be applied.

Specified by:
getConnectionWithTimeout in interface HttpConnectionManager
Parameters:
hostConfiguration - The host configuration specifying the connection details.
timeout - this parameter has no effect. The connection is always returned immediately.
Returns:
an HttpConnection for the given configuraiton
Since:
3.0
See Also:
HttpConnection.setHttpConnectionManager(HttpConnectionManager)

getConnection

public HttpConnection getConnection(HostConfiguration hostConfiguration,
                                    long timeout)
Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)

Description copied from interface: HttpConnectionManager
Gets an HttpConnection for a given host configuration. If a connection is not available, this method will block for at most the specified number of milliseconds or until a connection becomes available. The connection manager should be registered with any HttpConnection that is created.

Specified by:
getConnection in interface HttpConnectionManager
Parameters:
hostConfiguration - the host configuration to use to configure the connection
timeout - - the time (in milliseconds) to wait for a connection to become available, 0 to specify an infinite timeout
Returns:
an HttpConnection for the given configuraiton
See Also:
HttpConnectionManager.getConnection(HostConfiguration, long)

releaseConnection

public void releaseConnection(HttpConnection conn)
Description copied from interface: HttpConnectionManager
Releases the given HttpConnection for use by other requests.

Specified by:
releaseConnection in interface HttpConnectionManager
Parameters:
conn - - The HttpConnection to make available.
See Also:
HttpConnectionManager.releaseConnection(org.apache.commons.httpclient.HttpConnection)

getParams

public HttpConnectionManagerParams getParams()
Returns parameters associated with this connection manager.

Specified by:
getParams in interface HttpConnectionManager
Since:
2.1
See Also:
HttpConnectionManagerParams

setParams

public void setParams(HttpConnectionManagerParams params)
Assigns parameters for this connection manager.

Specified by:
setParams in interface HttpConnectionManager
Since:
2.1
See Also:
HttpConnectionManagerParams

closeIdleConnections

public void closeIdleConnections(long idleTimeout)
Description copied from interface: HttpConnectionManager
Closes connections that have been idle for at least the given amount of time. Only connections that are currently owned, not checked out, are subject to idle timeouts.

Specified by:
closeIdleConnections in interface HttpConnectionManager
Parameters:
idleTimeout - the minimum idle time, in milliseconds, for connections to be closed
Since:
3.0

shutdown

public void shutdown()
since 3.1



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/StatusLine.html100644 0 0 41711 10661532627 25563 0ustar 0 0 StatusLine (HttpClient 3.1 API)

org.apache.commons.httpclient
Class StatusLine

java.lang.Object
  extended by org.apache.commons.httpclient.StatusLine

public class StatusLine
extends Object

Represents a Status-Line as returned from a HTTP server. RFC2616 states the following regarding the Status-Line:

 6.1 Status-Line

  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
 

This class is immutable and is inherently thread safe.

Since:
2.0
Version:
$Id: StatusLine.java 480424 2006-11-29 05:56:49Z bayard $
Author:
Jeff Dever, Mike Bowler
See Also:
HttpStatus

Constructor Summary
StatusLine(String statusLine)
          Default constructor.
 
Method Summary
 String getHttpVersion()
           
 String getReasonPhrase()
           
 int getStatusCode()
           
static boolean startsWithHTTP(String s)
          Tests if the string starts with 'HTTP' signature.
 String toString()
          Return a string representation of this object.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

StatusLine

public StatusLine(String statusLine)
           throws HttpException
Default constructor.

Parameters:
statusLine - the status line returned from the HTTP server
Throws:
HttpException - if the status line is invalid
Method Detail

getStatusCode

public final int getStatusCode()
Returns:
the Status-Code

getHttpVersion

public final String getHttpVersion()
Returns:
the HTTP-Version

getReasonPhrase

public final String getReasonPhrase()
Returns:
the Reason-Phrase

toString

public final String toString()
Return a string representation of this object.

Overrides:
toString in class Object
Returns:
a string represenation of this object.

startsWithHTTP

public static boolean startsWithHTTP(String s)
Tests if the string starts with 'HTTP' signature.

Parameters:
s - string to test
Returns:
true if the line starts with 'HTTP' signature, false otherwise.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/URI.DefaultCharsetChanged.html100644 0 0 46552 10661532627 30306 0ustar 0 0 URI.DefaultCharsetChanged (HttpClient 3.1 API)

org.apache.commons.httpclient
Class URI.DefaultCharsetChanged

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.lang.RuntimeException
              extended by org.apache.commons.httpclient.URI.DefaultCharsetChanged
All Implemented Interfaces:
Serializable
Enclosing class:
URI

public static class URI.DefaultCharsetChanged
extends RuntimeException

The charset-changed normal operation to represent to be required to alert to user the fact the default charset is changed.

See Also:
Serialized Form

Field Summary
static int DOCUMENT_CHARSET
          Document charset changed.
static int PROTOCOL_CHARSET
          Protocol charset changed.
static int UNKNOWN
          No specified reason code.
 
Constructor Summary
URI.DefaultCharsetChanged(int reasonCode, String reason)
          The constructor with a reason string and its code arguments.
 
Method Summary
 String getReason()
          Get the reason message.
 int getReasonCode()
          Get the reason code.
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

UNKNOWN

public static final int UNKNOWN
No specified reason code.

See Also:
Constant Field Values

PROTOCOL_CHARSET

public static final int PROTOCOL_CHARSET
Protocol charset changed.

See Also:
Constant Field Values

DOCUMENT_CHARSET

public static final int DOCUMENT_CHARSET
Document charset changed.

See Also:
Constant Field Values
Constructor Detail

URI.DefaultCharsetChanged

public URI.DefaultCharsetChanged(int reasonCode,
                                 String reason)
The constructor with a reason string and its code arguments.

Parameters:
reasonCode - the reason code
reason - the reason
Method Detail

getReasonCode

public int getReasonCode()
Get the reason code.

Returns:
the reason code

getReason

public String getReason()
Get the reason message.

Returns:
the reason message


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/URI.LocaleToCharsetMap.html100644 0 0 31572 10661532627 27604 0ustar 0 0 URI.LocaleToCharsetMap (HttpClient 3.1 API)

org.apache.commons.httpclient
Class URI.LocaleToCharsetMap

java.lang.Object
  extended by org.apache.commons.httpclient.URI.LocaleToCharsetMap
Enclosing class:
URI

public static class URI.LocaleToCharsetMap
extends Object

A mapping to determine the (somewhat arbitrarily) preferred charset for a given locale. Supports all locales recognized in JDK 1.1.

The distribution of this class is Servlets.com. It was originally written by Jason Hunter [jhunter at acm.org] and used by with permission.


Constructor Summary
URI.LocaleToCharsetMap()
           
 
Method Summary
static String getCharset(Locale locale)
          Get the preferred charset for the given locale.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

URI.LocaleToCharsetMap

public URI.LocaleToCharsetMap()
Method Detail

getCharset

public static String getCharset(Locale locale)
Get the preferred charset for the given locale.

Parameters:
locale - the locale
Returns:
the preferred charset or null if the locale is not recognized.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/URI.html100644 0 0 727565 10661532627 24171 0ustar 0 0 URI (HttpClient 3.1 API)

org.apache.commons.httpclient
Class URI

java.lang.Object
  extended by org.apache.commons.httpclient.URI
All Implemented Interfaces:
Serializable, Cloneable, Comparable
Direct Known Subclasses:
HttpURL, URIUtil.Coder

public class URI
extends Object
implements Cloneable, Comparable, Serializable

The interface for the URI(Uniform Resource Identifiers) version of RFC 2396. This class has the purpose of supportting of parsing a URI reference to extend any specific protocols, the character encoding of the protocol to be transported and the charset of the document.

A URI is always in an "escaped" form, since escaping or unescaping a completed URI might change its semantics.

Implementers should be careful not to escape or unescape the same string more than once, since unescaping an already unescaped string might lead to misinterpreting a percent data character as another escaped character, or vice versa in the case of escaping an already escaped string.

In order to avoid these problems, data types used as follows:

   URI character sequence: char
   octet sequence: byte
   original character sequence: String
 

So, a URI is a sequence of characters as an array of a char type, which is not always represented as a sequence of octets as an array of byte.

URI Syntactic Components

 - In general, written as follows:
   Absolute URI = <scheme>:<scheme-specific-part>
   Generic URI = <scheme>://<authority><path>?<query>

 - Syntax
   absoluteURI   = scheme ":" ( hier_part | opaque_part )
   hier_part     = ( net_path | abs_path ) [ "?" query ]
   net_path      = "//" authority [ abs_path ]
   abs_path      = "/"  path_segments
 

The following examples illustrate URI that are in common use.

 ftp://ftp.is.co.za/rfc/rfc1808.txt
    -- ftp scheme for File Transfer Protocol services
 gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles
    -- gopher scheme for Gopher and Gopher+ Protocol services
 http://www.math.uio.no/faq/compression-faq/part1.html
    -- http scheme for Hypertext Transfer Protocol services
 mailto:mduerst@ifi.unizh.ch
    -- mailto scheme for electronic mail addresses
 news:comp.infosystems.www.servers.unix
    -- news scheme for USENET news groups and articles
 telnet://melvyl.ucop.edu/
    -- telnet scheme for interactive services via the TELNET Protocol
 
Please, notice that there are many modifications from URL(RFC 1738) and relative URL(RFC 1808).

The expressions for a URI

 For escaped URI forms
  - URI(char[]) // constructor
  - char[] getRawXxx() // method
  - String getEscapedXxx() // method
  - String toString() // method
 

For unescaped URI forms - URI(String) // constructor - String getXXX() // method

Version:
$Revision: 564973 $ $Date: 2002/03/14 15:14:01
Author:
Sung-Gu, Mike Bowler
See Also:
Serialized Form

Nested Class Summary
static class URI.DefaultCharsetChanged
          The charset-changed normal operation to represent to be required to alert to user the fact the default charset is changed.
static class URI.LocaleToCharsetMap
          A mapping to determine the (somewhat arbitrarily) preferred charset for a given locale.
 
Field Summary
protected  char[] _authority
          The authority.
protected  char[] _fragment
          The fragment.
protected  char[] _host
          The host.
protected  boolean _is_abs_path
           
protected  boolean _is_hier_part
           
protected  boolean _is_hostname
           
protected  boolean _is_IPv4address
           
protected  boolean _is_IPv6reference
           
protected  boolean _is_net_path
           
protected  boolean _is_opaque_part
           
protected  boolean _is_reg_name
           
protected  boolean _is_rel_path
           
protected  boolean _is_server
           
protected  char[] _opaque
          The opaque.
protected  char[] _path
          The path.
protected  int _port
          The port.
protected  char[] _query
          The query.
protected  char[] _scheme
          The scheme.
protected  char[] _uri
          This Uniform Resource Identifier (URI).
protected  char[] _userinfo
          The userinfo.
protected static BitSet abs_path
          URI absolute path.
protected static BitSet absoluteURI
          BitSet for absoluteURI.
static BitSet allowed_abs_path
          Those characters that are allowed for the abs_path.
static BitSet allowed_authority
          Those characters that are allowed for the authority component.
static BitSet allowed_fragment
          Those characters that are allowed for the fragment component.
static BitSet allowed_host
          Those characters that are allowed for the host component.
static BitSet allowed_IPv6reference
          Those characters that are allowed for the IPv6reference component.
static BitSet allowed_opaque_part
          Those characters that are allowed for the opaque_part.
static BitSet allowed_query
          Those characters that are allowed for the query component.
static BitSet allowed_reg_name
          Those characters that are allowed for the reg_name.
static BitSet allowed_rel_path
          Those characters that are allowed for the rel_path.
static BitSet allowed_userinfo
          Those characters that are allowed for the userinfo component.
static BitSet allowed_within_authority
          Those characters that are allowed for the authority component.
static BitSet allowed_within_path
          Those characters that are allowed within the path.
static BitSet allowed_within_query
          Those characters that are allowed within the query component.
static BitSet allowed_within_userinfo
          Those characters that are allowed for within the userinfo component.
protected static BitSet alpha
          BitSet for alpha.
protected static BitSet alphanum
          BitSet for alphanum (join of alpha & digit).
protected static BitSet authority
          BitSet for authority.
static BitSet control
          BitSet for control.
protected static String defaultDocumentCharset
          The default charset of the document.
protected static String defaultDocumentCharsetByLocale
           
protected static String defaultDocumentCharsetByPlatform
           
protected static String defaultProtocolCharset
          The default charset of the protocol.
static BitSet delims
          BitSet for delims.
protected static BitSet digit
          BitSet for digit.
static BitSet disallowed_opaque_part
          Disallowed opaque_part before escaping.
static BitSet disallowed_rel_path
          Disallowed rel_path before escaping.
protected static BitSet domainlabel
          BitSet for domainlabel.
protected static BitSet escaped
          BitSet for escaped.
protected static BitSet fragment
          BitSet for fragment (alias for uric).
protected  int hash
          Cache the hash code for this URI.
protected static BitSet hex
          BitSet for hex.
protected static BitSet hier_part
          BitSet for hier_part.
protected static BitSet host
          BitSet for host.
protected static BitSet hostname
          BitSet for hostname.
protected static BitSet hostport
          BitSet for hostport.
protected static BitSet IPv4address
          Bitset that combines digit and dot fo IPv$address.
protected static BitSet IPv6address
          RFC 2373.
protected static BitSet IPv6reference
          RFC 2732, 2373.
protected static BitSet mark
          BitSet for mark.
protected static BitSet net_path
          BitSet for net_path.
protected static BitSet opaque_part
          URI bitset that combines uric_no_slash and uric.
protected static BitSet param
          BitSet for param (alias for pchar).
protected static BitSet path
          URI bitset that combines absolute path and opaque part.
protected static BitSet path_segments
          BitSet for path segments.
protected static BitSet pchar
          BitSet for pchar.
protected static BitSet percent
          The percent "%" character always has the reserved purpose of being the escape indicator, it must be escaped as "%25" in order to be used as data within a URI.
protected static BitSet port
          Port, a logical alias for digit.
protected  String protocolCharset
          The charset of the protocol used by this URI instance.
protected static BitSet query
          BitSet for query (alias for uric).
protected static BitSet reg_name
          BitSet for reg_name.
protected static BitSet rel_path
          BitSet for rel_path.
protected static BitSet rel_segment
          BitSet for rel_segment.
protected static BitSet relativeURI
          BitSet for relativeURI.
protected static BitSet reserved
          BitSet for reserved.
protected static char[] rootPath
          The root path.
protected static BitSet scheme
          BitSet for scheme.
protected static BitSet segment
          BitSet for segment.
protected static BitSet server
          Bitset for server.
static BitSet space
          BitSet for space.
protected static BitSet toplabel
          BitSet for toplabel.
protected static BitSet unreserved
          Data characters that are allowed in a URI but do not have a reserved purpose are called unreserved.
static BitSet unwise
          BitSet for unwise.
protected static BitSet URI_reference
          BitSet for URI-reference.
protected static BitSet uric
          BitSet for uric.
protected static BitSet uric_no_slash
          URI bitset for encoding typical non-slash characters.
protected static BitSet userinfo
          Bitset for userinfo.
static BitSet within_userinfo
          BitSet for within the userinfo component like user and password.
 
Constructor Summary
protected URI()
          Create an instance as an internal use
  URI(char[] escaped)
          Deprecated. Use #URI(String, boolean)
  URI(char[] escaped, String charset)
          Deprecated. Use #URI(String, boolean, String)
  URI(String original)
          Deprecated. Use #URI(String, boolean)
  URI(String s, boolean escaped)
          Construct a URI from a string with the given charset.
  URI(String s, boolean escaped, String charset)
          Construct a URI from a string with the given charset.
  URI(String original, String charset)
          Deprecated. Use #URI(String, boolean, String)
  URI(String scheme, String schemeSpecificPart, String fragment)
          Construct a general URI from the given components.
  URI(String scheme, String userinfo, String host, int port)
          Construct a general URI from the given components.
  URI(String scheme, String userinfo, String host, int port, String path)
          Construct a general URI from the given components.
  URI(String scheme, String userinfo, String host, int port, String path, String query)
          Construct a general URI from the given components.
  URI(String scheme, String userinfo, String host, int port, String path, String query, String fragment)
          Construct a general URI from the given components.
  URI(String scheme, String host, String path, String fragment)
          Construct a general URI from the given components.
  URI(String scheme, String authority, String path, String query, String fragment)
          Construct a general URI from the given components.
  URI(URI base, String relative)
          Deprecated. Use #URI(URI, String, boolean)
  URI(URI base, String relative, boolean escaped)
          Construct a general URI with the given relative URI string.
  URI(URI base, URI relative)
          Construct a general URI with the given relative URI.
 
Method Summary
 Object clone()
          Create and return a copy of this object, the URI-reference containing the userinfo component.
 int compareTo(Object obj)
          Compare this URI to another object.
protected static String decode(char[] component, String charset)
          Decodes URI encoded string.
protected static String decode(String component, String charset)
          Decodes URI encoded string.
protected static char[] encode(String original, BitSet allowed, String charset)
          Encodes URI string.
protected  boolean equals(char[] first, char[] second)
          Test if the first array is equal to the second array.
 boolean equals(Object obj)
          Test an object if this URI is equal to another.
 String getAboveHierPath()
          Get the level above the this hierarchy level.
 String getAuthority()
          Get the authority.
 String getCurrentHierPath()
          Get the current hierarchy level.
static String getDefaultDocumentCharset()
          Get the recommended default charset of the document.
static String getDefaultDocumentCharsetByLocale()
          Get the default charset of the document by locale.
static String getDefaultDocumentCharsetByPlatform()
          Get the default charset of the document by platform.
static String getDefaultProtocolCharset()
          Get the default charset of the protocol.
 String getEscapedAboveHierPath()
          Get the level above the this hierarchy level.
 String getEscapedAuthority()
          Get the escaped authority.
 String getEscapedCurrentHierPath()
          Get the escaped current hierarchy level.
 String getEscapedFragment()
          Get the escaped fragment.
 String getEscapedName()
          Get the escaped basename of the path.
 String getEscapedPath()
          Get the escaped path.
 String getEscapedPathQuery()
          Get the escaped query.
 String getEscapedQuery()
          Get the escaped query.
 String getEscapedURI()
          It can be gotten the URI character sequence.
 String getEscapedURIReference()
          Get the escaped URI reference string.
 String getEscapedUserinfo()
          Get the escaped userinfo.
 String getFragment()
          Get the fragment.
 String getHost()
          Get the host.
 String getName()
          Get the basename of the path.
 String getPath()
          Get the path.
 String getPathQuery()
          Get the path and query.
 int getPort()
          Get the port.
 String getProtocolCharset()
          Get the protocol charset used by this current URI instance.
 String getQuery()
          Get the query.
 char[] getRawAboveHierPath()
          Get the level above the this hierarchy level.
 char[] getRawAuthority()
          Get the raw-escaped authority.
 char[] getRawCurrentHierPath()
          Get the raw-escaped current hierarchy level.
protected  char[] getRawCurrentHierPath(char[] path)
          Get the raw-escaped current hierarchy level in the given path.
 char[] getRawFragment()
          Get the raw-escaped fragment.
 char[] getRawHost()
          Get the host.
 char[] getRawName()
          Get the raw-escaped basename of the path.
 char[] getRawPath()
          Get the raw-escaped path.
 char[] getRawPathQuery()
          Get the raw-escaped path and query.
 char[] getRawQuery()
          Get the raw-escaped query.
 char[] getRawScheme()
          Get the scheme.
 char[] getRawURI()
          It can be gotten the URI character sequence.
 char[] getRawURIReference()
          Get the URI reference character sequence.
 char[] getRawUserinfo()
          Get the raw-escaped userinfo.
 String getScheme()
          Get the scheme.
 String getURI()
          It can be gotten the URI character sequence.
 String getURIReference()
          Get the original URI reference string.
 String getUserinfo()
          Get the userinfo.
 boolean hasAuthority()
          Tell whether or not this URI has authority.
 boolean hasFragment()
          Tell whether or not this URI has fragment.
 int hashCode()
          Return a hash code for this URI.
 boolean hasQuery()
          Tell whether or not this URI has query.
 boolean hasUserinfo()
          Tell whether or not this URI has userinfo.
protected  int indexFirstOf(char[] s, char delim)
          Get the earlier index that to be searched for the first occurrance in one of any of the given array.
protected  int indexFirstOf(char[] s, char delim, int offset)
          Get the earlier index that to be searched for the first occurrance in one of any of the given array.
protected  int indexFirstOf(String s, String delims)
          Get the earlier index that to be searched for the first occurrance in one of any of the given string.
protected  int indexFirstOf(String s, String delims, int offset)
          Get the earlier index that to be searched for the first occurrance in one of any of the given string.
 boolean isAbsoluteURI()
          Tell whether or not this URI is absolute.
 boolean isAbsPath()
          Tell whether or not the relativeURI or hier_part of this URI is abs_path.
 boolean isHierPart()
          Tell whether or not the absoluteURI of this URI is hier_part.
 boolean isHostname()
          Tell whether or not the host part of this URI is hostname.
 boolean isIPv4address()
          Tell whether or not the host part of this URI is IPv4address.
 boolean isIPv6reference()
          Tell whether or not the host part of this URI is IPv6reference.
 boolean isNetPath()
          Tell whether or not the relativeURI or heir_part of this URI is net_path.
 boolean isOpaquePart()
          Tell whether or not the absoluteURI of this URI is opaque_part.
 boolean isRegName()
          Tell whether or not the authority component of this URI is reg_name.
 boolean isRelativeURI()
          Tell whether or not this URI is relative.
 boolean isRelPath()
          Tell whether or not the relativeURI of this URI is rel_path.
 boolean isServer()
          Tell whether or not the authority component of this URI is server.
 void normalize()
          Normalizes the path part of this URI.
protected  char[] normalize(char[] path)
          Normalize the given hier path part.
protected  void parseAuthority(String original, boolean escaped)
          Parse the authority component.
protected  void parseUriReference(String original, boolean escaped)
          In order to avoid any possilbity of conflict with non-ASCII characters, Parse a URI reference as a String with the character encoding of the local system or the document.
protected  boolean prevalidate(String component, BitSet disallowed)
          Pre-validate the unescaped URI string within a specific component.
protected  char[] removeFragmentIdentifier(char[] component)
          Remove the fragment identifier of the given component.
protected  char[] resolvePath(char[] basePath, char[] relPath)
          Resolve the base and relative path.
static void setDefaultDocumentCharset(String charset)
          Set the default charset of the document.
static void setDefaultProtocolCharset(String charset)
          Set the default charset of the protocol.
 void setEscapedAuthority(String escapedAuthority)
          Set the authority.
 void setEscapedFragment(String escapedFragment)
          Set the escaped fragment string.
 void setEscapedPath(String escapedPath)
          Set the escaped path.
 void setEscapedQuery(String escapedQuery)
          Set the escaped query string.
 void setFragment(String fragment)
          Set the fragment.
 void setPath(String path)
          Set the path.
 void setQuery(String query)
          Set the query.
 void setRawAuthority(char[] escapedAuthority)
          Set the authority.
 void setRawFragment(char[] escapedFragment)
          Set the raw-escaped fragment.
 void setRawPath(char[] escapedPath)
          Set the raw-escaped path.
 void setRawQuery(char[] escapedQuery)
          Set the raw-escaped query.
protected  void setURI()
          Once it's parsed successfully, set this URI.
 String toString()
          Get the escaped URI string.
protected  boolean validate(char[] component, BitSet generous)
          Validate the URI characters within a specific component.
protected  boolean validate(char[] component, int soffset, int eoffset, BitSet generous)
          Validate the URI characters within a specific component.
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

hash

protected int hash
Cache the hash code for this URI.


_uri

protected char[] _uri
This Uniform Resource Identifier (URI). The URI is always in an "escaped" form, since escaping or unescaping a completed URI might change its semantics.


protocolCharset

protected String protocolCharset
The charset of the protocol used by this URI instance.


defaultProtocolCharset

protected static String defaultProtocolCharset
The default charset of the protocol. RFC 2277, 2396


defaultDocumentCharset

protected static String defaultDocumentCharset
The default charset of the document. RFC 2277, 2396 The platform's charset is used for the document by default.


defaultDocumentCharsetByLocale

protected static String defaultDocumentCharsetByLocale

defaultDocumentCharsetByPlatform

protected static String defaultDocumentCharsetByPlatform

_scheme

protected char[] _scheme
The scheme.


_opaque

protected char[] _opaque
The opaque.


_authority

protected char[] _authority
The authority.


_userinfo

protected char[] _userinfo
The userinfo.


_host

protected char[] _host
The host.


_port

protected int _port
The port.


_path

protected char[] _path
The path.


_query

protected char[] _query
The query.


_fragment

protected char[] _fragment
The fragment.


rootPath

protected static final char[] rootPath
The root path.


percent

protected static final BitSet percent
The percent "%" character always has the reserved purpose of being the escape indicator, it must be escaped as "%25" in order to be used as data within a URI.


digit

protected static final BitSet digit
BitSet for digit.

 digit    = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
            "8" | "9"
 


alpha

protected static final BitSet alpha
BitSet for alpha.

 alpha         = lowalpha | upalpha
 


alphanum

protected static final BitSet alphanum
BitSet for alphanum (join of alpha & digit).

  alphanum      = alpha | digit
 


hex

protected static final BitSet hex
BitSet for hex.

 hex           = digit | "A" | "B" | "C" | "D" | "E" | "F" |
                         "a" | "b" | "c" | "d" | "e" | "f"
 


escaped

protected static final BitSet escaped
BitSet for escaped.

 escaped       = "%" hex hex
 


mark

protected static final BitSet mark
BitSet for mark.

 mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
                 "(" | ")"
 


unreserved

protected static final BitSet unreserved
Data characters that are allowed in a URI but do not have a reserved purpose are called unreserved.

 unreserved    = alphanum | mark
 


reserved

protected static final BitSet reserved
BitSet for reserved.

 reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
                 "$" | ","
 


uric

protected static final BitSet uric
BitSet for uric.

 uric          = reserved | unreserved | escaped
 


fragment

protected static final BitSet fragment
BitSet for fragment (alias for uric).

 fragment      = *uric
 


query

protected static final BitSet query
BitSet for query (alias for uric).

 query         = *uric
 


pchar

protected static final BitSet pchar
BitSet for pchar.

 pchar         = unreserved | escaped |
                 ":" | "@" | "&" | "=" | "+" | "$" | ","
 


param

protected static final BitSet param
BitSet for param (alias for pchar).

 param         = *pchar
 


segment

protected static final BitSet segment
BitSet for segment.

 segment       = *pchar *( ";" param )
 


path_segments

protected static final BitSet path_segments
BitSet for path segments.

 path_segments = segment *( "/" segment )
 


abs_path

protected static final BitSet abs_path
URI absolute path.

 abs_path      = "/"  path_segments
 


uric_no_slash

protected static final BitSet uric_no_slash
URI bitset for encoding typical non-slash characters.

 uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
                 "&" | "=" | "+" | "$" | ","
 


opaque_part

protected static final BitSet opaque_part
URI bitset that combines uric_no_slash and uric.

 opaque_part   = uric_no_slash *uric
 


path

protected static final BitSet path
URI bitset that combines absolute path and opaque part.

 path          = [ abs_path | opaque_part ]
 


port

protected static final BitSet port
Port, a logical alias for digit.


IPv4address

protected static final BitSet IPv4address
Bitset that combines digit and dot fo IPv$address.

 IPv4address   = 1*digit "." 1*digit "." 1*digit "." 1*digit
 


IPv6address

protected static final BitSet IPv6address
RFC 2373.

 IPv6address = hexpart [ ":" IPv4address ]
 


IPv6reference

protected static final BitSet IPv6reference
RFC 2732, 2373.

 IPv6reference   = "[" IPv6address "]"
 


toplabel

protected static final BitSet toplabel
BitSet for toplabel.

 toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
 


domainlabel

protected static final BitSet domainlabel
BitSet for domainlabel.

 domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
 


hostname

protected static final BitSet hostname
BitSet for hostname.

 hostname      = *( domainlabel "." ) toplabel [ "." ]
 


host

protected static final BitSet host
BitSet for host.

 host          = hostname | IPv4address | IPv6reference
 


hostport

protected static final BitSet hostport
BitSet for hostport.

 hostport      = host [ ":" port ]
 


userinfo

protected static final BitSet userinfo
Bitset for userinfo.

 userinfo      = *( unreserved | escaped |
                    ";" | ":" | "&" | "=" | "+" | "$" | "," )
 


within_userinfo

public static final BitSet within_userinfo
BitSet for within the userinfo component like user and password.


server

protected static final BitSet server
Bitset for server.

 server        = [ [ userinfo "@" ] hostport ]
 


reg_name

protected static final BitSet reg_name
BitSet for reg_name.

 reg_name      = 1*( unreserved | escaped | "$" | "," |
                     ";" | ":" | "@" | "&" | "=" | "+" )
 


authority

protected static final BitSet authority
BitSet for authority.

 authority     = server | reg_name
 


scheme

protected static final BitSet scheme
BitSet for scheme.

 scheme        = alpha *( alpha | digit | "+" | "-" | "." )
 


rel_segment

protected static final BitSet rel_segment
BitSet for rel_segment.

 rel_segment   = 1*( unreserved | escaped |
                     ";" | "@" | "&" | "=" | "+" | "$" | "," )
 


rel_path

protected static final BitSet rel_path
BitSet for rel_path.

 rel_path      = rel_segment [ abs_path ]
 


net_path

protected static final BitSet net_path
BitSet for net_path.

 net_path      = "//" authority [ abs_path ]
 


hier_part

protected static final BitSet hier_part
BitSet for hier_part.

 hier_part     = ( net_path | abs_path ) [ "?" query ]
 


relativeURI

protected static final BitSet relativeURI
BitSet for relativeURI.

 relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
 


absoluteURI

protected static final BitSet absoluteURI
BitSet for absoluteURI.

 absoluteURI   = scheme ":" ( hier_part | opaque_part )
 


URI_reference

protected static final BitSet URI_reference
BitSet for URI-reference.

 URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
 


control

public static final BitSet control
BitSet for control.


space

public static final BitSet space
BitSet for space.


delims

public static final BitSet delims
BitSet for delims.


unwise

public static final BitSet unwise
BitSet for unwise.


disallowed_rel_path

public static final BitSet disallowed_rel_path
Disallowed rel_path before escaping.


disallowed_opaque_part

public static final BitSet disallowed_opaque_part
Disallowed opaque_part before escaping.


allowed_authority

public static final BitSet allowed_authority
Those characters that are allowed for the authority component.


allowed_opaque_part

public static final BitSet allowed_opaque_part
Those characters that are allowed for the opaque_part.


allowed_reg_name

public static final BitSet allowed_reg_name
Those characters that are allowed for the reg_name.


allowed_userinfo

public static final BitSet allowed_userinfo
Those characters that are allowed for the userinfo component.


allowed_within_userinfo

public static final BitSet allowed_within_userinfo
Those characters that are allowed for within the userinfo component.


allowed_IPv6reference

public static final BitSet allowed_IPv6reference
Those characters that are allowed for the IPv6reference component. The characters '[', ']' in IPv6reference should be excluded.


allowed_host

public static final BitSet allowed_host
Those characters that are allowed for the host component. The characters '[', ']' in IPv6reference should be excluded.


allowed_within_authority

public static final BitSet allowed_within_authority
Those characters that are allowed for the authority component.


allowed_abs_path

public static final BitSet allowed_abs_path
Those characters that are allowed for the abs_path.


allowed_rel_path

public static final BitSet allowed_rel_path
Those characters that are allowed for the rel_path.


allowed_within_path

public static final BitSet allowed_within_path
Those characters that are allowed within the path.


allowed_query

public static final BitSet allowed_query
Those characters that are allowed for the query component.


allowed_within_query

public static final BitSet allowed_within_query
Those characters that are allowed within the query component.


allowed_fragment

public static final BitSet allowed_fragment
Those characters that are allowed for the fragment component.


_is_hier_part

protected boolean _is_hier_part

_is_opaque_part

protected boolean _is_opaque_part

_is_net_path

protected boolean _is_net_path

_is_abs_path

protected boolean _is_abs_path

_is_rel_path

protected boolean _is_rel_path

_is_reg_name

protected boolean _is_reg_name

_is_server

protected boolean _is_server

_is_hostname

protected boolean _is_hostname

_is_IPv4address

protected boolean _is_IPv4address

_is_IPv6reference

protected boolean _is_IPv6reference
Constructor Detail

URI

protected URI()
Create an instance as an internal use


URI

public URI(String s,
           boolean escaped,
           String charset)
    throws URIException,
           NullPointerException
Construct a URI from a string with the given charset. The input string can be either in escaped or unescaped form.

Parameters:
s - URI character sequence
escaped - true if URI character sequence is in escaped form. false otherwise.
charset - the charset string to do escape encoding, if required
Throws:
URIException - If the URI cannot be created.
NullPointerException - if input string is null
Since:
3.0
See Also:
getProtocolCharset()

URI

public URI(String s,
           boolean escaped)
    throws URIException,
           NullPointerException
Construct a URI from a string with the given charset. The input string can be either in escaped or unescaped form.

Parameters:
s - URI character sequence
escaped - true if URI character sequence is in escaped form. false otherwise.
Throws:
URIException - If the URI cannot be created.
NullPointerException - if input string is null
Since:
3.0
See Also:
getProtocolCharset()

URI

public URI(char[] escaped,
           String charset)
    throws URIException,
           NullPointerException
Deprecated. Use #URI(String, boolean, String)

Construct a URI as an escaped form of a character array with the given charset.

Parameters:
escaped - the URI character sequence
charset - the charset string to do escape encoding
Throws:
URIException - If the URI cannot be created.
NullPointerException - if escaped is null
See Also:
getProtocolCharset()

URI

public URI(char[] escaped)
    throws URIException,
           NullPointerException
Deprecated. Use #URI(String, boolean)

Construct a URI as an escaped form of a character array. An URI can be placed within double-quotes or angle brackets like "http://test.com/" and <http://test.com/>

Parameters:
escaped - the URI character sequence
Throws:
URIException - If the URI cannot be created.
NullPointerException - if escaped is null
See Also:
getDefaultProtocolCharset()

URI

public URI(String original,
           String charset)
    throws URIException
Deprecated. Use #URI(String, boolean, String)

Construct a URI from the given string with the given charset.

Parameters:
original - the string to be represented to URI character sequence It is one of absoluteURI and relativeURI.
charset - the charset string to do escape encoding
Throws:
URIException - If the URI cannot be created.
See Also:
getProtocolCharset()

URI

public URI(String original)
    throws URIException
Deprecated. Use #URI(String, boolean)

Construct a URI from the given string.

   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
 

An URI can be placed within double-quotes or angle brackets like "http://test.com/" and <http://test.com/>

Parameters:
original - the string to be represented to URI character sequence It is one of absoluteURI and relativeURI.
Throws:
URIException - If the URI cannot be created.
See Also:
getDefaultProtocolCharset()

URI

public URI(String scheme,
           String schemeSpecificPart,
           String fragment)
    throws URIException
Construct a general URI from the given components.

   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
   absoluteURI   = scheme ":" ( hier_part | opaque_part )
   opaque_part   = uric_no_slash *uric
 

It's for absolute URI = <scheme>:<scheme-specific-part># <fragment>.

Parameters:
scheme - the scheme string
schemeSpecificPart - scheme_specific_part
fragment - the fragment string
Throws:
URIException - If the URI cannot be created.
See Also:
getDefaultProtocolCharset()

URI

public URI(String scheme,
           String authority,
           String path,
           String query,
           String fragment)
    throws URIException
Construct a general URI from the given components.

   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
   absoluteURI   = scheme ":" ( hier_part | opaque_part )
   relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
   hier_part     = ( net_path | abs_path ) [ "?" query ]
 

It's for absolute URI = <scheme>:<path>?<query>#< fragment> and relative URI = <path>?<query>#<fragment >.

Parameters:
scheme - the scheme string
authority - the authority string
path - the path string
query - the query string
fragment - the fragment string
Throws:
URIException - If the new URI cannot be created.
See Also:
getDefaultProtocolCharset()

URI

public URI(String scheme,
           String userinfo,
           String host,
           int port)
    throws URIException
Construct a general URI from the given components.

Parameters:
scheme - the scheme string
userinfo - the userinfo string
host - the host string
port - the port number
Throws:
URIException - If the new URI cannot be created.
See Also:
getDefaultProtocolCharset()

URI

public URI(String scheme,
           String userinfo,
           String host,
           int port,
           String path)
    throws URIException
Construct a general URI from the given components.

Parameters:
scheme - the scheme string
userinfo - the userinfo string
host - the host string
port - the port number
path - the path string
Throws:
URIException - If the new URI cannot be created.
See Also:
getDefaultProtocolCharset()

URI

public URI(String scheme,
           String userinfo,
           String host,
           int port,
           String path,
           String query)
    throws URIException
Construct a general URI from the given components.

Parameters:
scheme - the scheme string
userinfo - the userinfo string
host - the host string
port - the port number
path - the path string
query - the query string
Throws:
URIException - If the new URI cannot be created.
See Also:
getDefaultProtocolCharset()

URI

public URI(String scheme,
           String userinfo,
           String host,
           int port,
           String path,
           String query,
           String fragment)
    throws URIException
Construct a general URI from the given components.

Parameters:
scheme - the scheme string
userinfo - the userinfo string
host - the host string
port - the port number
path - the path string
query - the query string
fragment - the fragment string
Throws:
URIException - If the new URI cannot be created.
See Also:
getDefaultProtocolCharset()

URI

public URI(String scheme,
           String host,
           String path,
           String fragment)
    throws URIException
Construct a general URI from the given components.

Parameters:
scheme - the scheme string
host - the host string
path - the path string
fragment - the fragment string
Throws:
URIException - If the new URI cannot be created.
See Also:
getDefaultProtocolCharset()

URI

public URI(URI base,
           String relative)
    throws URIException
Deprecated. Use #URI(URI, String, boolean)

Construct a general URI with the given relative URI string.

Parameters:
base - the base URI
relative - the relative URI string
Throws:
URIException - If the new URI cannot be created.

URI

public URI(URI base,
           String relative,
           boolean escaped)
    throws URIException
Construct a general URI with the given relative URI string.

Parameters:
base - the base URI
relative - the relative URI string
escaped - true if URI character sequence is in escaped form. false otherwise.
Throws:
URIException - If the new URI cannot be created.
Since:
3.0

URI

public URI(URI base,
           URI relative)
    throws URIException
Construct a general URI with the given relative URI.

   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
   relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
 

Resolving Relative References to Absolute Form. Examples of Resolving Relative URI References Within an object with a well-defined base URI of

   http://a/b/c/d;p?q
 

the relative URI would be resolved as follows: Normal Examples

   g:h           =  g:h
   g             =  http://a/b/c/g
   ./g           =  http://a/b/c/g
   g/            =  http://a/b/c/g/
   /g            =  http://a/g
   //g           =  http://g
   ?y            =  http://a/b/c/?y
   g?y           =  http://a/b/c/g?y
   #s            =  (current document)#s
   g#s           =  http://a/b/c/g#s
   g?y#s         =  http://a/b/c/g?y#s
   ;x            =  http://a/b/c/;x
   g;x           =  http://a/b/c/g;x
   g;x?y#s       =  http://a/b/c/g;x?y#s
   .             =  http://a/b/c/
   ./            =  http://a/b/c/
   ..            =  http://a/b/
   ../           =  http://a/b/
   ../g          =  http://a/b/g
   ../..         =  http://a/
   ../../        =  http://a/ 
   ../../g       =  http://a/g
 

Some URI schemes do not allow a hierarchical syntax matching the syntax, and thus cannot use relative references.

Parameters:
base - the base URI
relative - the relative URI
Throws:
URIException - If the new URI cannot be created.
Method Detail

encode

protected static char[] encode(String original,
                               BitSet allowed,
                               String charset)
                        throws URIException
Encodes URI string. This is a two mapping, one from original characters to octets, and subsequently a second from octets to URI characters:

   original character sequence->octet sequence->URI character sequence
 

An escaped octet is encoded as a character triplet, consisting of the percent character "%" followed by the two hexadecimal digits representing the octet code. For example, "%20" is the escaped encoding for the US-ASCII space character.

Conversion from the local filesystem character set to UTF-8 will normally involve a two step process. First convert the local character set to the UCS; then convert the UCS to UTF-8. The first step in the process can be performed by maintaining a mapping table that includes the local character set code and the corresponding UCS code. The next step is to convert the UCS character code to the UTF-8 encoding.

Mapping between vendor codepages can be done in a very similar manner as described above.

The only time escape encodings can allowedly be made is when a URI is being created from its component parts. The escape and validate methods are internally performed within this method.

Parameters:
original - the original character sequence
allowed - those characters that are allowed within a component
charset - the protocol charset
Returns:
URI character sequence
Throws:
URIException - null component or unsupported character encoding

decode

protected static String decode(char[] component,
                               String charset)
                        throws URIException
Decodes URI encoded string. This is a two mapping, one from URI characters to octets, and subsequently a second from octets to original characters:

   URI character sequence->octet sequence->original character sequence
 

A URI must be separated into its components before the escaped characters within those components can be allowedly decoded.

Notice that there is a chance that URI characters that are non UTF-8 may be parsed as valid UTF-8. A recent non-scientific analysis found that EUC encoded Japanese words had a 2.7% false reading; SJIS had a 0.0005% false reading; other encoding such as ASCII or KOI-8 have a 0% false reading.

The percent "%" character always has the reserved purpose of being the escape indicator, it must be escaped as "%25" in order to be used as data within a URI.

The unescape method is internally performed within this method.

Parameters:
component - the URI character sequence
charset - the protocol charset
Returns:
original character sequence
Throws:
URIException - incomplete trailing escape pattern or unsupported character encoding

decode

protected static String decode(String component,
                               String charset)
                        throws URIException
Decodes URI encoded string. This is a two mapping, one from URI characters to octets, and subsequently a second from octets to original characters:

   URI character sequence->octet sequence->original character sequence
 

A URI must be separated into its components before the escaped characters within those components can be allowedly decoded.

Notice that there is a chance that URI characters that are non UTF-8 may be parsed as valid UTF-8. A recent non-scientific analysis found that EUC encoded Japanese words had a 2.7% false reading; SJIS had a 0.0005% false reading; other encoding such as ASCII or KOI-8 have a 0% false reading.

The percent "%" character always has the reserved purpose of being the escape indicator, it must be escaped as "%25" in order to be used as data within a URI.

The unescape method is internally performed within this method.

Parameters:
component - the URI character sequence
charset - the protocol charset
Returns:
original character sequence
Throws:
URIException - incomplete trailing escape pattern or unsupported character encoding
Since:
3.0

prevalidate

protected boolean prevalidate(String component,
                              BitSet disallowed)
Pre-validate the unescaped URI string within a specific component.

Parameters:
component - the component string within the component
disallowed - those characters disallowed within the component
Returns:
if true, it doesn't have the disallowed characters if false, the component is undefined or an incorrect one

validate

protected boolean validate(char[] component,
                           BitSet generous)
Validate the URI characters within a specific component. The component must be performed after escape encoding. Or it doesn't include escaped characters.

Parameters:
component - the characters sequence within the component
generous - those characters that are allowed within a component
Returns:
if true, it's the correct URI character sequence

validate

protected boolean validate(char[] component,
                           int soffset,
                           int eoffset,
                           BitSet generous)
Validate the URI characters within a specific component. The component must be performed after escape encoding. Or it doesn't include escaped characters.

It's not that much strict, generous. The strict validation might be performed before being called this method.

Parameters:
component - the characters sequence within the component
soffset - the starting offset of the given component
eoffset - the ending offset of the given component if -1, it means the length of the component
generous - those characters that are allowed within a component
Returns:
if true, it's the correct URI character sequence

parseUriReference

protected void parseUriReference(String original,
                                 boolean escaped)
                          throws URIException
In order to avoid any possilbity of conflict with non-ASCII characters, Parse a URI reference as a String with the character encoding of the local system or the document.

The following line is the regular expression for breaking-down a URI reference into its components.

   ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
    12            3  4          5       6  7        8 9
 

For example, matching the above expression to http://jakarta.apache.org/ietf/uri/#Related results in the following subexpression matches:

               $1 = http:
  scheme    =  $2 = http
               $3 = //jakarta.apache.org
  authority =  $4 = jakarta.apache.org
  path      =  $5 = /ietf/uri/
               $6 = 
  query     =  $7 = 
               $8 = #Related
  fragment  =  $9 = Related
 

Parameters:
original - the original character sequence
escaped - true if original is escaped
Throws:
URIException - If an error occurs.

indexFirstOf

protected int indexFirstOf(String s,
                           String delims)
Get the earlier index that to be searched for the first occurrance in one of any of the given string.

Parameters:
s - the string to be indexed
delims - the delimiters used to index
Returns:
the earlier index if there are delimiters

indexFirstOf

protected int indexFirstOf(String s,
                           String delims,
                           int offset)
Get the earlier index that to be searched for the first occurrance in one of any of the given string.

Parameters:
s - the string to be indexed
delims - the delimiters used to index
offset - the from index
Returns:
the earlier index if there are delimiters

indexFirstOf

protected int indexFirstOf(char[] s,
                           char delim)
Get the earlier index that to be searched for the first occurrance in one of any of the given array.

Parameters:
s - the character array to be indexed
delim - the delimiter used to index
Returns:
the ealier index if there are a delimiter

indexFirstOf

protected int indexFirstOf(char[] s,
                           char delim,
                           int offset)
Get the earlier index that to be searched for the first occurrance in one of any of the given array.

Parameters:
s - the character array to be indexed
delim - the delimiter used to index
offset - The offset.
Returns:
the ealier index if there is a delimiter

parseAuthority

protected void parseAuthority(String original,
                              boolean escaped)
                       throws URIException
Parse the authority component.

Parameters:
original - the original character sequence of authority component
escaped - true if original is escaped
Throws:
URIException - If an error occurs.

setURI

protected void setURI()
Once it's parsed successfully, set this URI.

See Also:
getRawURI()

isAbsoluteURI

public boolean isAbsoluteURI()
Tell whether or not this URI is absolute.

Returns:
true iif this URI is absoluteURI

isRelativeURI

public boolean isRelativeURI()
Tell whether or not this URI is relative.

Returns:
true iif this URI is relativeURI

isHierPart

public boolean isHierPart()
Tell whether or not the absoluteURI of this URI is hier_part.

Returns:
true iif the absoluteURI is hier_part

isOpaquePart

public boolean isOpaquePart()
Tell whether or not the absoluteURI of this URI is opaque_part.

Returns:
true iif the absoluteURI is opaque_part

isNetPath

public boolean isNetPath()
Tell whether or not the relativeURI or heir_part of this URI is net_path. It's the same function as the has_authority() method.

Returns:
true iif the relativeURI or heir_part is net_path
See Also:
hasAuthority()

isAbsPath

public boolean isAbsPath()
Tell whether or not the relativeURI or hier_part of this URI is abs_path.

Returns:
true iif the relativeURI or hier_part is abs_path

isRelPath

public boolean isRelPath()
Tell whether or not the relativeURI of this URI is rel_path.

Returns:
true iif the relativeURI is rel_path

hasAuthority

public boolean hasAuthority()
Tell whether or not this URI has authority. It's the same function as the is_net_path() method.

Returns:
true iif this URI has authority
See Also:
isNetPath()

isRegName

public boolean isRegName()
Tell whether or not the authority component of this URI is reg_name.

Returns:
true iif the authority component is reg_name

isServer

public boolean isServer()
Tell whether or not the authority component of this URI is server.

Returns:
true iif the authority component is server

hasUserinfo

public boolean hasUserinfo()
Tell whether or not this URI has userinfo.

Returns:
true iif this URI has userinfo

isHostname

public boolean isHostname()
Tell whether or not the host part of this URI is hostname.

Returns:
true iif the host part is hostname

isIPv4address

public boolean isIPv4address()
Tell whether or not the host part of this URI is IPv4address.

Returns:
true iif the host part is IPv4address

isIPv6reference

public boolean isIPv6reference()
Tell whether or not the host part of this URI is IPv6reference.

Returns:
true iif the host part is IPv6reference

hasQuery

public boolean hasQuery()
Tell whether or not this URI has query.

Returns:
true iif this URI has query

hasFragment

public boolean hasFragment()
Tell whether or not this URI has fragment.

Returns:
true iif this URI has fragment

setDefaultProtocolCharset

public static void setDefaultProtocolCharset(String charset)
                                      throws URI.DefaultCharsetChanged
Set the default charset of the protocol.

The character set used to store files SHALL remain a local decision and MAY depend on the capability of local operating systems. Prior to the exchange of URIs they SHOULD be converted into a ISO/IEC 10646 format and UTF-8 encoded. This approach, while allowing international exchange of URIs, will still allow backward compatibility with older systems because the code set positions for ASCII characters are identical to the one byte sequence in UTF-8.

An individual URI scheme may require a single charset, define a default charset, or provide a way to indicate the charset used.

Always all the time, the setter method is always succeeded and throws DefaultCharsetChanged exception. So API programmer must follow the following way:

  import org.apache.util.URI$DefaultCharsetChanged;
      .
      .
      .
  try {
      URI.setDefaultProtocolCharset("UTF-8");
  } catch (DefaultCharsetChanged cc) {
      // CASE 1: the exception could be ignored, when it is set by user
      if (cc.getReasonCode() == DefaultCharsetChanged.PROTOCOL_CHARSET) {
      // CASE 2: let user know the default protocol charset changed
      } else {
      // CASE 2: let user know the default document charset changed
      }
  }
  
The API programmer is responsible to set the correct charset. And each application should remember its own charset to support.

Parameters:
charset - the default charset for each protocol
Throws:
URI.DefaultCharsetChanged - default charset changed

getDefaultProtocolCharset

public static String getDefaultProtocolCharset()
Get the default charset of the protocol.

An individual URI scheme may require a single charset, define a default charset, or provide a way to indicate the charset used.

To work globally either requires support of a number of character sets and to be able to convert between them, or the use of a single preferred character set. For support of global compatibility it is STRONGLY RECOMMENDED that clients and servers use UTF-8 encoding when exchanging URIs.

Returns:
the default charset string

getProtocolCharset

public String getProtocolCharset()
Get the protocol charset used by this current URI instance. It was set by the constructor for this instance. If it was not set by contructor, it will return the default protocol charset.

Returns:
the protocol charset string
See Also:
getDefaultProtocolCharset()

setDefaultDocumentCharset

public static void setDefaultDocumentCharset(String charset)
                                      throws URI.DefaultCharsetChanged
Set the default charset of the document.

Notice that it will be possible to contain mixed characters (e.g. ftp://host/KoreanNamespace/ChineseResource). To handle the Bi-directional display of these character sets, the protocol charset could be simply used again. Because it's not yet implemented that the insertion of BIDI control characters at different points during composition is extracted.

Always all the time, the setter method is always succeeded and throws DefaultCharsetChanged exception. So API programmer must follow the following way:

  import org.apache.util.URI$DefaultCharsetChanged;
      .
      .
      .
  try {
      URI.setDefaultDocumentCharset("EUC-KR");
  } catch (DefaultCharsetChanged cc) {
      // CASE 1: the exception could be ignored, when it is set by user
      if (cc.getReasonCode() == DefaultCharsetChanged.DOCUMENT_CHARSET) {
      // CASE 2: let user know the default document charset changed
      } else {
      // CASE 2: let user know the default protocol charset changed
      }
  }
  
The API programmer is responsible to set the correct charset. And each application should remember its own charset to support.

Parameters:
charset - the default charset for the document
Throws:
URI.DefaultCharsetChanged - default charset changed

getDefaultDocumentCharset

public static String getDefaultDocumentCharset()
Get the recommended default charset of the document.

Returns:
the default charset string

getDefaultDocumentCharsetByLocale

public static String getDefaultDocumentCharsetByLocale()
Get the default charset of the document by locale.

Returns:
the default charset string by locale

getDefaultDocumentCharsetByPlatform

public static String getDefaultDocumentCharsetByPlatform()
Get the default charset of the document by platform.

Returns:
the default charset string by platform

getRawScheme

public char[] getRawScheme()
Get the scheme.

Returns:
the scheme

getScheme

public String getScheme()
Get the scheme.

Returns:
the scheme null if undefined scheme

setRawAuthority

public void setRawAuthority(char[] escapedAuthority)
                     throws URIException,
                            NullPointerException
Set the authority. It can be one type of server, hostport, hostname, IPv4address, IPv6reference and reg_name.

   authority     = server | reg_name
 

Parameters:
escapedAuthority - the raw escaped authority
Throws:
URIException - If parseAuthority(java.lang.String,boolean) fails
NullPointerException - null authority

setEscapedAuthority

public void setEscapedAuthority(String escapedAuthority)
                         throws URIException
Set the authority. It can be one type of server, hostport, hostname, IPv4address, IPv6reference and reg_name. Note that there is no setAuthority method by the escape encoding reason.

Parameters:
escapedAuthority - the escaped authority string
Throws:
URIException - If parseAuthority(java.lang.String,boolean) fails

getRawAuthority

public char[] getRawAuthority()
Get the raw-escaped authority.

Returns:
the raw-escaped authority

getEscapedAuthority

public String getEscapedAuthority()
Get the escaped authority.

Returns:
the escaped authority

getAuthority

public String getAuthority()
                    throws URIException
Get the authority.

Returns:
the authority
Throws:
URIException - If decode(char[], java.lang.String) fails

getRawUserinfo

public char[] getRawUserinfo()
Get the raw-escaped userinfo.

Returns:
the raw-escaped userinfo
See Also:
getAuthority()

getEscapedUserinfo

public String getEscapedUserinfo()
Get the escaped userinfo.

Returns:
the escaped userinfo
See Also:
getAuthority()

getUserinfo

public String getUserinfo()
                   throws URIException
Get the userinfo.

Returns:
the userinfo
Throws:
URIException - If decode(char[], java.lang.String) fails
See Also:
getAuthority()

getRawHost

public char[] getRawHost()
Get the host.

   host          = hostname | IPv4address | IPv6reference
 

Returns:
the host
See Also:
getAuthority()

getHost

public String getHost()
               throws URIException
Get the host.

   host          = hostname | IPv4address | IPv6reference
 

Returns:
the host
Throws:
URIException - If decode(char[], java.lang.String) fails
See Also:
getAuthority()

getPort

public int getPort()
Get the port. In order to get the specfic default port, the specific protocol-supported class extended from the URI class should be used. It has the server-based naming authority.

Returns:
the port if -1, it has the default port for the scheme or the server-based naming authority is not supported in the specific URI.

setRawPath

public void setRawPath(char[] escapedPath)
                throws URIException
Set the raw-escaped path.

Parameters:
escapedPath - the path character sequence
Throws:
URIException - encoding error or not proper for initial instance
See Also:
encode(java.lang.String, java.util.BitSet, java.lang.String)

setEscapedPath

public void setEscapedPath(String escapedPath)
                    throws URIException
Set the escaped path.

Parameters:
escapedPath - the escaped path string
Throws:
URIException - encoding error or not proper for initial instance
See Also:
encode(java.lang.String, java.util.BitSet, java.lang.String)

setPath

public void setPath(String path)
             throws URIException
Set the path.

Parameters:
path - the path string
Throws:
URIException - set incorrectly or fragment only
See Also:
encode(java.lang.String, java.util.BitSet, java.lang.String)

resolvePath

protected char[] resolvePath(char[] basePath,
                             char[] relPath)
                      throws URIException
Resolve the base and relative path.

Parameters:
basePath - a character array of the basePath
relPath - a character array of the relPath
Returns:
the resolved path
Throws:
URIException - no more higher path level to be resolved

getRawCurrentHierPath

protected char[] getRawCurrentHierPath(char[] path)
                                throws URIException
Get the raw-escaped current hierarchy level in the given path. If the last namespace is a collection, the slash mark ('/') should be ended with at the last character of the path string.

Parameters:
path - the path
Returns:
the current hierarchy level
Throws:
URIException - no hierarchy level

getRawCurrentHierPath

public char[] getRawCurrentHierPath()
                             throws URIException
Get the raw-escaped current hierarchy level.

Returns:
the raw-escaped current hierarchy level
Throws:
URIException - If getRawCurrentHierPath(char[]) fails.

getEscapedCurrentHierPath

public String getEscapedCurrentHierPath()
                                 throws URIException
Get the escaped current hierarchy level.

Returns:
the escaped current hierarchy level
Throws:
URIException - If getRawCurrentHierPath(char[]) fails.

getCurrentHierPath

public String getCurrentHierPath()
                          throws URIException
Get the current hierarchy level.

Returns:
the current hierarchy level
Throws:
URIException - If getRawCurrentHierPath(char[]) fails.
See Also:
decode(char[], java.lang.String)

getRawAboveHierPath

public char[] getRawAboveHierPath()
                           throws URIException
Get the level above the this hierarchy level.

Returns:
the raw above hierarchy level
Throws:
URIException - If getRawCurrentHierPath(char[]) fails.

getEscapedAboveHierPath

public String getEscapedAboveHierPath()
                               throws URIException
Get the level above the this hierarchy level.

Returns:
the raw above hierarchy level
Throws:
URIException - If getRawCurrentHierPath(char[]) fails.

getAboveHierPath

public String getAboveHierPath()
                        throws URIException
Get the level above the this hierarchy level.

Returns:
the above hierarchy level
Throws:
URIException - If getRawCurrentHierPath(char[]) fails.
See Also:
decode(char[], java.lang.String)

getRawPath

public char[] getRawPath()
Get the raw-escaped path.

   path          = [ abs_path | opaque_part ]
 

Returns:
the raw-escaped path

getEscapedPath

public String getEscapedPath()
Get the escaped path.

   path          = [ abs_path | opaque_part ]
   abs_path      = "/"  path_segments 
   opaque_part   = uric_no_slash *uric
 

Returns:
the escaped path string

getPath

public String getPath()
               throws URIException
Get the path.

   path          = [ abs_path | opaque_part ]
 

Returns:
the path string
Throws:
URIException - If decode(char[], java.lang.String) fails.
See Also:
decode(char[], java.lang.String)

getRawName

public char[] getRawName()
Get the raw-escaped basename of the path.

Returns:
the raw-escaped basename

getEscapedName

public String getEscapedName()
Get the escaped basename of the path.

Returns:
the escaped basename string

getName

public String getName()
               throws URIException
Get the basename of the path.

Returns:
the basename string
Throws:
URIException - incomplete trailing escape pattern or unsupported character encoding
See Also:
decode(char[], java.lang.String)

getRawPathQuery

public char[] getRawPathQuery()
Get the raw-escaped path and query.

Returns:
the raw-escaped path and query

getEscapedPathQuery

public String getEscapedPathQuery()
Get the escaped query.

Returns:
the escaped path and query string

getPathQuery

public String getPathQuery()
                    throws URIException
Get the path and query.

Returns:
the path and query string.
Throws:
URIException - incomplete trailing escape pattern or unsupported character encoding
See Also:
decode(char[], java.lang.String)

setRawQuery

public void setRawQuery(char[] escapedQuery)
                 throws URIException
Set the raw-escaped query.

Parameters:
escapedQuery - the raw-escaped query
Throws:
URIException - escaped query not valid

setEscapedQuery

public void setEscapedQuery(String escapedQuery)
                     throws URIException
Set the escaped query string.

Parameters:
escapedQuery - the escaped query string
Throws:
URIException - escaped query not valid

setQuery

public void setQuery(String query)
              throws URIException
Set the query.

When a query string is not misunderstood the reserved special characters ("&", "=", "+", ",", and "$") within a query component, it is recommended to use in encoding the whole query with this method.

The additional APIs for the special purpose using by the reserved special characters used in each protocol are implemented in each protocol classes inherited from URI. So refer to the same-named APIs implemented in each specific protocol instance.

Parameters:
query - the query string.
Throws:
URIException - incomplete trailing escape pattern or unsupported character encoding
See Also:
encode(java.lang.String, java.util.BitSet, java.lang.String)

getRawQuery

public char[] getRawQuery()
Get the raw-escaped query.

Returns:
the raw-escaped query

getEscapedQuery

public String getEscapedQuery()
Get the escaped query.

Returns:
the escaped query string

getQuery

public String getQuery()
                throws URIException
Get the query.

Returns:
the query string.
Throws:
URIException - incomplete trailing escape pattern or unsupported character encoding
See Also:
decode(char[], java.lang.String)

setRawFragment

public void setRawFragment(char[] escapedFragment)
                    throws URIException
Set the raw-escaped fragment.

Parameters:
escapedFragment - the raw-escaped fragment
Throws:
URIException - escaped fragment not valid

setEscapedFragment

public void setEscapedFragment(String escapedFragment)
                        throws URIException
Set the escaped fragment string.

Parameters:
escapedFragment - the escaped fragment string
Throws:
URIException - escaped fragment not valid

setFragment

public void setFragment(String fragment)
                 throws URIException
Set the fragment.

Parameters:
fragment - the fragment string.
Throws:
URIException - If an error occurs.

getRawFragment

public char[] getRawFragment()
Get the raw-escaped fragment.

The optional fragment identifier is not part of a URI, but is often used in conjunction with a URI.

The format and interpretation of fragment identifiers is dependent on the media type [RFC2046] of the retrieval result.

A fragment identifier is only meaningful when a URI reference is intended for retrieval and the result of that retrieval is a document for which the identified fragment is consistently defined.

Returns:
the raw-escaped fragment

getEscapedFragment

public String getEscapedFragment()
Get the escaped fragment.

Returns:
the escaped fragment string

getFragment

public String getFragment()
                   throws URIException
Get the fragment.

Returns:
the fragment string
Throws:
URIException - incomplete trailing escape pattern or unsupported character encoding
See Also:
decode(char[], java.lang.String)

removeFragmentIdentifier

protected char[] removeFragmentIdentifier(char[] component)
Remove the fragment identifier of the given component.

Parameters:
component - the component that a fragment may be included
Returns:
the component that the fragment identifier is removed

normalize

protected char[] normalize(char[] path)
                    throws URIException
Normalize the given hier path part.

Algorithm taken from URI reference parser at http://www.apache.org/~fielding/uri/rev-2002/issues.html.

Parameters:
path - the path to normalize
Returns:
the normalized path
Throws:
URIException - no more higher path level to be normalized

normalize

public void normalize()
               throws URIException
Normalizes the path part of this URI. Normalization is only meant to be performed on URIs with an absolute path. Calling this method on a relative path URI will have no effect.

Throws:
URIException - no more higher path level to be normalized
See Also:
isAbsPath()

equals

protected boolean equals(char[] first,
                         char[] second)
Test if the first array is equal to the second array.

Parameters:
first - the first character array
second - the second character array
Returns:
true if they're equal

equals

public boolean equals(Object obj)
Test an object if this URI is equal to another.

Overrides:
equals in class Object
Parameters:
obj - an object to compare
Returns:
true if two URI objects are equal

hashCode

public int hashCode()
Return a hash code for this URI.

Overrides:
hashCode in class Object
Returns:
a has code value for this URI

compareTo

public int compareTo(Object obj)
              throws ClassCastException
Compare this URI to another object.

Specified by:
compareTo in interface Comparable
Parameters:
obj - the object to be compared.
Returns:
0, if it's same, -1, if failed, first being compared with in the authority component
Throws:
ClassCastException - not URI argument

clone

public Object clone()
             throws CloneNotSupportedException
Create and return a copy of this object, the URI-reference containing the userinfo component. Notice that the whole URI-reference including the userinfo component counld not be gotten as a String.

To copy the identical URI object including the userinfo component, it should be used.

Overrides:
clone in class Object
Returns:
a clone of this instance
Throws:
CloneNotSupportedException

getRawURI

public char[] getRawURI()
It can be gotten the URI character sequence. It's raw-escaped. For the purpose of the protocol to be transported, it will be useful.

It is clearly unwise to use a URL that contains a password which is intended to be secret. In particular, the use of a password within the 'userinfo' component of a URL is strongly disrecommended except in those rare cases where the 'password' parameter is intended to be public.

When you want to get each part of the userinfo, you need to use the specific methods in the specific URL. It depends on the specific URL.

Returns:
the URI character sequence

getEscapedURI

public String getEscapedURI()
It can be gotten the URI character sequence. It's escaped. For the purpose of the protocol to be transported, it will be useful.

Returns:
the escaped URI string

getURI

public String getURI()
              throws URIException
It can be gotten the URI character sequence.

Returns:
the original URI string
Throws:
URIException - incomplete trailing escape pattern or unsupported character encoding
See Also:
decode(char[], java.lang.String)

getRawURIReference

public char[] getRawURIReference()
Get the URI reference character sequence.

Returns:
the URI reference character sequence

getEscapedURIReference

public String getEscapedURIReference()
Get the escaped URI reference string.

Returns:
the escaped URI reference string

getURIReference

public String getURIReference()
                       throws URIException
Get the original URI reference string.

Returns:
the original URI reference string
Throws:
URIException - If decode(char[], java.lang.String) fails.

toString

public String toString()
Get the escaped URI string.

On the document, the URI-reference form is only used without the userinfo component like http://jakarta.apache.org/ by the security reason. But the URI-reference form with the userinfo component could be parsed.

In other words, this URI and any its subclasses must not expose the URI-reference expression with the userinfo component like http://user:password@hostport/restricted_zone.
It means that the API client programmer should extract each user and password to access manually. Probably it will be supported in the each subclass, however, not a whole URI-reference expression.

Overrides:
toString in class Object
Returns:
the escaped URI string
See Also:
clone()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/URIException.html100644 0 0 67021 10661532627 26010 0ustar 0 0 URIException (HttpClient 3.1 API)

org.apache.commons.httpclient
Class URIException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.URIException
All Implemented Interfaces:
Serializable

public class URIException
extends HttpException

The URI parsing and escape encoding exception.

Version:
$Revision: 480424 $ $Date: 2002/03/14 15:14:01
Author:
Sung-Gu, Oleg Kalnichevski
See Also:
Serialized Form

Field Summary
static int ESCAPING
          The URI escape encoding and decoding error.
static int PARSING
          The URI parsing error.
static int PUNYCODE
          The DNS punycode encoding or decoding error.
protected  String reason
          The reason message.
protected  int reasonCode
          The reason code.
static int UNKNOWN
          No specified reason code.
static int UNSUPPORTED_ENCODING
          The unsupported character encoding.
 
Constructor Summary
URIException()
          Default constructor.
URIException(int reasonCode)
          The constructor with a reason code argument.
URIException(int reasonCode, String reason)
          The constructor with a reason string and its code arguments.
URIException(String reason)
          The constructor with a reason string argument.
 
Method Summary
 String getReason()
          Deprecated. You should instead call Throwable.getMessage().
 int getReasonCode()
          Get the reason code.
 void setReason(String reason)
          Deprecated. Callers should instead set this via a parameter to the constructor.
 void setReasonCode(int reasonCode)
          Deprecated. Callers should set the reason code as a parameter to the constructor.
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, printStackTrace, printStackTrace, printStackTrace
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

UNKNOWN

public static final int UNKNOWN
No specified reason code.

See Also:
Constant Field Values

PARSING

public static final int PARSING
The URI parsing error.

See Also:
Constant Field Values

UNSUPPORTED_ENCODING

public static final int UNSUPPORTED_ENCODING
The unsupported character encoding.

See Also:
Constant Field Values

ESCAPING

public static final int ESCAPING
The URI escape encoding and decoding error.

See Also:
Constant Field Values

PUNYCODE

public static final int PUNYCODE
The DNS punycode encoding or decoding error.

See Also:
Constant Field Values

reasonCode

protected int reasonCode
The reason code.


reason

protected String reason
The reason message.

Constructor Detail

URIException

public URIException()
Default constructor.


URIException

public URIException(int reasonCode)
The constructor with a reason code argument.

Parameters:
reasonCode - the reason code

URIException

public URIException(int reasonCode,
                    String reason)
The constructor with a reason string and its code arguments.

Parameters:
reasonCode - the reason code
reason - the reason

URIException

public URIException(String reason)
The constructor with a reason string argument.

Parameters:
reason - the reason
Method Detail

getReasonCode

public int getReasonCode()
Get the reason code.

Overrides:
getReasonCode in class HttpException
Returns:
the reason code

setReasonCode

public void setReasonCode(int reasonCode)
Deprecated. Callers should set the reason code as a parameter to the constructor.

Set the reason code.

Overrides:
setReasonCode in class HttpException
Parameters:
reasonCode - the reason code

getReason

public String getReason()
Deprecated. You should instead call Throwable.getMessage().

Get the reason message.

Overrides:
getReason in class HttpException
Returns:
the reason message

setReason

public void setReason(String reason)
Deprecated. Callers should instead set this via a parameter to the constructor.

Set the reason message.

Overrides:
setReason in class HttpException
Parameters:
reason - the reason message


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/UsernamePasswordCredentials.html100644 0 0 54463 10661532627 31160 0ustar 0 0 UsernamePasswordCredentials (HttpClient 3.1 API)

org.apache.commons.httpclient
Class UsernamePasswordCredentials

java.lang.Object
  extended by org.apache.commons.httpclient.UsernamePasswordCredentials
All Implemented Interfaces:
Credentials
Direct Known Subclasses:
NTCredentials

public class UsernamePasswordCredentials
extends Object
implements Credentials

Username and password Credentials.

Version:
$Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
Author:
Remy Maucherat, Sean C. Sullivan, Mike Bowler, Oleg Kalnichevski

Constructor Summary
UsernamePasswordCredentials()
          Deprecated. Do not use. Null user name no longer allowed
UsernamePasswordCredentials(String usernamePassword)
          The constructor with the username and password combined string argument.
UsernamePasswordCredentials(String userName, String password)
          The constructor with the username and password arguments.
 
Method Summary
 boolean equals(Object o)
          These credentials are assumed equal if the username and password are the same.
 String getPassword()
          Password property getter.
 String getUserName()
          User name property getter.
 int hashCode()
          Does a hash of both user name and password.
 void setPassword(String password)
          Deprecated. Do not use. The UsernamePasswordCredentials objects should be immutable
 void setUserName(String userName)
          Deprecated. Do not use. The UsernamePasswordCredentials objects should be immutable
 String toString()
          Get this object string.
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

UsernamePasswordCredentials

public UsernamePasswordCredentials()
Deprecated. Do not use. Null user name no longer allowed

Default constructor.


UsernamePasswordCredentials

public UsernamePasswordCredentials(String usernamePassword)
The constructor with the username and password combined string argument.

Parameters:
usernamePassword - the username:password formed string
See Also:
toString()

UsernamePasswordCredentials

public UsernamePasswordCredentials(String userName,
                                   String password)
The constructor with the username and password arguments.

Parameters:
userName - the user name
password - the password
Method Detail

setUserName

public void setUserName(String userName)
Deprecated. Do not use. The UsernamePasswordCredentials objects should be immutable

User name property setter. User name may not be null.

Parameters:
userName -
See Also:
getUserName()

getUserName

public String getUserName()
User name property getter.

Returns:
the userName
See Also:
setUserName(String)

setPassword

public void setPassword(String password)
Deprecated. Do not use. The UsernamePasswordCredentials objects should be immutable

Password property setter.

Parameters:
password -
See Also:
getPassword()

getPassword

public String getPassword()
Password property getter.

Returns:
the password
See Also:
setPassword(String)

toString

public String toString()
Get this object string.

Overrides:
toString in class Object
Returns:
the username:password formed string

hashCode

public int hashCode()
Does a hash of both user name and password.

Overrides:
hashCode in class Object
Returns:
The hash code including user name and password.

equals

public boolean equals(Object o)
These credentials are assumed equal if the username and password are the same.

Overrides:
equals in class Object
Parameters:
o - The other object to compare with.
Returns:
true if the object is equivalent.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/AuthChallengeException.html100644 0 0 44266 10661532627 31024 0ustar 0 0 AuthChallengeException (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class AuthChallengeException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.ProtocolException
                      extended by org.apache.commons.httpclient.auth.AuthenticationException
                          extended by org.apache.commons.httpclient.auth.AuthChallengeException
All Implemented Interfaces:
Serializable

public class AuthChallengeException
extends AuthenticationException

Signals a failure processing authentication challenge

Since:
3.0
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
AuthChallengeException()
          Creates a new AuthChallengeException with a null detail message.
AuthChallengeException(String message)
          Creates a new AuthChallengeException with the specified message.
AuthChallengeException(String message, Throwable cause)
          Creates a new AuthChallengeException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

AuthChallengeException

public AuthChallengeException()
Creates a new AuthChallengeException with a null detail message.


AuthChallengeException

public AuthChallengeException(String message)
Creates a new AuthChallengeException with the specified message.

Parameters:
message - the exception detail message

AuthChallengeException

public AuthChallengeException(String message,
                              Throwable cause)
Creates a new AuthChallengeException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/AuthChallengeParser.html100644 0 0 42112 10661532627 30306 0ustar 0 0 AuthChallengeParser (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class AuthChallengeParser

java.lang.Object
  extended by org.apache.commons.httpclient.auth.AuthChallengeParser

public final class AuthChallengeParser
extends Object

This class provides utility methods for parsing HTTP www and proxy authentication challenges.

Since:
2.0beta1
Author:
Oleg Kalnichevski

Constructor Summary
AuthChallengeParser()
           
 
Method Summary
static Map extractParams(String challengeStr)
          Extracts a map of challenge parameters from an authentication challenge.
static String extractScheme(String challengeStr)
          Extracts authentication scheme from the given authentication challenge.
static Map parseChallenges(Header[] headers)
          Extracts a map of challenges ordered by authentication scheme name
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

AuthChallengeParser

public AuthChallengeParser()
Method Detail

extractScheme

public static String extractScheme(String challengeStr)
                            throws MalformedChallengeException
Extracts authentication scheme from the given authentication challenge.

Parameters:
challengeStr - the authentication challenge string
Returns:
authentication scheme
Throws:
MalformedChallengeException - when the authentication challenge string is malformed
Since:
2.0beta1

extractParams

public static Map extractParams(String challengeStr)
                         throws MalformedChallengeException
Extracts a map of challenge parameters from an authentication challenge. Keys in the map are lower-cased

Parameters:
challengeStr - the authentication challenge string
Returns:
a map of authentication challenge parameters
Throws:
MalformedChallengeException - when the authentication challenge string is malformed
Since:
2.0beta1

parseChallenges

public static Map parseChallenges(Header[] headers)
                           throws MalformedChallengeException
Extracts a map of challenges ordered by authentication scheme name

Parameters:
headers - the array of authorization challenges
Returns:
a map of authorization challenges
Throws:
MalformedChallengeException - if any of challenge strings is malformed
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/AuthChallengeProcessor.html100644 0 0 44706 10661532627 31044 0ustar 0 0 AuthChallengeProcessor (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class AuthChallengeProcessor

java.lang.Object
  extended by org.apache.commons.httpclient.auth.AuthChallengeProcessor

public final class AuthChallengeProcessor
extends Object

This class provides utility methods for processing HTTP www and proxy authentication challenges.

Since:
3.0
Author:
Oleg Kalnichevski

Constructor Summary
AuthChallengeProcessor(HttpParams params)
          Creates an authentication challenge processor with the given HTTP parameters
 
Method Summary
 AuthScheme processChallenge(AuthState state, Map challenges)
          Processes the given collection of challenges and updates the state of the authentication process.
 AuthScheme selectAuthScheme(Map challenges)
          Determines the preferred authentication scheme that can be used to respond to the given collection of challenges.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

AuthChallengeProcessor

public AuthChallengeProcessor(HttpParams params)
Creates an authentication challenge processor with the given HTTP parameters

Parameters:
params - the HTTP parameters used by this processor
Method Detail

selectAuthScheme

public AuthScheme selectAuthScheme(Map challenges)
                            throws AuthChallengeException
Determines the preferred authentication scheme that can be used to respond to the given collection of challenges.

Parameters:
challenges - the collection of authentication challenges
Returns:
the preferred authentication scheme
Throws:
AuthChallengeException - if the preferred authentication scheme cannot be determined or is not supported

processChallenge

public AuthScheme processChallenge(AuthState state,
                                   Map challenges)
                            throws MalformedChallengeException,
                                   AuthenticationException
Processes the given collection of challenges and updates the state of the authentication process.

Parameters:
challenges - the collection of authentication challenges
Returns:
the authentication scheme used to process the challenge
Throws:
AuthChallengeException - if authentication challenges cannot be successfully processed or the preferred authentication scheme cannot be determined
MalformedChallengeException
AuthenticationException


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/AuthPolicy.html100644 0 0 65654 10661532627 26526 0ustar 0 0 AuthPolicy (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class AuthPolicy

java.lang.Object
  extended by org.apache.commons.httpclient.auth.AuthPolicy

public abstract class AuthPolicy
extends Object

Authentication policy class. The Authentication policy provides corresponding authentication scheme interfrace for a given type of authorization challenge.

The following specifications are provided:

  • Basic: Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported)
  • Digest: Digest authentication scheme as defined in RFC2617
  • NTLM: The NTLM scheme is a proprietary Microsoft Windows Authentication protocol (considered to be the most secure among currently supported authentication schemes)

Since:
3.0
Version:
$Revision: 480424 $
Author:
Oleg Kalnichevski

Field Summary
static String AUTH_SCHEME_PRIORITY
          The key used to look up the list of IDs of supported authentication schemes in their order of preference.
static String BASIC
          Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported)
static String DIGEST
          Digest authentication scheme as defined in RFC2617.
protected static Log LOG
          Log object.
static String NTLM
          The NTLM scheme is a proprietary Microsoft Windows Authentication protocol (considered to be the most secure among currently supported authentication schemes).
 
Constructor Summary
AuthPolicy()
           
 
Method Summary
static AuthScheme getAuthScheme(String id)
          Gets the authentication scheme with the given ID.
static List getDefaultAuthPrefs()
          Returns a list containing all registered authentication schemes in their default order.
static void registerAuthScheme(String id, Class clazz)
          Registers a class implementing an authentication scheme with the given identifier.
static void unregisterAuthScheme(String id)
          Unregisters the class implementing an authentication scheme with the given ID.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

AUTH_SCHEME_PRIORITY

public static final String AUTH_SCHEME_PRIORITY
The key used to look up the list of IDs of supported authentication schemes in their order of preference. The scheme IDs are stored in a Collection as Strings.

If several schemes are returned in the WWW-Authenticate or Proxy-Authenticate header, this parameter defines which authentication schemes takes precedence over others. The first item in the collection represents the most preferred authentication scheme, the last item represents the ID of the least preferred one.

See Also:
DefaultHttpParams, Constant Field Values

NTLM

public static final String NTLM
The NTLM scheme is a proprietary Microsoft Windows Authentication protocol (considered to be the most secure among currently supported authentication schemes).

See Also:
Constant Field Values

DIGEST

public static final String DIGEST
Digest authentication scheme as defined in RFC2617.

See Also:
Constant Field Values

BASIC

public static final String BASIC
Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported)

See Also:
Constant Field Values

LOG

protected static final Log LOG
Log object.

Constructor Detail

AuthPolicy

public AuthPolicy()
Method Detail

registerAuthScheme

public static void registerAuthScheme(String id,
                                      Class clazz)
Registers a class implementing an authentication scheme with the given identifier. If a class with the given ID already exists it will be overridden. This ID is the same one used to retrieve the authentication scheme from getAuthScheme(String).

Please note that custom authentication preferences, if used, need to be updated accordingly for the new authentication scheme to take effect.

Parameters:
id - the identifier for this scheme
clazz - the class to register
See Also:
getAuthScheme(String), AUTH_SCHEME_PRIORITY

unregisterAuthScheme

public static void unregisterAuthScheme(String id)
Unregisters the class implementing an authentication scheme with the given ID.

Parameters:
id - the ID of the class to unregister

getAuthScheme

public static AuthScheme getAuthScheme(String id)
                                throws IllegalStateException
Gets the authentication scheme with the given ID.

Parameters:
id - the authentication scheme ID
Returns:
authentication scheme
Throws:
IllegalStateException - if a scheme with the ID cannot be found

getDefaultAuthPrefs

public static List getDefaultAuthPrefs()
Returns a list containing all registered authentication schemes in their default order.

Returns:
authentication scheme


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/AuthScheme.html100644 0 0 60533 10661532627 26462 0ustar 0 0 AuthScheme (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Interface AuthScheme

All Known Implementing Classes:
AuthSchemeBase, BasicScheme, DigestScheme, NTLMScheme, RFC2617Scheme

public interface AuthScheme

This interface represents an abstract challenge-response oriented authentication scheme.

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

  • Parse and process the challenge sent by the targer server in response to request for a protected resource
  • Provide its textual designation
  • Provide its parameters, if available
  • Provide the realm this authentication scheme is applicable to, if available
  • Generate authorization string for the given set of credentials, request method and URI as specificed in the HTTP request line in response to the actual authorization challenge

Authentication schemes may ignore method name and URI parameters if they are not relevant for the given authentication mechanism

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

Since:
2.0beta1
Author:
Oleg Kalnichevski, Adrian Sutton

Method Summary
 String authenticate(Credentials credentials, HttpMethod method)
          Produces an authorization string for the given set of Credentials.
 String authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use authenticate(Credentials, HttpMethod) Produces an authorization string for the given set of Credentials, method name and URI using the given authentication scheme in response to the actual authorization challenge.
 String getID()
          Deprecated. no longer used
 String getParameter(String name)
          Returns authentication parameter with the given name, if available.
 String getRealm()
          Returns authentication realm.
 String getSchemeName()
          Returns textual designation of the given authentication scheme.
 boolean isComplete()
          Authentication process may involve a series of challenge-response exchanges.
 boolean isConnectionBased()
          Tests if the authentication scheme is provides authorization on a per connection basis instead of usual per request basis
 void processChallenge(String challenge)
          Processes the given challenge token.
 

Method Detail

processChallenge

void processChallenge(String challenge)
                      throws MalformedChallengeException
Processes the given challenge token. Some authentication schemes may involve multiple challenge-response exchanges. Such schemes must be able to maintain the state information when dealing with sequential challenges

Parameters:
challenge - the challenge string
Throws:
MalformedChallengeException
Since:
3.0

getSchemeName

String getSchemeName()
Returns textual designation of the given authentication scheme.

Returns:
the name of the given authentication scheme

getParameter

String getParameter(String name)
Returns authentication parameter with the given name, if available.

Parameters:
name - The name of the parameter to be returned
Returns:
the parameter with the given name

getRealm

String getRealm()
Returns authentication realm. If the concept of an authentication realm is not applicable to the given authentication scheme, returns null.

Returns:
the authentication realm

getID

String getID()
Deprecated. no longer used

Returns a String identifying the authentication challenge. This is used, in combination with the host and port to determine if authorization has already been attempted or not. Schemes which require multiple requests to complete the authentication should return a different value for each stage in the request.

Additionally, the ID should take into account any changes to the authentication challenge and return a different value when appropriate. For example when the realm changes in basic authentication it should be considered a different authentication attempt and a different value should be returned.

Returns:
String a String identifying the authentication challenge. The returned value may be null.

isConnectionBased

boolean isConnectionBased()
Tests if the authentication scheme is provides authorization on a per connection basis instead of usual per request basis

Returns:
true if the scheme is connection based, false if the scheme is request based.
Since:
3.0

isComplete

boolean isComplete()
Authentication process may involve a series of challenge-response exchanges. This method tests if the authorization process has been completed, either successfully or unsuccessfully, that is, all the required authorization challenges have been processed in their entirety.

Returns:
true if the authentication process has been completed, false otherwise.
Since:
3.0

authenticate

String authenticate(Credentials credentials,
                    String method,
                    String uri)
                    throws AuthenticationException
Deprecated. Use authenticate(Credentials, HttpMethod) Produces an authorization string for the given set of Credentials, method name and URI using the given authentication scheme in response to the actual authorization challenge.

Parameters:
credentials - The set of credentials to be used for athentication
method - The name of the method that requires authorization. This parameter may be ignored, if it is irrelevant or not applicable to the given authentication scheme
uri - The URI for which authorization is needed. This parameter may be ignored, if it is irrelevant or not applicable to the given authentication scheme
Returns:
the authorization string
Throws:
AuthenticationException - if authorization string cannot be generated due to an authentication failure
See Also:
HttpMethod.getName(), HttpMethod.getPath()

authenticate

String authenticate(Credentials credentials,
                    HttpMethod method)
                    throws AuthenticationException
Produces an authorization string for the given set of Credentials.

Parameters:
credentials - The set of credentials to be used for athentication
method - The method being authenticated
Returns:
the authorization string
Throws:
AuthenticationException - if authorization string cannot be generated due to an authentication failure
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/AuthSchemeBase.html100644 0 0 44324 10661532627 27255 0ustar 0 0 AuthSchemeBase (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class AuthSchemeBase

java.lang.Object
  extended by org.apache.commons.httpclient.auth.AuthSchemeBase
All Implemented Interfaces:
AuthScheme

Deprecated. No longer used

public abstract class AuthSchemeBase
extends Object
implements AuthScheme

Abstract authentication scheme class that implements AuthScheme interface and provides a default contstructor.

Author:
Oleg Kalnichevski

Constructor Summary
AuthSchemeBase(String challenge)
          Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
 
Method Summary
 boolean equals(Object obj)
          Deprecated.  
 int hashCode()
          Deprecated.  
 String toString()
          Deprecated.  
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface org.apache.commons.httpclient.auth.AuthScheme
authenticate, authenticate, getID, getParameter, getRealm, getSchemeName, isComplete, isConnectionBased, processChallenge
 

Constructor Detail

AuthSchemeBase

public AuthSchemeBase(String challenge)
               throws MalformedChallengeException
Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method

Constructor for an abstract authetication schemes.

Parameters:
challenge - authentication challenge
Throws:
MalformedChallengeException - is thrown if the authentication challenge is malformed
Method Detail

equals

public boolean equals(Object obj)
Deprecated. 
Overrides:
equals in class Object
See Also:
Object.equals(Object)

hashCode

public int hashCode()
Deprecated. 
Overrides:
hashCode in class Object
See Also:
Object.hashCode()

toString

public String toString()
Deprecated. 
Overrides:
toString in class Object
See Also:
Object.toString()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/AuthScope.html100644 0 0 72651 10661532627 26333 0ustar 0 0 AuthScope (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class AuthScope

java.lang.Object
  extended by org.apache.commons.httpclient.auth.AuthScope
Direct Known Subclasses:
HttpAuthRealm

public class AuthScope
extends Object

The class represents an authentication scope consisting of a host name, a port number, a realm name and an authentication scheme name which Credentials apply to.

Since:
3.0
Author:
Oleg Kalnichevski, Adrian Sutton

Field Summary
static AuthScope ANY
          Default scope matching any host, port, realm and authentication scheme.
static String ANY_HOST
          The null value represents any host.
static int ANY_PORT
          The -1 value represents any port.
static String ANY_REALM
          The null value represents any realm.
static String ANY_SCHEME
          The null value represents any authentication scheme.
 
Constructor Summary
AuthScope(AuthScope authscope)
          Creates a copy of the given credentials scope.
AuthScope(String host, int port)
          Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.
AuthScope(String host, int port, String realm)
          Creates a new credentials scope for the given host, port, realm, and any authentication scheme.
AuthScope(String host, int port, String realm, String scheme)
          Creates a new credentials scope for the given host, port, realm, and authentication scheme.
 
Method Summary
 boolean equals(Object o)
           
 String getHost()
           
 int getPort()
           
 String getRealm()
           
 String getScheme()
           
 int hashCode()
           
 int match(AuthScope that)
          Tests if the authentication scopes match.
 String toString()
           
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

ANY_HOST

public static final String ANY_HOST
The null value represents any host. In the future versions of HttpClient the use of this parameter will be discontinued.


ANY_PORT

public static final int ANY_PORT
The -1 value represents any port.

See Also:
Constant Field Values

ANY_REALM

public static final String ANY_REALM
The null value represents any realm.


ANY_SCHEME

public static final String ANY_SCHEME
The null value represents any authentication scheme.


ANY

public static final AuthScope ANY
Default scope matching any host, port, realm and authentication scheme. In the future versions of HttpClient the use of this parameter will be discontinued.

Constructor Detail

AuthScope

public AuthScope(String host,
                 int port,
                 String realm,
                 String scheme)
Creates a new credentials scope for the given host, port, realm, and authentication scheme.

Parameters:
host - the host the credentials apply to. May be set to null if credenticals are applicable to any host.
port - the port the credentials apply to. May be set to negative value if credenticals are applicable to any port.
realm - the realm the credentials apply to. May be set to null if credenticals are applicable to any realm.
scheme - the authentication scheme the credentials apply to. May be set to null if credenticals are applicable to any authentication scheme.
Since:
3.0

AuthScope

public AuthScope(String host,
                 int port,
                 String realm)
Creates a new credentials scope for the given host, port, realm, and any authentication scheme.

Parameters:
host - the host the credentials apply to. May be set to null if credenticals are applicable to any host.
port - the port the credentials apply to. May be set to negative value if credenticals are applicable to any port.
realm - the realm the credentials apply to. May be set to null if credenticals are applicable to any realm.
Since:
3.0

AuthScope

public AuthScope(String host,
                 int port)
Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.

Parameters:
host - the host the credentials apply to. May be set to null if credenticals are applicable to any host.
port - the port the credentials apply to. May be set to negative value if credenticals are applicable to any port.
Since:
3.0

AuthScope

public AuthScope(AuthScope authscope)
Creates a copy of the given credentials scope.

Since:
3.0
Method Detail

getHost

public String getHost()
Returns:
the host
Since:
3.0

getPort

public int getPort()
Returns:
the port
Since:
3.0

getRealm

public String getRealm()
Returns:
the realm name
Since:
3.0

getScheme

public String getScheme()
Returns:
the scheme type
Since:
3.0

match

public int match(AuthScope that)
Tests if the authentication scopes match.

Returns:
the match factor. Negative value signifies no match. Non-negative signifies a match. The greater the returned value the closer the match.
Since:
3.0

equals

public boolean equals(Object o)
Overrides:
equals in class Object
See Also:
Object.equals(Object)

toString

public String toString()
Overrides:
toString in class Object
See Also:
Object.toString()

hashCode

public int hashCode()
Overrides:
hashCode in class Object
See Also:
Object.hashCode()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/AuthState.html100644 0 0 55032 10661532627 26334 0ustar 0 0 AuthState (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class AuthState

java.lang.Object
  extended by org.apache.commons.httpclient.auth.AuthState

public class AuthState
extends Object

This class provides detailed information about the state of the authentication process.

Since:
3.0
Author:
Oleg Kalnichevski

Field Summary
static String PREEMPTIVE_AUTH_SCHEME
           
 
Constructor Summary
AuthState()
          Default constructor.
 
Method Summary
 AuthScheme getAuthScheme()
          Returns the authentication scheme.
 String getRealm()
          Returns the authentication realm.
 void invalidate()
          Invalidates the authentication state by resetting its parameters.
 boolean isAuthAttempted()
          Tests whether authenication challenge has been responsed to
 boolean isAuthRequested()
          Tests whether authenication challenge has been received
 boolean isPreemptive()
          Tests if preemptive authentication is used.
 void setAuthAttempted(boolean challengeResponded)
          Sets authentication attempt status
 void setAuthRequested(boolean challengeReceived)
          Sets authentication request status
 void setAuthScheme(AuthScheme authScheme)
          Assigns the given authentication scheme.
 void setPreemptive()
          Preemptively assigns Basic authentication scheme.
 String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

PREEMPTIVE_AUTH_SCHEME

public static final String PREEMPTIVE_AUTH_SCHEME
See Also:
Constant Field Values
Constructor Detail

AuthState

public AuthState()
Default constructor.

Method Detail

invalidate

public void invalidate()
Invalidates the authentication state by resetting its parameters.


isAuthRequested

public boolean isAuthRequested()
Tests whether authenication challenge has been received

Returns:
true if authenication challenge has been received, false otherwise

setAuthRequested

public void setAuthRequested(boolean challengeReceived)
Sets authentication request status

Parameters:
challengeReceived - true if authenication has been requested, false otherwise

isAuthAttempted

public boolean isAuthAttempted()
Tests whether authenication challenge has been responsed to

Returns:
true if authenication challenge has been responsed to, false otherwise

setAuthAttempted

public void setAuthAttempted(boolean challengeResponded)
Sets authentication attempt status

Parameters:
challengeResponded - true if authenication has been attempted, false otherwise

setPreemptive

public void setPreemptive()
Preemptively assigns Basic authentication scheme.


isPreemptive

public boolean isPreemptive()
Tests if preemptive authentication is used.

Returns:
true if using the default Basic authentication scheme, false otherwise.

setAuthScheme

public void setAuthScheme(AuthScheme authScheme)
Assigns the given authentication scheme.

Parameters:
authScheme - the authentication scheme

getAuthScheme

public AuthScheme getAuthScheme()
Returns the authentication scheme.

Returns:
authentication scheme

getRealm

public String getRealm()
Returns the authentication realm.

Returns:
the name of the authentication realm

toString

public String toString()
Overrides:
toString in class Object


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/AuthenticationException.html100644 0 0 45443 10661532627 31275 0ustar 0 0 AuthenticationException (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class AuthenticationException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.ProtocolException
                      extended by org.apache.commons.httpclient.auth.AuthenticationException
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
AuthChallengeException, CredentialsNotAvailableException, InvalidCredentialsException

public class AuthenticationException
extends ProtocolException

Signals a failure in authentication process

Since:
2.0
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
AuthenticationException()
          Creates a new AuthenticationException with a null detail message.
AuthenticationException(String message)
          Creates a new AuthenticationException with the specified message.
AuthenticationException(String message, Throwable cause)
          Creates a new AuthenticationException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

AuthenticationException

public AuthenticationException()
Creates a new AuthenticationException with a null detail message.


AuthenticationException

public AuthenticationException(String message)
Creates a new AuthenticationException with the specified message.

Parameters:
message - the exception detail message

AuthenticationException

public AuthenticationException(String message,
                               Throwable cause)
Creates a new AuthenticationException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/BasicScheme.html100644 0 0 75440 10661532627 26605 0ustar 0 0 BasicScheme (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class BasicScheme

java.lang.Object
  extended by org.apache.commons.httpclient.auth.RFC2617Scheme
      extended by org.apache.commons.httpclient.auth.BasicScheme
All Implemented Interfaces:
AuthScheme

public class BasicScheme
extends RFC2617Scheme

Basic authentication scheme as defined in RFC 2617.

Author:
Remy Maucherat, Rodney Waldhoff, Jeff Dever, Ortwin Gl?ck, Sean C. Sullivan, Adrian Sutton, Mike Bowler, Oleg Kalnichevski

Constructor Summary
BasicScheme()
          Default constructor for the basic authetication scheme.
BasicScheme(String challenge)
          Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
 
Method Summary
 String authenticate(Credentials credentials, HttpMethod method)
          Produces basic authorization string for the given set of Credentials.
 String authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use authenticate(Credentials, HttpMethod)
static String authenticate(UsernamePasswordCredentials credentials)
          Deprecated. Use authenticate(UsernamePasswordCredentials, String) Returns a basic Authorization header value for the given UsernamePasswordCredentials.
static String authenticate(UsernamePasswordCredentials credentials, String charset)
          Returns a basic Authorization header value for the given UsernamePasswordCredentials and charset.
 String getSchemeName()
          Returns textual designation of the basic authentication scheme.
 boolean isComplete()
          Tests if the Basic authentication process has been completed.
 boolean isConnectionBased()
          Returns false.
 void processChallenge(String challenge)
          Processes the Basic challenge.
 
Methods inherited from class org.apache.commons.httpclient.auth.RFC2617Scheme
getID, getParameter, getParameters, getRealm
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

BasicScheme

public BasicScheme()
Default constructor for the basic authetication scheme.

Since:
3.0

BasicScheme

public BasicScheme(String challenge)
            throws MalformedChallengeException
Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method

Constructor for the basic authetication scheme.

Parameters:
challenge - authentication challenge
Throws:
MalformedChallengeException - is thrown if the authentication challenge is malformed
Method Detail

getSchemeName

public String getSchemeName()
Returns textual designation of the basic authentication scheme.

Returns:
basic

processChallenge

public void processChallenge(String challenge)
                      throws MalformedChallengeException
Processes the Basic challenge.

Specified by:
processChallenge in interface AuthScheme
Overrides:
processChallenge in class RFC2617Scheme
Parameters:
challenge - the challenge string
Throws:
MalformedChallengeException - is thrown if the authentication challenge is malformed
Since:
3.0

isComplete

public boolean isComplete()
Tests if the Basic authentication process has been completed.

Returns:
true if Basic authorization has been processed, false otherwise.
Since:
3.0

authenticate

public String authenticate(Credentials credentials,
                           String method,
                           String uri)
                    throws AuthenticationException
Deprecated. Use authenticate(Credentials, HttpMethod)

Produces basic authorization string for the given set of Credentials.

Parameters:
credentials - The set of credentials to be used for athentication
method - Method name is ignored by the basic authentication scheme
uri - URI is ignored by the basic authentication scheme
Returns:
a basic authorization string
Throws:
InvalidCredentialsException - if authentication credentials are not valid or not applicable for this authentication scheme
AuthenticationException - if authorization string cannot be generated due to an authentication failure
See Also:
HttpMethod.getName(), HttpMethod.getPath()

isConnectionBased

public boolean isConnectionBased()
Returns false. Basic authentication scheme is request based.

Returns:
false.
Since:
3.0

authenticate

public String authenticate(Credentials credentials,
                           HttpMethod method)
                    throws AuthenticationException
Produces basic authorization string for the given set of Credentials.

Parameters:
credentials - The set of credentials to be used for athentication
method - The method being authenticated
Returns:
a basic authorization string
Throws:
InvalidCredentialsException - if authentication credentials are not valid or not applicable for this authentication scheme
AuthenticationException - if authorization string cannot be generated due to an authentication failure
Since:
3.0

authenticate

public static String authenticate(UsernamePasswordCredentials credentials)
Deprecated. Use authenticate(UsernamePasswordCredentials, String) Returns a basic Authorization header value for the given UsernamePasswordCredentials.

Parameters:
credentials - The credentials to encode.
Returns:
a basic authorization string

authenticate

public static String authenticate(UsernamePasswordCredentials credentials,
                                  String charset)
Returns a basic Authorization header value for the given UsernamePasswordCredentials and charset.

Parameters:
credentials - The credentials to encode.
charset - The charset to use for encoding the credentials
Returns:
a basic authorization string
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/CredentialsNotAvailableException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/CredentialsNotAvailableExcept100644 0 0 45607 10661532627 31366 0ustar 0 0 CredentialsNotAvailableException (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class CredentialsNotAvailableException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.ProtocolException
                      extended by org.apache.commons.httpclient.auth.AuthenticationException
                          extended by org.apache.commons.httpclient.auth.CredentialsNotAvailableException
All Implemented Interfaces:
Serializable

public class CredentialsNotAvailableException
extends AuthenticationException

Authentication credentials required to respond to a authentication challenge are not available

Since:
3.0
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
CredentialsNotAvailableException()
          Creates a new CredentialsNotAvailableException with a null detail message.
CredentialsNotAvailableException(String message)
          Creates a new CredentialsNotAvailableException with the specified message.
CredentialsNotAvailableException(String message, Throwable cause)
          Creates a new CredentialsNotAvailableException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

CredentialsNotAvailableException

public CredentialsNotAvailableException()
Creates a new CredentialsNotAvailableException with a null detail message.


CredentialsNotAvailableException

public CredentialsNotAvailableException(String message)
Creates a new CredentialsNotAvailableException with the specified message.

Parameters:
message - the exception detail message

CredentialsNotAvailableException

public CredentialsNotAvailableException(String message,
                                        Throwable cause)
Creates a new CredentialsNotAvailableException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/CredentialsProvider.html100644 0 0 33466 10661532627 30411 0ustar 0 0 CredentialsProvider (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Interface CredentialsProvider


public interface CredentialsProvider

Credentials provider interface can be used to provide HTTP method with a means to request authentication credentials if no credentials have been given or given credentials are incorrect.

HttpClient makes no provisions to check whether the same credentials have been tried already. It is a responsibility of the custom credentials provider to keep track of authentication attempts and to ensure that credentials known to be invalid are not retried. HttpClient will simply store the set of credentials returned by the custom credentials provider in the http state object and will attempt to use these credentials for all subsequent requests with the given authentication scope.

Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads

Since:
3.0
Author:
Ortwin Glueck, Oleg Kalnichevski

Field Summary
static String PROVIDER
          Sets the credentials provider parameter.
 
Method Summary
 Credentials getCredentials(AuthScheme scheme, String host, int port, boolean proxy)
          Requests additional authentication credentials.
 

Field Detail

PROVIDER

static final String PROVIDER
Sets the credentials provider parameter.

This parameter expects a value of type CredentialsProvider.

See Also:
Constant Field Values
Method Detail

getCredentials

Credentials getCredentials(AuthScheme scheme,
                           String host,
                           int port,
                           boolean proxy)
                           throws CredentialsNotAvailableException
Requests additional authentication credentials.

Parameters:
scheme - the authentication scheme
host - the authentication host
port - the port of the authentication host
proxy - true if authenticating with a proxy, false otherwise
Throws:
CredentialsNotAvailableException


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/DigestScheme.html100644 0 0 73360 10661532627 27002 0ustar 0 0 DigestScheme (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class DigestScheme

java.lang.Object
  extended by org.apache.commons.httpclient.auth.RFC2617Scheme
      extended by org.apache.commons.httpclient.auth.DigestScheme
All Implemented Interfaces:
AuthScheme

public class DigestScheme
extends RFC2617Scheme

Digest authentication scheme as defined in RFC 2617. Both MD5 (default) and MD5-sess are supported. Currently only qop=auth or no qop is supported. qop=auth-int is unsupported. If auth and auth-int are provided, auth is used.

Credential charset is configured via the credential charset parameter. Since the digest username is included as clear text in the generated Authentication header, the charset of the username must be compatible with the http element charset.

TODO: make class more stateful regarding repeated authentication requests

Author:
Remy Maucherat, Rodney Waldhoff, Jeff Dever, Ortwin Gl?ck, Sean C. Sullivan, Adrian Sutton, Mike Bowler, Oleg Kalnichevski

Constructor Summary
DigestScheme()
          Default constructor for the digest authetication scheme.
DigestScheme(String challenge)
          Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
 
Method Summary
 String authenticate(Credentials credentials, HttpMethod method)
          Produces a digest authorization string for the given set of Credentials, method name and URI.
 String authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use authenticate(Credentials, HttpMethod)
static String createCnonce()
          Creates a random cnonce value based on the current time.
 String getID()
          Deprecated. no longer used
 String getSchemeName()
          Returns textual designation of the digest authentication scheme.
 boolean isComplete()
          Tests if the Digest authentication process has been completed.
 boolean isConnectionBased()
          Returns false.
 void processChallenge(String challenge)
          Processes the Digest challenge.
 
Methods inherited from class org.apache.commons.httpclient.auth.RFC2617Scheme
getParameter, getParameters, getRealm
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

DigestScheme

public DigestScheme()
Default constructor for the digest authetication scheme.

Since:
3.0

DigestScheme

public DigestScheme(String challenge)
             throws MalformedChallengeException
Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method

Constructor for the digest authetication scheme.

Parameters:
challenge - authentication challenge
Throws:
MalformedChallengeException - is thrown if the authentication challenge is malformed
Method Detail

getID

public String getID()
Deprecated. no longer used

Gets an ID based upon the realm and the nonce value. This ensures that requests to the same realm with different nonce values will succeed. This differentiation allows servers to request re-authentication using a fresh nonce value.

Specified by:
getID in interface AuthScheme
Overrides:
getID in class RFC2617Scheme
Returns:
String a String identifying the authentication challenge. The returned value may be null.

processChallenge

public void processChallenge(String challenge)
                      throws MalformedChallengeException
Processes the Digest challenge.

Specified by:
processChallenge in interface AuthScheme
Overrides:
processChallenge in class RFC2617Scheme
Parameters:
challenge - the challenge string
Throws:
MalformedChallengeException - is thrown if the authentication challenge is malformed
Since:
3.0

isComplete

public boolean isComplete()
Tests if the Digest authentication process has been completed.

Returns:
true if Digest authorization has been processed, false otherwise.
Since:
3.0

getSchemeName

public String getSchemeName()
Returns textual designation of the digest authentication scheme.

Returns:
digest

isConnectionBased

public boolean isConnectionBased()
Returns false. Digest authentication scheme is request based.

Returns:
false.
Since:
3.0

authenticate

public String authenticate(Credentials credentials,
                           String method,
                           String uri)
                    throws AuthenticationException
Deprecated. Use authenticate(Credentials, HttpMethod)

Produces a digest authorization string for the given set of Credentials, method name and URI.

Parameters:
credentials - A set of credentials to be used for athentication
method - the name of the method that requires authorization.
uri - The URI for which authorization is needed.
Returns:
a digest authorization string
Throws:
InvalidCredentialsException - if authentication credentials are not valid or not applicable for this authentication scheme
AuthenticationException - if authorization string cannot be generated due to an authentication failure
See Also:
HttpMethod.getName(), HttpMethod.getPath()

authenticate

public String authenticate(Credentials credentials,
                           HttpMethod method)
                    throws AuthenticationException
Produces a digest authorization string for the given set of Credentials, method name and URI.

Parameters:
credentials - A set of credentials to be used for athentication
method - The method being authenticated
Returns:
a digest authorization string
Throws:
InvalidCredentialsException - if authentication credentials are not valid or not applicable for this authentication scheme
AuthenticationException - if authorization string cannot be generated due to an authentication failure
Since:
3.0

createCnonce

public static String createCnonce()
Creates a random cnonce value based on the current time.

Returns:
The cnonce value as String.
Throws:
HttpClientError - if MD5 algorithm is not supported.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/HttpAuthRealm.html100644 0 0 36011 10661532627 27150 0ustar 0 0 HttpAuthRealm (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class HttpAuthRealm

java.lang.Object
  extended by org.apache.commons.httpclient.auth.AuthScope
      extended by org.apache.commons.httpclient.auth.HttpAuthRealm

Deprecated. no longer used

public class HttpAuthRealm
extends AuthScope

The key used to look up authentication credentials.

Author:
Oleg Kalnichevski, Adrian Sutton

Field Summary
 
Fields inherited from class org.apache.commons.httpclient.auth.AuthScope
ANY, ANY_HOST, ANY_PORT, ANY_REALM, ANY_SCHEME
 
Constructor Summary
HttpAuthRealm(String domain, String realm)
          Deprecated. Creates a new HttpAuthRealm for the given domain and realm.
 
Method Summary
 
Methods inherited from class org.apache.commons.httpclient.auth.AuthScope
equals, getHost, getPort, getRealm, getScheme, hashCode, match, toString
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

HttpAuthRealm

public HttpAuthRealm(String domain,
                     String realm)
Deprecated. 
Creates a new HttpAuthRealm for the given domain and realm.

Parameters:
domain - the domain the credentials apply to. May be set to null if credenticals are applicable to any domain.
realm - the realm the credentials apply to. May be set to null if credenticals are applicable to any realm.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/HttpAuthenticator.html100644 0 0 106304 10661532627 30123 0ustar 0 0 HttpAuthenticator (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class HttpAuthenticator

java.lang.Object
  extended by org.apache.commons.httpclient.auth.HttpAuthenticator

Deprecated. no longer used

public final class HttpAuthenticator
extends Object

Utility methods for HTTP authorization and authentication. This class provides utility methods for generating responses to HTTP www and proxy authentication challenges.

A client SHOULD assume that all paths at or deeper than the depth of the last symbolic element in the path field of the Request-URI also are within the protection space specified by the basic realm value of the current challenge. A client MAY preemptively send the corresponding Authorization header with requests for resources in that space without receipt of another challenge from the server. Similarly, when a client sends a request to a proxy, it may reuse a userid and password in the Proxy-Authorization header field without receiving another challenge from the proxy server.

Author:
Remy Maucherat, Rodney Waldhoff, Jeff Dever, Ortwin Gl?ck, Sean C. Sullivan, Adrian Sutton, Mike Bowler, Oleg Kalnichevski

Field Summary
static String PROXY_AUTH
          Deprecated. The proxy authenticate challange header.
static String PROXY_AUTH_RESP
          Deprecated. The proxy authenticate response header.
static String WWW_AUTH
          Deprecated. The www authenticate challange header.
static String WWW_AUTH_RESP
          Deprecated. The www authenticate response header.
 
Constructor Summary
HttpAuthenticator()
          Deprecated.  
 
Method Summary
static boolean authenticate(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean authenticateDefault(HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean authenticateProxy(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean authenticateProxyDefault(HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static AuthScheme selectAuthScheme(Header[] challenges)
          Deprecated. Use AuthChallengeParser.parseChallenges(Header[]) and AuthPolicy.getAuthScheme(String)
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

WWW_AUTH

public static final String WWW_AUTH
Deprecated. 
The www authenticate challange header.

See Also:
Constant Field Values

WWW_AUTH_RESP

public static final String WWW_AUTH_RESP
Deprecated. 
The www authenticate response header.

See Also:
Constant Field Values

PROXY_AUTH

public static final String PROXY_AUTH
Deprecated. 
The proxy authenticate challange header.

See Also:
Constant Field Values

PROXY_AUTH_RESP

public static final String PROXY_AUTH_RESP
Deprecated. 
The proxy authenticate response header.

See Also:
Constant Field Values
Constructor Detail

HttpAuthenticator

public HttpAuthenticator()
Deprecated. 
Method Detail

selectAuthScheme

public static AuthScheme selectAuthScheme(Header[] challenges)
                                   throws MalformedChallengeException
Deprecated. Use AuthChallengeParser.parseChallenges(Header[]) and AuthPolicy.getAuthScheme(String)

Chooses the strongest authentication scheme supported from the array of authentication challenges. Currently only NTLM, Digest, Basic schemes are recognized. The NTLM scheme is considered the strongest and is preferred to all others. The Digest scheme is preferred to the Basic one which provides no encryption for credentials. The Basic scheme is used only if it is the only one supported.

Parameters:
challenges - The array of authentication challenges
Returns:
The strongest authentication scheme supported
Throws:
MalformedChallengeException - is thrown if an authentication challenge is malformed
UnsupportedOperationException - when none of challenge types available is supported.

authenticateDefault

public static boolean authenticateDefault(HttpMethod method,
                                          HttpConnection conn,
                                          HttpState state)
                                   throws AuthenticationException
Deprecated. use AuthScheme

Attempt to provide default authentication credentials to the given method in the given context using basic authentication scheme.

Parameters:
method - the HttpMethod which requires authentication
conn - the connection to a specific host. This parameter may be null if default credentials (not specific to any particular host) are to be used
state - the HttpState object providing Credentials
Returns:
true if the Authenticate response header was added
Throws:
InvalidCredentialsException - if authentication credentials are not valid or not applicable for basic scheme
AuthenticationException - when a parsing or other error occurs
See Also:
HttpState.setCredentials(String,String,Credentials)

authenticateProxyDefault

public static boolean authenticateProxyDefault(HttpMethod method,
                                               HttpConnection conn,
                                               HttpState state)
                                        throws AuthenticationException
Deprecated. use AuthScheme

Attempt to provide default proxy authentication credentials to the given method in the given context using basic authentication scheme.

Parameters:
method - the HttpMethod which requires authentication
conn - the connection to a specific host. This parameter may be null if default credentials (not specific to any particular host) are to be used
state - the HttpState object providing Credentials
Returns:
true if the Proxy-Authenticate response header was added
Throws:
InvalidCredentialsException - if authentication credentials are not valid or not applicable for basic scheme
AuthenticationException - when a parsing or other error occurs
See Also:
HttpState.setCredentials(String,String,Credentials)

authenticate

public static boolean authenticate(AuthScheme authscheme,
                                   HttpMethod method,
                                   HttpConnection conn,
                                   HttpState state)
                            throws AuthenticationException
Deprecated. use AuthScheme

Attempt to provide requisite authentication credentials to the given method in the given context using the given authentication scheme.

Parameters:
authscheme - The authentication scheme to be used
method - The HttpMethod which requires authentication
conn - the connection to a specific host. This parameter may be null if default credentials (not specific to any particular host) are to be used
state - The HttpState object providing Credentials
Returns:
true if the Authenticate response header was added
Throws:
CredentialsNotAvailableException - if authentication credentials required to respond to the authentication challenge are not available
AuthenticationException - when a parsing or other error occurs
See Also:
HttpState.setCredentials(String,String,Credentials)

authenticateProxy

public static boolean authenticateProxy(AuthScheme authscheme,
                                        HttpMethod method,
                                        HttpConnection conn,
                                        HttpState state)
                                 throws AuthenticationException
Deprecated. use AuthScheme

Attempt to provide requisite proxy authentication credentials to the given method in the given context using the given authentication scheme.

Parameters:
authscheme - The authentication scheme to be used
method - the HttpMethod which requires authentication
conn - the connection to a specific host. This parameter may be null if default credentials (not specific to any particular host) are to be used
state - the HttpState object providing Credentials
Returns:
true if the Proxy-Authenticate response header was added
Throws:
CredentialsNotAvailableException - if authentication credentials required to respond to the authentication challenge are not available
AuthenticationException - when a parsing or other error occurs
See Also:
HttpState.setCredentials(String,String,Credentials)


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/InvalidCredentialsException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/InvalidCredentialsException.h100644 0 0 45312 10661532627 31340 0ustar 0 0 InvalidCredentialsException (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class InvalidCredentialsException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.ProtocolException
                      extended by org.apache.commons.httpclient.auth.AuthenticationException
                          extended by org.apache.commons.httpclient.auth.InvalidCredentialsException
All Implemented Interfaces:
Serializable

public class InvalidCredentialsException
extends AuthenticationException

Authentication credentials required to respond to a authentication challenge are invalid

Since:
3.0
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
InvalidCredentialsException()
          Creates a new InvalidCredentialsException with a null detail message.
InvalidCredentialsException(String message)
          Creates a new InvalidCredentialsException with the specified message.
InvalidCredentialsException(String message, Throwable cause)
          Creates a new InvalidCredentialsException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

InvalidCredentialsException

public InvalidCredentialsException()
Creates a new InvalidCredentialsException with a null detail message.


InvalidCredentialsException

public InvalidCredentialsException(String message)
Creates a new InvalidCredentialsException with the specified message.

Parameters:
message - the exception detail message

InvalidCredentialsException

public InvalidCredentialsException(String message,
                                   Throwable cause)
Creates a new InvalidCredentialsException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/MalformedChallengeException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/MalformedChallengeException.h100644 0 0 44657 10661532627 31320 0ustar 0 0 MalformedChallengeException (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class MalformedChallengeException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.ProtocolException
                      extended by org.apache.commons.httpclient.auth.MalformedChallengeException
All Implemented Interfaces:
Serializable

public class MalformedChallengeException
extends ProtocolException

Signals that authentication challenge is in some way invalid or illegal in the given context

Since:
2.0
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
MalformedChallengeException()
          Creates a new MalformedChallengeException with a null detail message.
MalformedChallengeException(String message)
          Creates a new MalformedChallengeException with the specified message.
MalformedChallengeException(String message, Throwable cause)
          Creates a new MalformedChallengeException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

MalformedChallengeException

public MalformedChallengeException()
Creates a new MalformedChallengeException with a null detail message.


MalformedChallengeException

public MalformedChallengeException(String message)
Creates a new MalformedChallengeException with the specified message.

Parameters:
message - the exception detail message

MalformedChallengeException

public MalformedChallengeException(String message,
                                   Throwable cause)
Creates a new MalformedChallengeException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/NTLMScheme.html100644 0 0 112330 10661532627 26344 0ustar 0 0 NTLMScheme (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class NTLMScheme

java.lang.Object
  extended by org.apache.commons.httpclient.auth.NTLMScheme
All Implemented Interfaces:
AuthScheme

public class NTLMScheme
extends Object
implements AuthScheme

An implementation of the Microsoft proprietary NTLM authentication scheme. For a detailed explanation of the NTLM scheme please see http://davenport.sourceforge.net/ntlm.html.

Author:
Remy Maucherat, Rodney Waldhoff, Jeff Dever, Ortwin Gl???ck, Sean C. Sullivan, Adrian Sutton, Mike Bowler, Oleg Kalnichevski

Constructor Summary
NTLMScheme()
          Default constructor for the NTLM authentication scheme.
NTLMScheme(String challenge)
          Constructor for the NTLM authentication scheme.
 
Method Summary
 String authenticate(Credentials credentials, HttpMethod method)
          Produces NTLM authorization string for the given set of Credentials.
 String authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use authenticate(Credentials, HttpMethod)
static String authenticate(NTCredentials credentials, String challenge)
          Deprecated. Use non-static authenticate(Credentials, HttpMethod)
static String authenticate(NTCredentials credentials, String challenge, String charset)
          Deprecated. Use non-static authenticate(Credentials, HttpMethod)
 String getID()
          Deprecated. no longer used
 String getParameter(String name)
          Returns the authentication parameter with the given name, if available.
 String getRealm()
          The concept of an authentication realm is not supported by the NTLM authentication scheme.
 String getSchemeName()
          Returns textual designation of the NTLM authentication scheme.
 boolean isComplete()
          Tests if the NTLM authentication process has been completed.
 boolean isConnectionBased()
          Returns true.
 void processChallenge(String challenge)
          Processes the NTLM challenge.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

NTLMScheme

public NTLMScheme()
Default constructor for the NTLM authentication scheme.

Since:
3.0

NTLMScheme

public NTLMScheme(String challenge)
           throws MalformedChallengeException
Constructor for the NTLM authentication scheme.

Parameters:
challenge - The authentication challenge
Throws:
MalformedChallengeException - is thrown if the authentication challenge is malformed
Method Detail

processChallenge

public void processChallenge(String challenge)
                      throws MalformedChallengeException
Processes the NTLM challenge.

Specified by:
processChallenge in interface AuthScheme
Parameters:
challenge - the challenge string
Throws:
MalformedChallengeException - is thrown if the authentication challenge is malformed
Since:
3.0

isComplete

public boolean isComplete()
Tests if the NTLM authentication process has been completed.

Specified by:
isComplete in interface AuthScheme
Returns:
true if Basic authorization has been processed, false otherwise.
Since:
3.0

getSchemeName

public String getSchemeName()
Returns textual designation of the NTLM authentication scheme.

Specified by:
getSchemeName in interface AuthScheme
Returns:
ntlm

getRealm

public String getRealm()
The concept of an authentication realm is not supported by the NTLM authentication scheme. Always returns null.

Specified by:
getRealm in interface AuthScheme
Returns:
null

getID

public String getID()
Deprecated. no longer used

Returns a String identifying the authentication challenge. This is used, in combination with the host and port to determine if authorization has already been attempted or not. Schemes which require multiple requests to complete the authentication should return a different value for each stage in the request.

Additionally, the ID should take into account any changes to the authentication challenge and return a different value when appropriate. For example when the realm changes in basic authentication it should be considered a different authentication attempt and a different value should be returned.

Specified by:
getID in interface AuthScheme
Returns:
String a String identifying the authentication challenge. The returned value may be null.

getParameter

public String getParameter(String name)
Returns the authentication parameter with the given name, if available.

There are no valid parameters for NTLM authentication so this method always returns null.

Specified by:
getParameter in interface AuthScheme
Parameters:
name - The name of the parameter to be returned
Returns:
the parameter with the given name

isConnectionBased

public boolean isConnectionBased()
Returns true. NTLM authentication scheme is connection based.

Specified by:
isConnectionBased in interface AuthScheme
Returns:
true.
Since:
3.0

authenticate

public static String authenticate(NTCredentials credentials,
                                  String challenge)
                           throws AuthenticationException
Deprecated. Use non-static authenticate(Credentials, HttpMethod)

Create a NTLM authorization string for the given challenge and NT credentials.

Parameters:
challenge - The challenge.
credentials - NTCredentials
Returns:
a ntlm authorization string
Throws:
AuthenticationException - is thrown if authentication fails

authenticate

public static String authenticate(NTCredentials credentials,
                                  String challenge,
                                  String charset)
                           throws AuthenticationException
Deprecated. Use non-static authenticate(Credentials, HttpMethod)

Create a NTLM authorization string for the given challenge and NT credentials.

Parameters:
challenge - The challenge.
credentials - NTCredentials
charset - The charset to use for encoding the credentials
Returns:
a ntlm authorization string
Throws:
AuthenticationException - is thrown if authentication fails
Since:
3.0

authenticate

public String authenticate(Credentials credentials,
                           String method,
                           String uri)
                    throws AuthenticationException
Deprecated. Use authenticate(Credentials, HttpMethod)

Produces NTLM authorization string for the given set of Credentials.

Specified by:
authenticate in interface AuthScheme
Parameters:
credentials - The set of credentials to be used for athentication
method - Method name is ignored by the NTLM authentication scheme
uri - URI is ignored by the NTLM authentication scheme
Returns:
an NTLM authorization string
Throws:
InvalidCredentialsException - if authentication credentials are not valid or not applicable for this authentication scheme
AuthenticationException - if authorization string cannot be generated due to an authentication failure
See Also:
HttpMethod.getName(), HttpMethod.getPath()

authenticate

public String authenticate(Credentials credentials,
                           HttpMethod method)
                    throws AuthenticationException
Produces NTLM authorization string for the given set of Credentials.

Specified by:
authenticate in interface AuthScheme
Parameters:
credentials - The set of credentials to be used for athentication
method - The method being authenticated
Returns:
an NTLM authorization string
Throws:
InvalidCredentialsException - if authentication credentials are not valid or not applicable for this authentication scheme
AuthenticationException - if authorization string cannot be generated due to an authentication failure
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/RFC2617Scheme.html100644 0 0 55214 10661532627 26513 0ustar 0 0 RFC2617Scheme (HttpClient 3.1 API)

org.apache.commons.httpclient.auth
Class RFC2617Scheme

java.lang.Object
  extended by org.apache.commons.httpclient.auth.RFC2617Scheme
All Implemented Interfaces:
AuthScheme
Direct Known Subclasses:
BasicScheme, DigestScheme

public abstract class RFC2617Scheme
extends Object
implements AuthScheme

Abstract authentication scheme class that lays foundation for all RFC 2617 compliant authetication schemes and provides capabilities common to all authentication schemes defined in RFC 2617.

Author:
Oleg Kalnichevski

Constructor Summary
RFC2617Scheme()
          Default constructor for RFC2617 compliant authetication schemes.
RFC2617Scheme(String challenge)
          Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
 
Method Summary
 String getID()
          Deprecated. no longer used
 String getParameter(String name)
          Returns authentication parameter with the given name, if available.
protected  Map getParameters()
          Returns authentication parameters map.
 String getRealm()
          Returns authentication realm.
 void processChallenge(String challenge)
          Processes the given challenge token.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface org.apache.commons.httpclient.auth.AuthScheme
authenticate, authenticate, getSchemeName, isComplete, isConnectionBased
 

Constructor Detail

RFC2617Scheme

public RFC2617Scheme()
Default constructor for RFC2617 compliant authetication schemes.

Since:
3.0

RFC2617Scheme

public RFC2617Scheme(String challenge)
              throws MalformedChallengeException
Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method

Default constructor for RFC2617 compliant authetication schemes.

Parameters:
challenge - authentication challenge
Throws:
MalformedChallengeException - is thrown if the authentication challenge is malformed
Method Detail

processChallenge

public void processChallenge(String challenge)
                      throws MalformedChallengeException
Processes the given challenge token. Some authentication schemes may involve multiple challenge-response exchanges. Such schemes must be able to maintain the state information when dealing with sequential challenges

Specified by:
processChallenge in interface AuthScheme
Parameters:
challenge - the challenge string
Throws:
MalformedChallengeException - is thrown if the authentication challenge is malformed
Since:
3.0

getParameters

protected Map getParameters()
Returns authentication parameters map. Keys in the map are lower-cased.

Returns:
the map of authentication parameters

getParameter

public String getParameter(String name)
Returns authentication parameter with the given name, if available.

Specified by:
getParameter in interface AuthScheme
Parameters:
name - The name of the parameter to be returned
Returns:
the parameter with the given name

getRealm

public String getRealm()
Returns authentication realm. The realm may not be null.

Specified by:
getRealm in interface AuthScheme
Returns:
the authentication realm

getID

public String getID()
Deprecated. no longer used

Returns a String identifying the authentication challenge. This is used, in combination with the host and port to determine if authorization has already been attempted or not. Schemes which require multiple requests to complete the authentication should return a different value for each stage in the request.

Additionally, the ID should take into account any changes to the authentication challenge and return a different value when appropriate. For example when the realm changes in basic authentication it should be considered a different authentication attempt and a different value should be returned.

This method simply returns the realm for the challenge.

Specified by:
getID in interface AuthScheme
Returns:
String a String identifying the authentication challenge. The returned value may be null.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthChallengeException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthChallengeExcept100644 0 0 21272 10661532627 31242 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.AuthChallengeException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.AuthChallengeException

Packages that use AuthChallengeException
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Uses of AuthChallengeException in org.apache.commons.httpclient.auth
 

Methods in org.apache.commons.httpclient.auth that throw AuthChallengeException
 AuthScheme AuthChallengeProcessor.selectAuthScheme(Map challenges)
          Determines the preferred authentication scheme that can be used to respond to the given collection of challenges.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthChallengeParser.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthChallengeParser100644 0 0 14060 10661532627 31243 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.AuthChallengeParser (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.AuthChallengeParser

No usage of org.apache.commons.httpclient.auth.AuthChallengeParser



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthChallengeProcessor.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthChallengeProces100644 0 0 14116 10661532627 31244 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.AuthChallengeProcessor (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.AuthChallengeProcessor

No usage of org.apache.commons.httpclient.auth.AuthChallengeProcessor



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthPolicy.html100644 0 0 13726 10661532627 30416 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.AuthPolicy (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.AuthPolicy

No usage of org.apache.commons.httpclient.auth.AuthPolicy



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthScheme.html100644 0 0 50023 10661532627 30352 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.auth.AuthScheme (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.auth.AuthScheme

Packages that use AuthScheme
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Uses of AuthScheme in org.apache.commons.httpclient.auth
 

Classes in org.apache.commons.httpclient.auth that implement AuthScheme
 class AuthSchemeBase
          Deprecated. No longer used
 class BasicScheme
           Basic authentication scheme as defined in RFC 2617.
 class DigestScheme
           Digest authentication scheme as defined in RFC 2617.
 class NTLMScheme
          An implementation of the Microsoft proprietary NTLM authentication scheme.
 class RFC2617Scheme
           Abstract authentication scheme class that lays foundation for all RFC 2617 compliant authetication schemes and provides capabilities common to all authentication schemes defined in RFC 2617.
 

Methods in org.apache.commons.httpclient.auth that return AuthScheme
 AuthScheme AuthState.getAuthScheme()
          Returns the authentication scheme.
static AuthScheme AuthPolicy.getAuthScheme(String id)
          Gets the authentication scheme with the given ID.
 AuthScheme AuthChallengeProcessor.processChallenge(AuthState state, Map challenges)
          Processes the given collection of challenges and updates the state of the authentication process.
static AuthScheme HttpAuthenticator.selectAuthScheme(Header[] challenges)
          Deprecated. Use AuthChallengeParser.parseChallenges(Header[]) and AuthPolicy.getAuthScheme(String)
 AuthScheme AuthChallengeProcessor.selectAuthScheme(Map challenges)
          Determines the preferred authentication scheme that can be used to respond to the given collection of challenges.
 

Methods in org.apache.commons.httpclient.auth with parameters of type AuthScheme
static boolean HttpAuthenticator.authenticate(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean HttpAuthenticator.authenticateProxy(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
 Credentials CredentialsProvider.getCredentials(AuthScheme scheme, String host, int port, boolean proxy)
          Requests additional authentication credentials.
 void AuthState.setAuthScheme(AuthScheme authScheme)
          Assigns the given authentication scheme.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthSchemeBase.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthSchemeBase.html100644 0 0 13776 10661532627 31163 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.AuthSchemeBase (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.AuthSchemeBase

No usage of org.apache.commons.httpclient.auth.AuthSchemeBase



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthScope.html100644 0 0 37765 10661532627 30241 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.AuthScope (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.AuthScope

Packages that use AuthScope
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Uses of AuthScope in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient with parameters of type AuthScope
 Credentials HttpState.getCredentials(AuthScope authscope)
          Get the credentials for the given authentication scope.
 Credentials HttpState.getProxyCredentials(AuthScope authscope)
          Get the proxy credentials for the given authentication scope.
 void HttpState.setCredentials(AuthScope authscope, Credentials credentials)
          Sets the credentials for the given authentication scope.
 void HttpState.setProxyCredentials(AuthScope authscope, Credentials credentials)
          Sets the proxy credentials for the given authentication realm.
 

Uses of AuthScope in org.apache.commons.httpclient.auth
 

Subclasses of AuthScope in org.apache.commons.httpclient.auth
 class HttpAuthRealm
          Deprecated. no longer used
 

Fields in org.apache.commons.httpclient.auth declared as AuthScope
static AuthScope AuthScope.ANY
          Default scope matching any host, port, realm and authentication scheme.
 

Methods in org.apache.commons.httpclient.auth with parameters of type AuthScope
 int AuthScope.match(AuthScope that)
          Tests if the authentication scopes match.
 

Constructors in org.apache.commons.httpclient.auth with parameters of type AuthScope
AuthScope(AuthScope authscope)
          Creates a copy of the given credentials scope.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthState.html100644 0 0 31241 10661532627 30227 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.AuthState (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.AuthState

Packages that use AuthState
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Uses of AuthState in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return AuthState
 AuthState HttpMethodBase.getHostAuthState()
          Returns the target host authentication state
 AuthState HttpMethod.getHostAuthState()
          Returns the target host authentication state
 AuthState HttpMethodBase.getProxyAuthState()
          Returns the proxy authentication state
 AuthState HttpMethod.getProxyAuthState()
          Returns the proxy authentication state
 

Uses of AuthState in org.apache.commons.httpclient.auth
 

Methods in org.apache.commons.httpclient.auth with parameters of type AuthState
 AuthScheme AuthChallengeProcessor.processChallenge(AuthState state, Map challenges)
          Processes the given collection of challenges and updates the state of the authentication process.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 156 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthenticationException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/AuthenticationExcep100644 0 0 67216 10661532627 31341 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.AuthenticationException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.AuthenticationException

Packages that use AuthenticationException
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Uses of AuthenticationException in org.apache.commons.httpclient.auth
 

Subclasses of AuthenticationException in org.apache.commons.httpclient.auth
 class AuthChallengeException
          Signals a failure processing authentication challenge
 class CredentialsNotAvailableException
          Authentication credentials required to respond to a authentication challenge are not available
 class InvalidCredentialsException
          Authentication credentials required to respond to a authentication challenge are invalid
 

Methods in org.apache.commons.httpclient.auth that throw AuthenticationException
static boolean HttpAuthenticator.authenticate(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
 String NTLMScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces NTLM authorization string for the given set of Credentials.
 String DigestScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces a digest authorization string for the given set of Credentials, method name and URI.
 String BasicScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces basic authorization string for the given set of Credentials.
 String AuthScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces an authorization string for the given set of Credentials.
 String NTLMScheme.authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use NTLMScheme.authenticate(Credentials, HttpMethod)
 String DigestScheme.authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use DigestScheme.authenticate(Credentials, HttpMethod)
 String BasicScheme.authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use BasicScheme.authenticate(Credentials, HttpMethod)
 String AuthScheme.authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use AuthScheme.authenticate(Credentials, HttpMethod) Produces an authorization string for the given set of Credentials, method name and URI using the given authentication scheme in response to the actual authorization challenge.
static String NTLMScheme.authenticate(NTCredentials credentials, String challenge)
          Deprecated. Use non-static NTLMScheme.authenticate(Credentials, HttpMethod)
static String NTLMScheme.authenticate(NTCredentials credentials, String challenge, String charset)
          Deprecated. Use non-static NTLMScheme.authenticate(Credentials, HttpMethod)
static boolean HttpAuthenticator.authenticateDefault(HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean HttpAuthenticator.authenticateProxy(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean HttpAuthenticator.authenticateProxyDefault(HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
 AuthScheme AuthChallengeProcessor.processChallenge(AuthState state, Map challenges)
          Processes the given collection of challenges and updates the state of the authentication process.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/BasicScheme.html100644 0 0 13740 10661532627 30477 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.BasicScheme (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.BasicScheme

No usage of org.apache.commons.httpclient.auth.BasicScheme



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 167 10661532634 10265 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/CredentialsNotAvailableException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/CredentialsNotAvail100644 0 0 22044 10661532627 31256 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.CredentialsNotAvailableException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.CredentialsNotAvailableException

Packages that use CredentialsNotAvailableException
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Uses of CredentialsNotAvailableException in org.apache.commons.httpclient.auth
 

Methods in org.apache.commons.httpclient.auth that throw CredentialsNotAvailableException
 Credentials CredentialsProvider.getCredentials(AuthScheme scheme, String host, int port, boolean proxy)
          Requests additional authentication credentials.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/CredentialsProvider.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/CredentialsProvider100644 0 0 14104 10661532627 31331 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.auth.CredentialsProvider (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.auth.CredentialsProvider

No usage of org.apache.commons.httpclient.auth.CredentialsProvider



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/DigestScheme.html100644 0 0 13752 10661532627 30700 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.DigestScheme (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.DigestScheme

No usage of org.apache.commons.httpclient.auth.DigestScheme



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/HttpAuthRealm.html100644 0 0 13764 10661532627 31061 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.HttpAuthRealm (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.HttpAuthRealm

No usage of org.apache.commons.httpclient.auth.HttpAuthRealm



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/HttpAuthenticator.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/HttpAuthenticator.h100644 0 0 14034 10661532627 31263 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.HttpAuthenticator (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.HttpAuthenticator

No usage of org.apache.commons.httpclient.auth.HttpAuthenticator



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 162 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/InvalidCredentialsException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/InvalidCredentialsE100644 0 0 14200 10661532627 31227 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.InvalidCredentialsException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.InvalidCredentialsException

No usage of org.apache.commons.httpclient.auth.InvalidCredentialsException



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 162 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/MalformedChallengeException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/MalformedChallengeE100644 0 0 45116 10661532627 31206 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.MalformedChallengeException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.MalformedChallengeException

Packages that use MalformedChallengeException
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Uses of MalformedChallengeException in org.apache.commons.httpclient.auth
 

Methods in org.apache.commons.httpclient.auth that throw MalformedChallengeException
static Map AuthChallengeParser.extractParams(String challengeStr)
          Extracts a map of challenge parameters from an authentication challenge.
static String AuthChallengeParser.extractScheme(String challengeStr)
          Extracts authentication scheme from the given authentication challenge.
static Map AuthChallengeParser.parseChallenges(Header[] headers)
          Extracts a map of challenges ordered by authentication scheme name
 AuthScheme AuthChallengeProcessor.processChallenge(AuthState state, Map challenges)
          Processes the given collection of challenges and updates the state of the authentication process.
 void NTLMScheme.processChallenge(String challenge)
          Processes the NTLM challenge.
 void DigestScheme.processChallenge(String challenge)
          Processes the Digest challenge.
 void RFC2617Scheme.processChallenge(String challenge)
          Processes the given challenge token.
 void BasicScheme.processChallenge(String challenge)
          Processes the Basic challenge.
 void AuthScheme.processChallenge(String challenge)
          Processes the given challenge token.
static AuthScheme HttpAuthenticator.selectAuthScheme(Header[] challenges)
          Deprecated. Use AuthChallengeParser.parseChallenges(Header[]) and AuthPolicy.getAuthScheme(String)
 

Constructors in org.apache.commons.httpclient.auth that throw MalformedChallengeException
AuthSchemeBase(String challenge)
          Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
BasicScheme(String challenge)
          Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
DigestScheme(String challenge)
          Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
NTLMScheme(String challenge)
          Constructor for the NTLM authentication scheme.
RFC2617Scheme(String challenge)
          Deprecated. Use parameterless constructor and AuthScheme.processChallenge(String) method
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/NTLMScheme.html100644 0 0 13726 10661532627 30234 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.NTLMScheme (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.NTLMScheme

No usage of org.apache.commons.httpclient.auth.NTLMScheme



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/class-use/RFC2617Scheme.html100644 0 0 20745 10661532627 30413 0ustar 0 0 Uses of Class org.apache.commons.httpclient.auth.RFC2617Scheme (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.auth.RFC2617Scheme

Packages that use RFC2617Scheme
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Uses of RFC2617Scheme in org.apache.commons.httpclient.auth
 

Subclasses of RFC2617Scheme in org.apache.commons.httpclient.auth
 class BasicScheme
           Basic authentication scheme as defined in RFC 2617.
 class DigestScheme
           Digest authentication scheme as defined in RFC 2617.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/package-frame.html100644 0 0 7371 10661532627 27100 0ustar 0 0 org.apache.commons.httpclient.auth (HttpClient 3.1 API) org.apache.commons.httpclient.auth
Interfaces 
AuthScheme
CredentialsProvider
Classes 
AuthChallengeParser
AuthChallengeProcessor
AuthPolicy
AuthSchemeBase
AuthScope
AuthState
BasicScheme
DigestScheme
HttpAuthenticator
HttpAuthRealm
NTLMScheme
RFC2617Scheme
Exceptions 
AuthChallengeException
AuthenticationException
CredentialsNotAvailableException
InvalidCredentialsException
MalformedChallengeException
commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/package-summary.html100644 0 0 33132 10661532627 27515 0ustar 0 0 org.apache.commons.httpclient.auth (HttpClient 3.1 API)

Package org.apache.commons.httpclient.auth

Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests.

See:
          Description

Interface Summary
AuthScheme This interface represents an abstract challenge-response oriented authentication scheme.
CredentialsProvider Credentials provider interface can be used to provide HTTP method with a means to request authentication credentials if no credentials have been given or given credentials are incorrect.
 

Class Summary
AuthChallengeParser This class provides utility methods for parsing HTTP www and proxy authentication challenges.
AuthChallengeProcessor This class provides utility methods for processing HTTP www and proxy authentication challenges.
AuthPolicy Authentication policy class.
AuthSchemeBase Deprecated. No longer used
AuthScope The class represents an authentication scope consisting of a host name, a port number, a realm name and an authentication scheme name which Credentials apply to.
AuthState This class provides detailed information about the state of the authentication process.
BasicScheme Basic authentication scheme as defined in RFC 2617.
DigestScheme Digest authentication scheme as defined in RFC 2617.
HttpAuthenticator Deprecated. no longer used
HttpAuthRealm Deprecated. no longer used
NTLMScheme An implementation of the Microsoft proprietary NTLM authentication scheme.
RFC2617Scheme Abstract authentication scheme class that lays foundation for all RFC 2617 compliant authetication schemes and provides capabilities common to all authentication schemes defined in RFC 2617.
 

Exception Summary
AuthChallengeException Signals a failure processing authentication challenge
AuthenticationException Signals a failure in authentication process
CredentialsNotAvailableException Authentication credentials required to respond to a authentication challenge are not available
InvalidCredentialsException Authentication credentials required to respond to a authentication challenge are invalid
MalformedChallengeException Signals that authentication challenge is in some way invalid or illegal in the given context
 

Package org.apache.commons.httpclient.auth Description

Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests.

Since:
2.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/package-tree.html100644 0 0 27506 10661532627 26767 0ustar 0 0 org.apache.commons.httpclient.auth Class Hierarchy (HttpClient 3.1 API)

Hierarchy For Package org.apache.commons.httpclient.auth

Package Hierarchies:
All Packages

Class Hierarchy

Interface Hierarchy



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/auth/package-use.html100644 0 0 27021 10661532627 26614 0ustar 0 0 Uses of Package org.apache.commons.httpclient.auth (HttpClient 3.1 API)

Uses of Package
org.apache.commons.httpclient.auth

Packages that use org.apache.commons.httpclient.auth
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Classes in org.apache.commons.httpclient.auth used by org.apache.commons.httpclient
AuthScope
          The class represents an authentication scope consisting of a host name, a port number, a realm name and an authentication scheme name which Credentials apply to.
AuthState
          This class provides detailed information about the state of the authentication process.
 

Classes in org.apache.commons.httpclient.auth used by org.apache.commons.httpclient.auth
AuthChallengeException
          Signals a failure processing authentication challenge
AuthenticationException
          Signals a failure in authentication process
AuthScheme
           This interface represents an abstract challenge-response oriented authentication scheme.
AuthScope
          The class represents an authentication scope consisting of a host name, a port number, a realm name and an authentication scheme name which Credentials apply to.
AuthState
          This class provides detailed information about the state of the authentication process.
CredentialsNotAvailableException
          Authentication credentials required to respond to a authentication challenge are not available
MalformedChallengeException
          Signals that authentication challenge is in some way invalid or illegal in the given context
RFC2617Scheme
           Abstract authentication scheme class that lays foundation for all RFC 2617 compliant authetication schemes and provides capabilities common to all authentication schemes defined in RFC 2617.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ChunkedInputStream.html100644 0 0 13701 10661532627 31142 0ustar 0 0 Uses of Class org.apache.commons.httpclient.ChunkedInputStream (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.ChunkedInputStream

No usage of org.apache.commons.httpclient.ChunkedInputStream



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ChunkedOutputStream.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ChunkedOutputStream.html100644 0 0 13713 10661532627 31346 0ustar 0 0 Uses of Class org.apache.commons.httpclient.ChunkedOutputStream (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.ChunkedOutputStream

No usage of org.apache.commons.httpclient.ChunkedOutputStream



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 153 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/CircularRedirectException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/CircularRedirectExceptio100644 0 0 14007 10661532627 31351 0ustar 0 0 Uses of Class org.apache.commons.httpclient.CircularRedirectException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.CircularRedirectException

No usage of org.apache.commons.httpclient.CircularRedirectException



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ConnectMethod.html100644 0 0 17720 10661532627 30124 0ustar 0 0 Uses of Class org.apache.commons.httpclient.ConnectMethod (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.ConnectMethod

Packages that use ConnectMethod
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of ConnectMethod in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return ConnectMethod
 ConnectMethod ProxyClient.ConnectResponse.getConnectMethod()
          Gets the method that was used to execute the connect.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ConnectTimeoutException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ConnectTimeoutException.100644 0 0 40440 10661532627 31317 0ustar 0 0 Uses of Class org.apache.commons.httpclient.ConnectTimeoutException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.ConnectTimeoutException

Packages that use ConnectTimeoutException
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.protocol Provides protocol specific socket factory handling. 
 

Uses of ConnectTimeoutException in org.apache.commons.httpclient
 

Subclasses of ConnectTimeoutException in org.apache.commons.httpclient
 class ConnectionPoolTimeoutException
          A timeout while connecting waiting for an available connection from an HttpConnectionManager.
 

Uses of ConnectTimeoutException in org.apache.commons.httpclient.protocol
 

Methods in org.apache.commons.httpclient.protocol that throw ConnectTimeoutException
static Socket ControllerThreadSocketFactory.createSocket(ControllerThreadSocketFactory.SocketTask task, int timeout)
           
static Socket ControllerThreadSocketFactory.createSocket(ProtocolSocketFactory socketfactory, String host, int port, InetAddress localAddress, int localPort, int timeout)
          This method spawns a controller thread overseeing the process of socket initialisation.
 Socket SSLProtocolSocketFactory.createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params)
          Attempts to get a new socket connection to the given host within the given time limit.
 Socket DefaultProtocolSocketFactory.createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params)
          Attempts to get a new socket connection to the given host within the given time limit.
 Socket ProtocolSocketFactory.createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params)
          Gets a new socket connection to the given host.
static Socket ReflectionSocketFactory.createSocket(String socketfactoryName, String host, int port, InetAddress localAddress, int localPort, int timeout)
          This method attempts to execute Socket method available since Java 1.4 using reflection.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 160 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ConnectionPoolTimeoutException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ConnectionPoolTimeoutExc100644 0 0 22527 10661532627 31370 0ustar 0 0 Uses of Class org.apache.commons.httpclient.ConnectionPoolTimeoutException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.ConnectionPoolTimeoutException

Packages that use ConnectionPoolTimeoutException
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of ConnectionPoolTimeoutException in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that throw ConnectionPoolTimeoutException
 HttpConnection MultiThreadedHttpConnectionManager.getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
          Gets a connection or waits if one is not available.
 HttpConnection HttpConnectionManager.getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
          Gets an HttpConnection for a given host configuration.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ContentLengthInputStream.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ContentLengthInputStream100644 0 0 13775 10661532627 31405 0ustar 0 0 Uses of Class org.apache.commons.httpclient.ContentLengthInputStream (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.ContentLengthInputStream

No usage of org.apache.commons.httpclient.ContentLengthInputStream



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/Cookie.html100644 0 0 172126 10661532627 26625 0ustar 0 0 Uses of Class org.apache.commons.httpclient.Cookie (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.Cookie

Packages that use Cookie
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
 

Uses of Cookie in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return Cookie
 Cookie[] HttpState.getCookies()
          Returns an array of cookies that this HTTP state currently contains.
 Cookie[] HttpState.getCookies(String domain, int port, String path, boolean secure)
          Deprecated. use CookieSpec#match(String, int, String, boolean, Cookie)
 

Methods in org.apache.commons.httpclient with parameters of type Cookie
 void HttpState.addCookie(Cookie cookie)
          Adds an HTTP cookie, replacing any existing equivalent cookies.
 void HttpState.addCookies(Cookie[] cookies)
          Adds an array of HTTP cookies.
 

Uses of Cookie in org.apache.commons.httpclient.cookie
 

Subclasses of Cookie in org.apache.commons.httpclient.cookie
 class Cookie2
           Cookie class for RFC2965Spec cookie specification.
 

Methods in org.apache.commons.httpclient.cookie that return Cookie
 Cookie[] IgnoreCookiesSpec.match(String host, int port, String path, boolean secure, Cookie[] cookies)
          Returns an empty cookie array.
 Cookie[] CookieSpecBase.match(String host, int port, String path, boolean secure, Cookie[] cookies)
          Return an array of Cookies that should be submitted with a request with given attributes, false otherwise.
 Cookie[] CookieSpec.match(String host, int port, String path, boolean secure, Cookie[] cookies)
          Determines which of an array of Cookies matches a location.
 Cookie[] RFC2965Spec.parse(String host, int port, String path, boolean secure, Header header)
          Parses the Set-Cookie2 value into an array of Cookies.
 Cookie[] IgnoreCookiesSpec.parse(String host, int port, String path, boolean secure, Header header)
          Returns an empty cookie array.
 Cookie[] CookieSpecBase.parse(String host, int port, String path, boolean secure, Header header)
          Parse the "Set-Cookie" Header into an array of Cookies.
 Cookie[] CookieSpec.parse(String host, int port, String path, boolean secure, Header header)
          Parse the "Set-Cookie" Header into an array of Cookies.
 Cookie[] RFC2965Spec.parse(String host, int port, String path, boolean secure, String header)
           
 Cookie[] NetscapeDraftSpec.parse(String host, int port, String path, boolean secure, String header)
          Parses the Set-Cookie value into an array of Cookies.
 Cookie[] IgnoreCookiesSpec.parse(String host, int port, String path, boolean secure, String header)
          Returns an empty cookie array.
 Cookie[] CookieSpecBase.parse(String host, int port, String path, boolean secure, String header)
          Parses the Set-Cookie value into an array of Cookies.
 Cookie[] CookieSpec.parse(String host, int port, String path, boolean secure, String header)
          Parse the "Set-Cookie" header value into Cookie array.
 

Methods in org.apache.commons.httpclient.cookie with parameters of type Cookie
 String RFC2965Spec.formatCookie(Cookie cookie)
          Return a string suitable for sending in a "Cookie" header as defined in RFC 2965
 String RFC2109Spec.formatCookie(Cookie cookie)
          Return a string suitable for sending in a "Cookie" header as defined in RFC 2109
 String IgnoreCookiesSpec.formatCookie(Cookie cookie)
           
 String CookieSpecBase.formatCookie(Cookie cookie)
          Return a string suitable for sending in a "Cookie" header
 String CookieSpec.formatCookie(Cookie cookie)
          Create a "Cookie" header value for an array of cookies.
 Header IgnoreCookiesSpec.formatCookieHeader(Cookie cookie)
           
 Header CookieSpecBase.formatCookieHeader(Cookie cookie)
          Create a "Cookie" Header containing the Cookie.
 Header CookieSpec.formatCookieHeader(Cookie cookie)
          Create a "Cookie" Header for single Cookie.
 Header IgnoreCookiesSpec.formatCookieHeader(Cookie[] cookies)
           
 Header CookieSpecBase.formatCookieHeader(Cookie[] cookies)
          Create a "Cookie" Header containing all Cookies in cookies.
 Header CookieSpec.formatCookieHeader(Cookie[] cookies)
          Create a "Cookie" Header for an array of Cookies.
 String RFC2965Spec.formatCookies(Cookie[] cookies)
          Create a RFC 2965 compliant "Cookie" header value containing all Cookies suitable for sending in a "Cookie" header
 String RFC2109Spec.formatCookies(Cookie[] cookies)
          Create a RFC 2109 compliant "Cookie" header value containing all Cookies in cookies suitable for sending in a "Cookie" header
 String IgnoreCookiesSpec.formatCookies(Cookie[] cookies)
           
 String CookieSpecBase.formatCookies(Cookie[] cookies)
          Create a "Cookie" header value containing all Cookies in cookies suitable for sending in a "Cookie" header
 String CookieSpec.formatCookies(Cookie[] cookies)
          Create a "Cookie" header value for an array of cookies.
 boolean CookieAttributeHandler.match(Cookie cookie, CookieOrigin origin)
          Matches the given value (property of the destination host where request is being submitted) with the corresponding cookie attribute.
 boolean RFC2965Spec.match(String host, int port, String path, boolean secure, Cookie cookie)
          Return true if the cookie should be submitted with a request with given attributes, false otherwise.
 boolean IgnoreCookiesSpec.match(String host, int port, String path, boolean secure, Cookie cookie)
           
 boolean CookieSpecBase.match(String host, int port, String path, boolean secure, Cookie cookie)
          Return true if the cookie should be submitted with a request with given attributes, false otherwise.
 boolean CookieSpec.match(String host, int port, String path, boolean secure, Cookie cookie)
          Determines if a Cookie matches a location.
 Cookie[] IgnoreCookiesSpec.match(String host, int port, String path, boolean secure, Cookie[] cookies)
          Returns an empty cookie array.
 Cookie[] CookieSpecBase.match(String host, int port, String path, boolean secure, Cookie[] cookies)
          Return an array of Cookies that should be submitted with a request with given attributes, false otherwise.
 Cookie[] CookieSpec.match(String host, int port, String path, boolean secure, Cookie[] cookies)
          Determines which of an array of Cookies matches a location.
 void CookieAttributeHandler.parse(Cookie cookie, String value)
          Parse the given cookie attribute value and update the corresponding Cookie property.
 void RFC2965Spec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse RFC 2965 specific cookie attribute and update the corresponsing Cookie properties.
 void RFC2109Spec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse RFC 2109 specific cookie attribute and update the corresponsing Cookie properties.
 void NetscapeDraftSpec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties as defined by the Netscape draft specification
 void IgnoreCookiesSpec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Does nothing.
 void CookieSpecBase.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties.
 void CookieSpec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties.
 void CookieAttributeHandler.validate(Cookie cookie, CookieOrigin origin)
          Peforms cookie validation for the given attribute value.
 void RFC2965Spec.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs RFC 2965 compliant Cookie validation
 void RFC2109Spec.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs RFC 2109 compliant Cookie validation
 void NetscapeDraftSpec.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs Netscape draft compliant Cookie validation
 void IgnoreCookiesSpec.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Does nothing.
 void CookieSpecBase.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs most common Cookie validation
 void CookieSpec.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Validate the cookie according to validation rules defined by the cookie specification.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/Credentials.html100644 0 0 72607 10661532627 27634 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.Credentials (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.Credentials

Packages that use Credentials
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Uses of Credentials in org.apache.commons.httpclient
 

Classes in org.apache.commons.httpclient that implement Credentials
 class NTCredentials
          Credentials for use with the NTLM authentication scheme which requires additional information.
 class UsernamePasswordCredentials
          Username and password Credentials.
 

Methods in org.apache.commons.httpclient that return Credentials
 Credentials HttpState.getCredentials(AuthScope authscope)
          Get the credentials for the given authentication scope.
 Credentials HttpState.getCredentials(String realm, String host)
          Deprecated. use #getCredentials(AuthScope)
 Credentials HttpState.getProxyCredentials(AuthScope authscope)
          Get the proxy credentials for the given authentication scope.
 Credentials HttpState.getProxyCredentials(String realm, String proxyHost)
          Deprecated. use #getProxyCredentials(AuthScope)
 

Methods in org.apache.commons.httpclient with parameters of type Credentials
 void HttpState.setCredentials(AuthScope authscope, Credentials credentials)
          Sets the credentials for the given authentication scope.
 void HttpState.setCredentials(String realm, String host, Credentials credentials)
          Deprecated. use #setCredentials(AuthScope, Credentials)
 void HttpState.setProxyCredentials(AuthScope authscope, Credentials credentials)
          Sets the proxy credentials for the given authentication realm.
 void HttpState.setProxyCredentials(String realm, String proxyHost, Credentials credentials)
          Deprecated. use #setProxyCredentials(AuthScope, Credentials)
 

Uses of Credentials in org.apache.commons.httpclient.auth
 

Methods in org.apache.commons.httpclient.auth that return Credentials
 Credentials CredentialsProvider.getCredentials(AuthScheme scheme, String host, int port, boolean proxy)
          Requests additional authentication credentials.
 

Methods in org.apache.commons.httpclient.auth with parameters of type Credentials
 String NTLMScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces NTLM authorization string for the given set of Credentials.
 String DigestScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces a digest authorization string for the given set of Credentials, method name and URI.
 String BasicScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces basic authorization string for the given set of Credentials.
 String AuthScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces an authorization string for the given set of Credentials.
 String NTLMScheme.authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use NTLMScheme.authenticate(Credentials, HttpMethod)
 String DigestScheme.authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use DigestScheme.authenticate(Credentials, HttpMethod)
 String BasicScheme.authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use BasicScheme.authenticate(Credentials, HttpMethod)
 String AuthScheme.authenticate(Credentials credentials, String method, String uri)
          Deprecated. Use AuthScheme.authenticate(Credentials, HttpMethod) Produces an authorization string for the given set of Credentials, method name and URI using the given authentication scheme in response to the actual authorization challenge.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 157 10661532634 10264 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/DefaultHttpMethodRetryHandler.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/DefaultHttpMethodRetryHa100644 0 0 14057 10661532627 31313 0ustar 0 0 Uses of Class org.apache.commons.httpclient.DefaultHttpMethodRetryHandler (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.DefaultHttpMethodRetryHandler

No usage of org.apache.commons.httpclient.DefaultHttpMethodRetryHandler



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 153 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/DefaultMethodRetryHandler.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/DefaultMethodRetryHandle100644 0 0 14007 10661532627 31311 0ustar 0 0 Uses of Class org.apache.commons.httpclient.DefaultMethodRetryHandler (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.DefaultMethodRetryHandler

No usage of org.apache.commons.httpclient.DefaultMethodRetryHandler



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/Header.html100644 0 0 134532 10661532627 26603 0ustar 0 0 Uses of Class org.apache.commons.httpclient.Header (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.Header

Packages that use Header
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
 

Uses of Header in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return Header
 Header[] HeaderGroup.getAllHeaders()
          Gets all of the headers contained within this group.
 Header HeaderGroup.getCondensedHeader(String name)
          Gets a header representing all of the header values with the given name.
 Header HeaderGroup.getFirstHeader(String name)
          Gets the first header with the given name.
 Header[] HeaderGroup.getHeaders(String name)
          Gets all of the headers with the given name.
 Header HeaderGroup.getLastHeader(String name)
          Gets the last header with the given name.
 Header HttpMethodBase.getRequestHeader(String headerName)
          Returns the specified request header.
 Header HttpMethod.getRequestHeader(String headerName)
          Gets the request header with the given name.
 Header[] HttpMethodBase.getRequestHeaders()
          Returns an array of the requests headers that the HTTP method currently has
 Header[] HttpMethod.getRequestHeaders()
          Returns the current request headers for this HTTP method.
 Header[] HttpMethodBase.getRequestHeaders(String headerName)
           
 Header[] HttpMethod.getRequestHeaders(String headerName)
          Returns the request headers with the given name.
 Header HttpMethodBase.getResponseFooter(String footerName)
          Gets the response footer associated with the given name.
 Header HttpMethod.getResponseFooter(String footerName)
          Return the specified response footer.
 Header[] HttpMethodBase.getResponseFooters()
          Returns an array of the response footers that the HTTP method currently has in the order in which they were read.
 Header[] HttpMethod.getResponseFooters()
          Returns the response footers from the most recent execution of this request.
 Header HttpMethodBase.getResponseHeader(String headerName)
          Gets the response header associated with the given name.
 Header HttpMethod.getResponseHeader(String headerName)
          Returns the specified response header.
 Header[] HttpMethodBase.getResponseHeaders()
          Returns an array of the response headers that the HTTP method currently has in the order in which they were read.
 Header[] HttpMethod.getResponseHeaders()
          Returns the response headers from the most recent execution of this request.
 Header[] HttpMethodBase.getResponseHeaders(String headerName)
           
 Header[] HttpMethod.getResponseHeaders(String headerName)
          Returns the response headers with the given name.
static Header[] HttpParser.parseHeaders(InputStream is)
          Deprecated. use #parseHeaders(InputStream, String)
static Header[] HttpParser.parseHeaders(InputStream is, String charset)
          Parses headers from the given stream.
 

Methods in org.apache.commons.httpclient with parameters of type Header
 void HeaderGroup.addHeader(Header header)
          Adds the given header to the group.
 void HttpMethodBase.addRequestHeader(Header header)
          Adds the specified request header, NOT overwriting any previous value.
 void HttpMethod.addRequestHeader(Header header)
          Adds the specified request header, not overwriting any previous value.
 void HttpMethodBase.addResponseFooter(Header footer)
          Use this method internally to add footers.
 void HttpMethod.addResponseFooter(Header footer)
          Add a footer to this method's response.
protected  String HttpMethodBase.getContentCharSet(Header contentheader)
          Returns the character set from the Content-Type header.
protected  void HttpMethodBase.processCookieHeaders(CookieSpec parser, Header[] headers, HttpState state, HttpConnection conn)
          This method processes the specified cookie headers.
 void HeaderGroup.removeHeader(Header header)
          Removes the given header.
 void HttpMethodBase.removeRequestHeader(Header header)
          Removes the given request header.
 void HttpMethod.removeRequestHeader(Header header)
          Removes the given request header.
 void HeaderGroup.setHeaders(Header[] headers)
          Sets all of the headers contained within this group overriding any existing headers.
 void HttpMethodBase.setRequestHeader(Header header)
          Sets the specified request header, overwriting any previous value.
 void HttpMethod.setRequestHeader(Header header)
          Sets the specified request header, overwriting any previous value.
 

Uses of Header in org.apache.commons.httpclient.auth
 

Methods in org.apache.commons.httpclient.auth with parameters of type Header
static Map AuthChallengeParser.parseChallenges(Header[] headers)
          Extracts a map of challenges ordered by authentication scheme name
static AuthScheme HttpAuthenticator.selectAuthScheme(Header[] challenges)
          Deprecated. Use AuthChallengeParser.parseChallenges(Header[]) and AuthPolicy.getAuthScheme(String)
 

Uses of Header in org.apache.commons.httpclient.cookie
 

Methods in org.apache.commons.httpclient.cookie that return Header
 Header IgnoreCookiesSpec.formatCookieHeader(Cookie cookie)
           
 Header CookieSpecBase.formatCookieHeader(Cookie cookie)
          Create a "Cookie" Header containing the Cookie.
 Header CookieSpec.formatCookieHeader(Cookie cookie)
          Create a "Cookie" Header for single Cookie.
 Header IgnoreCookiesSpec.formatCookieHeader(Cookie[] cookies)
           
 Header CookieSpecBase.formatCookieHeader(Cookie[] cookies)
          Create a "Cookie" Header containing all Cookies in cookies.
 Header CookieSpec.formatCookieHeader(Cookie[] cookies)
          Create a "Cookie" Header for an array of Cookies.
 Header RFC2965Spec.getVersionHeader()
           
 Header CookieVersionSupport.getVersionHeader()
           
 

Methods in org.apache.commons.httpclient.cookie with parameters of type Header
 Cookie[] RFC2965Spec.parse(String host, int port, String path, boolean secure, Header header)
          Parses the Set-Cookie2 value into an array of Cookies.
 Cookie[] IgnoreCookiesSpec.parse(String host, int port, String path, boolean secure, Header header)
          Returns an empty cookie array.
 Cookie[] CookieSpecBase.parse(String host, int port, String path, boolean secure, Header header)
          Parse the "Set-Cookie" Header into an array of Cookies.
 Cookie[] CookieSpec.parse(String host, int port, String path, boolean secure, Header header)
          Parse the "Set-Cookie" Header into an array of Cookies.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HeaderElement.html100644 0 0 25023 10661532627 30067 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HeaderElement (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HeaderElement

Packages that use HeaderElement
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of HeaderElement in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return HeaderElement
 HeaderElement[] Header.getElements()
          Returns an array of HeaderElements constructed from my value.
 HeaderElement[] Header.getValues()
          Deprecated. Use #getElements
static HeaderElement[] HeaderElement.parse(String headerValue)
          Deprecated. Use #parseElements(String).
static HeaderElement[] HeaderElement.parseElements(char[] headerValue)
          This parses the value part of a header.
static HeaderElement[] HeaderElement.parseElements(String headerValue)
          This parses the value part of a header.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HeaderGroup.html100644 0 0 22777 10661532627 27607 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HeaderGroup (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HeaderGroup

Packages that use HeaderGroup
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of HeaderGroup in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return HeaderGroup
protected  HeaderGroup HttpMethodBase.getRequestHeaderGroup()
          Gets the header group storing the request headers.
protected  HeaderGroup HttpMethodBase.getResponseHeaderGroup()
          Gets the header group storing the response headers.
protected  HeaderGroup HttpMethodBase.getResponseTrailerHeaderGroup()
          Gets the header group storing the response trailer headers as per RFC 2616 section 3.6.1.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HostConfiguration.html100644 0 0 73774 10661532627 31052 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HostConfiguration (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HostConfiguration

Packages that use HostConfiguration
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.params HttpClient preferences framework. 
 

Uses of HostConfiguration in org.apache.commons.httpclient
 

Fields in org.apache.commons.httpclient declared as HostConfiguration
static HostConfiguration HostConfiguration.ANY_HOST_CONFIGURATION
          A value to represent any host configuration, instead of using something like null.
 

Methods in org.apache.commons.httpclient that return HostConfiguration
 HostConfiguration ProxyClient.getHostConfiguration()
          Returns the host configuration associated with the ProxyClient.
 HostConfiguration HttpClient.getHostConfiguration()
          Returns the host configuration associated with the HttpClient.
 HostConfiguration HttpMethodBase.getHostConfiguration()
          Deprecated. no longer applicable
 HostConfiguration HttpMethod.getHostConfiguration()
          Deprecated. no longer applicable
 

Methods in org.apache.commons.httpclient with parameters of type HostConfiguration
 int HttpClient.executeMethod(HostConfiguration hostConfiguration, HttpMethod method)
          Executes the given HTTP method using custom host configuration.
 int HttpClient.executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state)
          Executes the given HTTP method using the given custom host configuration with the given custom HTTP state.
 HttpConnection SimpleHttpConnectionManager.getConnection(HostConfiguration hostConfiguration)
           
 HttpConnection MultiThreadedHttpConnectionManager.getConnection(HostConfiguration hostConfiguration)
           
 HttpConnection HttpConnectionManager.getConnection(HostConfiguration hostConfiguration)
          Gets an HttpConnection for a given host configuration.
 HttpConnection SimpleHttpConnectionManager.getConnection(HostConfiguration hostConfiguration, long timeout)
          Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
 HttpConnection MultiThreadedHttpConnectionManager.getConnection(HostConfiguration hostConfiguration, long timeout)
          Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
 HttpConnection HttpConnectionManager.getConnection(HostConfiguration hostConfiguration, long timeout)
          Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
 int MultiThreadedHttpConnectionManager.getConnectionsInPool(HostConfiguration hostConfiguration)
          Gets the total number of pooled connections for the given host configuration.
 int MultiThreadedHttpConnectionManager.getConnectionsInUse(HostConfiguration hostConfiguration)
          Deprecated. Use MultiThreadedHttpConnectionManager.getConnectionsInPool(HostConfiguration)
 HttpConnection SimpleHttpConnectionManager.getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
          This method always returns the same connection object.
 HttpConnection MultiThreadedHttpConnectionManager.getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
          Gets a connection or waits if one is not available.
 HttpConnection HttpConnectionManager.getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
          Gets an HttpConnection for a given host configuration.
 void ProxyClient.setHostConfiguration(HostConfiguration hostConfiguration)
          Assigns the host configuration to use with the ProxyClient.
 void HttpClient.setHostConfiguration(HostConfiguration hostConfiguration)
          Assigns the host configuration to use with the HttpClient.
 void HttpMethodBase.setHostConfiguration(HostConfiguration hostconfig)
          Deprecated. no longer applicable
 

Constructors in org.apache.commons.httpclient with parameters of type HostConfiguration
ConnectMethod(HostConfiguration targethost)
          Create a connect method.
HostConfiguration(HostConfiguration hostConfiguration)
          Copy constructor for HostConfiguration
HttpConnection(HostConfiguration hostConfiguration)
          Creates a new HTTP connection for the given host configuration.
 

Uses of HostConfiguration in org.apache.commons.httpclient.params
 

Methods in org.apache.commons.httpclient.params with parameters of type HostConfiguration
 int HttpConnectionManagerParams.getMaxConnectionsPerHost(HostConfiguration hostConfiguration)
          Gets the maximum number of connections to be used for a particular host config.
 void HttpConnectionManagerParams.setMaxConnectionsPerHost(HostConfiguration hostConfiguration, int maxHostConnections)
          Sets the maximum number of connections to be used for the given host config.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpClient.html100644 0 0 13561 10661532627 27447 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpClient (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpClient

No usage of org.apache.commons.httpclient.HttpClient



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpClientError.html100644 0 0 13643 10661532627 30462 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpClientError (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpClientError

No usage of org.apache.commons.httpclient.HttpClientError



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpConnection.html100644 0 0 205707 10661532627 30355 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpConnection (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpConnection

Packages that use HttpConnection
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient. 
 

Uses of HttpConnection in org.apache.commons.httpclient
 

Fields in org.apache.commons.httpclient declared as HttpConnection
protected  HttpConnection SimpleHttpConnectionManager.httpConnection
          The http connection
 

Methods in org.apache.commons.httpclient that return HttpConnection
 HttpConnection SimpleHttpConnectionManager.getConnection(HostConfiguration hostConfiguration)
           
 HttpConnection MultiThreadedHttpConnectionManager.getConnection(HostConfiguration hostConfiguration)
           
 HttpConnection HttpConnectionManager.getConnection(HostConfiguration hostConfiguration)
          Gets an HttpConnection for a given host configuration.
 HttpConnection SimpleHttpConnectionManager.getConnection(HostConfiguration hostConfiguration, long timeout)
          Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
 HttpConnection MultiThreadedHttpConnectionManager.getConnection(HostConfiguration hostConfiguration, long timeout)
          Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
 HttpConnection HttpConnectionManager.getConnection(HostConfiguration hostConfiguration, long timeout)
          Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
 HttpConnection SimpleHttpConnectionManager.getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
          This method always returns the same connection object.
 HttpConnection MultiThreadedHttpConnectionManager.getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
          Gets a connection or waits if one is not available.
 HttpConnection HttpConnectionManager.getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
          Gets an HttpConnection for a given host configuration.
 

Methods in org.apache.commons.httpclient with parameters of type HttpConnection
protected  void HttpMethodBase.addCookieRequestHeader(HttpState state, HttpConnection conn)
          Generates Cookie request headers for those cookies that match the given host, port and path.
protected  void ConnectMethod.addCookieRequestHeader(HttpState state, HttpConnection conn)
          This method does nothing.
protected  void HttpMethodBase.addHostRequestHeader(HttpState state, HttpConnection conn)
          Generates Host request header, as long as no Host request header already exists.
protected  void HttpMethodBase.addProxyConnectionHeader(HttpState state, HttpConnection conn)
          Generates Proxy-Connection: Keep-Alive request header when communicating via a proxy server.
protected  void HttpMethodBase.addRequestHeaders(HttpState state, HttpConnection conn)
          Generates all the required request headers to be submitted via the given connection.
protected  void ConnectMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
protected  void HttpMethodBase.addUserAgentRequestHeader(HttpState state, HttpConnection conn)
          Generates default User-Agent request header, as long as no User-Agent request header already exists.
 int HttpMethodBase.execute(HttpState state, HttpConnection conn)
          Executes this method using the specified HttpConnection and HttpState.
 int ConnectMethod.execute(HttpState state, HttpConnection conn)
          Execute this method and create a tunneled HttpConnection.
 int HttpMethod.execute(HttpState state, HttpConnection connection)
          Executes this method using the specified HttpConnection and HttpState.
protected static String HttpMethodBase.generateRequestLine(HttpConnection connection, String name, String requestPath, String query, String version)
          Generates HTTP request line according to the specified attributes.
 boolean HostConfiguration.hostEquals(HttpConnection connection)
          Tests if the host configuration equals the configuration set on the connection.
protected  void HttpMethodBase.processCookieHeaders(CookieSpec parser, Header[] headers, HttpState state, HttpConnection conn)
          This method processes the specified cookie headers.
protected  void HttpMethodBase.processResponseBody(HttpState state, HttpConnection conn)
          This method is invoked immediately after HttpMethodBase.readResponseBody(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom body processing.
protected  void HttpMethodBase.processResponseHeaders(HttpState state, HttpConnection conn)
          This method is invoked immediately after HttpMethodBase.readResponseHeaders(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom response headers processing.
protected  void HttpMethodBase.processStatusLine(HttpState state, HttpConnection conn)
          This method is invoked immediately after HttpMethodBase.readStatusLine(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom response status line processing.
 boolean HostConfiguration.proxyEquals(HttpConnection connection)
          Tests if the proxy configuration equals the configuration set on the connection.
protected  void HttpMethodBase.readResponse(HttpState state, HttpConnection conn)
          Reads the response from the given connection.
protected  void HttpMethodBase.readResponseBody(HttpState state, HttpConnection conn)
          Read the response body from the given HttpConnection.
protected  void HttpMethodBase.readResponseHeaders(HttpState state, HttpConnection conn)
          Reads the response headers from the given connection.
protected  void HttpMethodBase.readStatusLine(HttpState state, HttpConnection conn)
          Read the status line from the given HttpConnection, setting my status code and status text.
 void SimpleHttpConnectionManager.releaseConnection(HttpConnection conn)
           
 void MultiThreadedHttpConnectionManager.releaseConnection(HttpConnection conn)
          Make the given HttpConnection available for use by other requests.
 void HttpConnectionManager.releaseConnection(HttpConnection conn)
          Releases the given HttpConnection for use by other requests.
 boolean DefaultMethodRetryHandler.retryMethod(HttpMethod method, HttpConnection connection, HttpRecoverableException recoverableException, int executionCount, boolean requestSent)
          Deprecated. Used retryCount and requestSentRetryEnabled to determine if the given method should be retried.
 boolean MethodRetryHandler.retryMethod(HttpMethod method, HttpConnection connection, HttpRecoverableException recoverableException, int executionCount, boolean requestSent)
          Deprecated. Determines if a method should be retried after an HttpRecoverableException occurs during execution.
protected  boolean HttpMethodBase.shouldCloseConnection(HttpConnection conn)
          Tests if the connection should be closed after the method has been executed.
protected  boolean ConnectMethod.shouldCloseConnection(HttpConnection conn)
          Returns true if the status code is anything other than SC_OK, false otherwise.
protected  void HttpMethodBase.writeRequest(HttpState state, HttpConnection conn)
           Sends the request via the given connection.
protected  boolean HttpMethodBase.writeRequestBody(HttpState state, HttpConnection conn)
          Writes the request body to the given connection.
protected  void HttpMethodBase.writeRequestHeaders(HttpState state, HttpConnection conn)
          Writes the request headers to the given connection.
protected  void HttpMethodBase.writeRequestLine(HttpState state, HttpConnection conn)
          Writes the request line to the given connection.
protected  void ConnectMethod.writeRequestLine(HttpState state, HttpConnection conn)
          Special Connect request.
 

Uses of HttpConnection in org.apache.commons.httpclient.auth
 

Methods in org.apache.commons.httpclient.auth with parameters of type HttpConnection
static boolean HttpAuthenticator.authenticate(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean HttpAuthenticator.authenticateDefault(HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean HttpAuthenticator.authenticateProxy(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean HttpAuthenticator.authenticateProxyDefault(HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
 

Uses of HttpConnection in org.apache.commons.httpclient.methods
 

Methods in org.apache.commons.httpclient.methods with parameters of type HttpConnection
protected  void MultipartPostMethod.addContentLengthRequestHeader(HttpState state, HttpConnection conn)
          Deprecated. Adds a Content-Length request header, as long as no Content-Length request header already exists.
protected  void EntityEnclosingMethod.addContentLengthRequestHeader(HttpState state, HttpConnection conn)
          Generates Content-Length or Transfer-Encoding: Chunked request header, as long as no Content-Length request header already exists.
protected  void MultipartPostMethod.addContentTypeRequestHeader(HttpState state, HttpConnection conn)
          Deprecated. Adds a Content-Type request header.
protected  void MultipartPostMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Deprecated. Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
protected  void ExpectContinueMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Sets the Expect header if it has not already been set, in addition to the "standard" set of headers.
protected  void EntityEnclosingMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
protected  void OptionsMethod.processResponseHeaders(HttpState state, HttpConnection conn)
           This implementation will parse the Allow header to obtain the set of methods supported by the resource identified by the Request-URI.
protected  void HeadMethod.readResponseBody(HttpState state, HttpConnection conn)
          Overrides HttpMethodBase method to not read a response body, despite the presence of a Content-Length or Transfer-Encoding header.
protected  boolean MultipartPostMethod.writeRequestBody(HttpState state, HttpConnection conn)
          Deprecated. Writes the request body to the given connection.
protected  boolean EntityEnclosingMethod.writeRequestBody(HttpState state, HttpConnection conn)
          Writes the request body to the given connection.
 

Uses of HttpConnection in org.apache.commons.httpclient.util
 

Methods in org.apache.commons.httpclient.util with parameters of type HttpConnection
 void IdleConnectionHandler.add(HttpConnection connection)
          Registers the given connection with this handler.
 void IdleConnectionHandler.remove(HttpConnection connection)
          Removes the given connection from the list of connections to be closed when idle.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpConnectionManager.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpConnectionManager.ht100644 0 0 44004 10661532627 31266 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.HttpConnectionManager (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.HttpConnectionManager

Packages that use HttpConnectionManager
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient. 
 

Uses of HttpConnectionManager in org.apache.commons.httpclient
 

Classes in org.apache.commons.httpclient that implement HttpConnectionManager
 class MultiThreadedHttpConnectionManager
          Manages a set of HttpConnections for various HostConfigurations.
 class SimpleHttpConnectionManager
          A connection manager that provides access to a single HttpConnection.
 

Methods in org.apache.commons.httpclient that return HttpConnectionManager
 HttpConnectionManager HttpClient.getHttpConnectionManager()
          Returns the HTTP connection manager associated with the HttpClient.
 HttpConnectionManager HttpConnection.getHttpConnectionManager()
          Returns the httpConnectionManager.
 

Methods in org.apache.commons.httpclient with parameters of type HttpConnectionManager
 void HttpClient.setHttpConnectionManager(HttpConnectionManager httpConnectionManager)
          Assigns the HTTP connection manager to use with the HttpClient.
 void HttpConnection.setHttpConnectionManager(HttpConnectionManager httpConnectionManager)
          Sets the httpConnectionManager.
 

Constructors in org.apache.commons.httpclient with parameters of type HttpConnectionManager
HttpClient(HttpClientParams params, HttpConnectionManager httpConnectionManager)
          Creates an instance of HttpClient with a user specified parameter set and HTTP connection manager.
HttpClient(HttpConnectionManager httpConnectionManager)
          Creates an instance of HttpClient with a user specified HTTP connection manager.
 

Uses of HttpConnectionManager in org.apache.commons.httpclient.util
 

Methods in org.apache.commons.httpclient.util with parameters of type HttpConnectionManager
 void IdleConnectionTimeoutThread.addConnectionManager(HttpConnectionManager connectionManager)
          Adds a connection manager to be handled by this class.
protected  void IdleConnectionTimeoutThread.handleCloseIdleConnections(HttpConnectionManager connectionManager)
          Handles calling closeIdleConnections() and doing any other cleanup work on the given connection mangaer.
 void IdleConnectionTimeoutThread.removeConnectionManager(HttpConnectionManager connectionManager)
          Removes the connection manager from this class.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpConstants.html100644 0 0 13617 10661532627 30207 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpConstants (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpConstants

No usage of org.apache.commons.httpclient.HttpConstants



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 156 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpContentTooLargeException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpContentTooLargeExcep100644 0 0 14045 10661532627 31320 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpContentTooLargeException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpContentTooLargeException

No usage of org.apache.commons.httpclient.HttpContentTooLargeException



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpException.html100644 0 0 153520 10661532627 30207 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpException

Packages that use HttpException
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
 

Uses of HttpException in org.apache.commons.httpclient
 

Subclasses of HttpException in org.apache.commons.httpclient
 class CircularRedirectException
          Signals a circular redirect
 class HttpContentTooLargeException
          Signals that the response content was larger than anticipated.
 class HttpRecoverableException
          Deprecated. no longer used
 class InvalidRedirectLocationException
          Signals violation of HTTP specification caused by an invalid redirect location
 class ProtocolException
          Signals that an HTTP protocol violation has occurred.
 class RedirectException
          Signals violation of HTTP specification caused by an invalid redirect
 class URIException
          The URI parsing and escape encoding exception.
 

Methods in org.apache.commons.httpclient that throw HttpException
protected  void HttpMethodBase.addCookieRequestHeader(HttpState state, HttpConnection conn)
          Generates Cookie request headers for those cookies that match the given host, port and path.
protected  void ConnectMethod.addCookieRequestHeader(HttpState state, HttpConnection conn)
          This method does nothing.
protected  void HttpMethodBase.addHostRequestHeader(HttpState state, HttpConnection conn)
          Generates Host request header, as long as no Host request header already exists.
protected  void HttpMethodBase.addProxyConnectionHeader(HttpState state, HttpConnection conn)
          Generates Proxy-Connection: Keep-Alive request header when communicating via a proxy server.
protected  void HttpMethodBase.addRequestHeaders(HttpState state, HttpConnection conn)
          Generates all the required request headers to be submitted via the given connection.
protected  void ConnectMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
protected  void HttpMethodBase.addUserAgentRequestHeader(HttpState state, HttpConnection conn)
          Generates default User-Agent request header, as long as no User-Agent request header already exists.
 ProxyClient.ConnectResponse ProxyClient.connect()
          Creates a socket that is connected, via the HTTP CONNECT method, to a proxy.
 int HttpMethodBase.execute(HttpState state, HttpConnection conn)
          Executes this method using the specified HttpConnection and HttpState.
 int ConnectMethod.execute(HttpState state, HttpConnection conn)
          Execute this method and create a tunneled HttpConnection.
 int HttpMethod.execute(HttpState state, HttpConnection connection)
          Executes this method using the specified HttpConnection and HttpState.
 int HttpClient.executeMethod(HostConfiguration hostConfiguration, HttpMethod method)
          Executes the given HTTP method using custom host configuration.
 int HttpClient.executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state)
          Executes the given HTTP method using the given custom host configuration with the given custom HTTP state.
 int HttpClient.executeMethod(HttpMethod method)
          Executes the given HTTP method.
 HttpConnection MultiThreadedHttpConnectionManager.getConnection(HostConfiguration hostConfiguration, long timeout)
          Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
 HttpConnection HttpConnectionManager.getConnection(HostConfiguration hostConfiguration, long timeout)
          Deprecated. Use #getConnectionWithTimeout(HostConfiguration, long)
 HeaderElement[] Header.getValues()
          Deprecated. Use #getElements
static HeaderElement[] HeaderElement.parse(String headerValue)
          Deprecated. Use #parseElements(String).
static Header[] HttpParser.parseHeaders(InputStream is)
          Deprecated. use #parseHeaders(InputStream, String)
static Header[] HttpParser.parseHeaders(InputStream is, String charset)
          Parses headers from the given stream.
protected  void HttpMethodBase.readResponse(HttpState state, HttpConnection conn)
          Reads the response from the given connection.
protected  void HttpMethodBase.readResponseBody(HttpState state, HttpConnection conn)
          Read the response body from the given HttpConnection.
protected  void HttpMethodBase.readResponseHeaders(HttpState state, HttpConnection conn)
          Reads the response headers from the given connection.
protected  void HttpMethodBase.readStatusLine(HttpState state, HttpConnection conn)
          Read the status line from the given HttpConnection, setting my status code and status text.
protected  void HttpMethodBase.writeRequest(HttpState state, HttpConnection conn)
           Sends the request via the given connection.
protected  boolean HttpMethodBase.writeRequestBody(HttpState state, HttpConnection conn)
          Writes the request body to the given connection.
protected  void HttpMethodBase.writeRequestHeaders(HttpState state, HttpConnection conn)
          Writes the request headers to the given connection.
protected  void HttpMethodBase.writeRequestLine(HttpState state, HttpConnection conn)
          Writes the request line to the given connection.
protected  void ConnectMethod.writeRequestLine(HttpState state, HttpConnection conn)
          Special Connect request.
 

Constructors in org.apache.commons.httpclient that throw HttpException
StatusLine(String statusLine)
          Default constructor.
 

Uses of HttpException in org.apache.commons.httpclient.auth
 

Subclasses of HttpException in org.apache.commons.httpclient.auth
 class AuthChallengeException
          Signals a failure processing authentication challenge
 class AuthenticationException
          Signals a failure in authentication process
 class CredentialsNotAvailableException
          Authentication credentials required to respond to a authentication challenge are not available
 class InvalidCredentialsException
          Authentication credentials required to respond to a authentication challenge are invalid
 class MalformedChallengeException
          Signals that authentication challenge is in some way invalid or illegal in the given context
 

Uses of HttpException in org.apache.commons.httpclient.cookie
 

Subclasses of HttpException in org.apache.commons.httpclient.cookie
 class MalformedCookieException
          Signals that a cookie is in some way invalid or illegal in a given context
 

Uses of HttpException in org.apache.commons.httpclient.methods
 

Methods in org.apache.commons.httpclient.methods that throw HttpException
protected  void MultipartPostMethod.addContentLengthRequestHeader(HttpState state, HttpConnection conn)
          Deprecated. Adds a Content-Length request header, as long as no Content-Length request header already exists.
protected  void EntityEnclosingMethod.addContentLengthRequestHeader(HttpState state, HttpConnection conn)
          Generates Content-Length or Transfer-Encoding: Chunked request header, as long as no Content-Length request header already exists.
protected  void MultipartPostMethod.addContentTypeRequestHeader(HttpState state, HttpConnection conn)
          Deprecated. Adds a Content-Type request header.
protected  void MultipartPostMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Deprecated. Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
protected  void ExpectContinueMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Sets the Expect header if it has not already been set, in addition to the "standard" set of headers.
protected  void EntityEnclosingMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
protected  void HeadMethod.readResponseBody(HttpState state, HttpConnection conn)
          Overrides HttpMethodBase method to not read a response body, despite the presence of a Content-Length or Transfer-Encoding header.
protected  boolean MultipartPostMethod.writeRequestBody(HttpState state, HttpConnection conn)
          Deprecated. Writes the request body to the given connection.
protected  boolean EntityEnclosingMethod.writeRequestBody(HttpState state, HttpConnection conn)
          Writes the request body to the given connection.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpHost.html100644 0 0 23221 10661532627 27140 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpHost (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpHost

Packages that use HttpHost
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of HttpHost in org.apache.commons.httpclient
 

Subclasses of HttpHost in org.apache.commons.httpclient
 class ProxyHost
          Holds all of the variables needed to describe an HTTP connection to a proxy.
 

Methods in org.apache.commons.httpclient with parameters of type HttpHost
 void HostConfiguration.setHost(HttpHost host)
          Sets the given host
 

Constructors in org.apache.commons.httpclient with parameters of type HttpHost
HttpHost(HttpHost httphost)
          Copy constructor for HttpHost
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpMethod.html100644 0 0 110410 10661532627 27460 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.HttpMethod (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.HttpMethod

Packages that use HttpMethod
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient. 
 

Uses of HttpMethod in org.apache.commons.httpclient
 

Classes in org.apache.commons.httpclient that implement HttpMethod
 class ConnectMethod
          Establishes a tunneled HTTP connection via the CONNECT method.
 class HttpMethodBase
          An abstract base implementation of HttpMethod.
 

Methods in org.apache.commons.httpclient with parameters of type HttpMethod
 int HttpClient.executeMethod(HostConfiguration hostConfiguration, HttpMethod method)
          Executes the given HTTP method using custom host configuration.
 int HttpClient.executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state)
          Executes the given HTTP method using the given custom host configuration with the given custom HTTP state.
 int HttpClient.executeMethod(HttpMethod method)
          Executes the given HTTP method.
 boolean DefaultMethodRetryHandler.retryMethod(HttpMethod method, HttpConnection connection, HttpRecoverableException recoverableException, int executionCount, boolean requestSent)
          Deprecated. Used retryCount and requestSentRetryEnabled to determine if the given method should be retried.
 boolean MethodRetryHandler.retryMethod(HttpMethod method, HttpConnection connection, HttpRecoverableException recoverableException, int executionCount, boolean requestSent)
          Deprecated. Determines if a method should be retried after an HttpRecoverableException occurs during execution.
 boolean HttpMethodRetryHandler.retryMethod(HttpMethod method, IOException exception, int executionCount)
          Determines if a method should be retried after an HttpRecoverableException occurs during execution.
 boolean DefaultHttpMethodRetryHandler.retryMethod(HttpMethod method, IOException exception, int executionCount)
          Used retryCount and requestSentRetryEnabled to determine if the given method should be retried.
 

Constructors in org.apache.commons.httpclient with parameters of type HttpMethod
ChunkedInputStream(InputStream in, HttpMethod method)
          ChunkedInputStream constructor that associates the chunked input stream with a HTTP method.
ConnectMethod(HttpMethod method)
          Deprecated. the wrapped method is no longer used Create a connect method wrapping the existing method
 

Uses of HttpMethod in org.apache.commons.httpclient.auth
 

Methods in org.apache.commons.httpclient.auth with parameters of type HttpMethod
static boolean HttpAuthenticator.authenticate(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
 String NTLMScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces NTLM authorization string for the given set of Credentials.
 String DigestScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces a digest authorization string for the given set of Credentials, method name and URI.
 String BasicScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces basic authorization string for the given set of Credentials.
 String AuthScheme.authenticate(Credentials credentials, HttpMethod method)
          Produces an authorization string for the given set of Credentials.
static boolean HttpAuthenticator.authenticateDefault(HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean HttpAuthenticator.authenticateProxy(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean HttpAuthenticator.authenticateProxyDefault(HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
 

Uses of HttpMethod in org.apache.commons.httpclient.methods
 

Classes in org.apache.commons.httpclient.methods that implement HttpMethod
 class DeleteMethod
          Implements the HTTP DELETE method.
 class EntityEnclosingMethod
          This abstract class serves as a foundation for all HTTP methods that can enclose an entity within requests
 class ExpectContinueMethod
           This abstract class serves as a foundation for all HTTP methods that support 'Expect: 100-continue' handshake.
 class GetMethod
          Implements the HTTP GET method.
 class HeadMethod
          Implements the HTTP HEAD method.
 class MultipartPostMethod
          Deprecated. Use MultipartRequestEntity in conjunction with PostMethod instead.
 class OptionsMethod
          Implements the HTTP OPTIONS method.
 class PostMethod
          Implements the HTTP POST method.
 class PutMethod
          Implements the HTTP PUT method.
 class TraceMethod
          Implements the HTTP TRACE method.
 

Uses of HttpMethod in org.apache.commons.httpclient.util
 

Constructors in org.apache.commons.httpclient.util with parameters of type HttpMethod
HttpURLConnection(HttpMethod method, URL url)
          Creates an HttpURLConnection from a HttpMethod.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpMethodBase.html100644 0 0 33650 10661532627 30245 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpMethodBase (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpMethodBase

Packages that use HttpMethodBase
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
 

Uses of HttpMethodBase in org.apache.commons.httpclient
 

Subclasses of HttpMethodBase in org.apache.commons.httpclient
 class ConnectMethod
          Establishes a tunneled HTTP connection via the CONNECT method.
 

Uses of HttpMethodBase in org.apache.commons.httpclient.methods
 

Subclasses of HttpMethodBase in org.apache.commons.httpclient.methods
 class DeleteMethod
          Implements the HTTP DELETE method.
 class EntityEnclosingMethod
          This abstract class serves as a foundation for all HTTP methods that can enclose an entity within requests
 class ExpectContinueMethod
           This abstract class serves as a foundation for all HTTP methods that support 'Expect: 100-continue' handshake.
 class GetMethod
          Implements the HTTP GET method.
 class HeadMethod
          Implements the HTTP HEAD method.
 class MultipartPostMethod
          Deprecated. Use MultipartRequestEntity in conjunction with PostMethod instead.
 class OptionsMethod
          Implements the HTTP OPTIONS method.
 class PostMethod
          Implements the HTTP POST method.
 class PutMethod
          Implements the HTTP PUT method.
 class TraceMethod
          Implements the HTTP TRACE method.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpMethodRetryHandler.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpMethodRetryHandler.h100644 0 0 20437 10661532627 31260 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.HttpMethodRetryHandler (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.HttpMethodRetryHandler

Packages that use HttpMethodRetryHandler
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of HttpMethodRetryHandler in org.apache.commons.httpclient
 

Classes in org.apache.commons.httpclient that implement HttpMethodRetryHandler
 class DefaultHttpMethodRetryHandler
          The default HttpMethodRetryHandler used by HttpMethods.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpParser.html100644 0 0 13561 10661532627 27465 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpParser (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpParser

No usage of org.apache.commons.httpclient.HttpParser



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpRecoverableException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpRecoverableException100644 0 0 24037 10661532627 31376 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpRecoverableException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpRecoverableException

Packages that use HttpRecoverableException
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of HttpRecoverableException in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient with parameters of type HttpRecoverableException
 boolean DefaultMethodRetryHandler.retryMethod(HttpMethod method, HttpConnection connection, HttpRecoverableException recoverableException, int executionCount, boolean requestSent)
          Deprecated. Used retryCount and requestSentRetryEnabled to determine if the given method should be retried.
 boolean MethodRetryHandler.retryMethod(HttpMethod method, HttpConnection connection, HttpRecoverableException recoverableException, int executionCount, boolean requestSent)
          Deprecated. Determines if a method should be retried after an HttpRecoverableException occurs during execution.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpState.html100644 0 0 147236 10661532627 27340 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpState (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpState

Packages that use HttpState
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
 

Uses of HttpState in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return HttpState
 HttpState ProxyClient.getState()
          Returns HTTP state associated with the ProxyClient.
 HttpState HttpClient.getState()
          Returns HTTP state associated with the HttpClient.
 

Methods in org.apache.commons.httpclient with parameters of type HttpState
protected  void HttpMethodBase.addCookieRequestHeader(HttpState state, HttpConnection conn)
          Generates Cookie request headers for those cookies that match the given host, port and path.
protected  void ConnectMethod.addCookieRequestHeader(HttpState state, HttpConnection conn)
          This method does nothing.
protected  void HttpMethodBase.addHostRequestHeader(HttpState state, HttpConnection conn)
          Generates Host request header, as long as no Host request header already exists.
protected  void HttpMethodBase.addProxyConnectionHeader(HttpState state, HttpConnection conn)
          Generates Proxy-Connection: Keep-Alive request header when communicating via a proxy server.
protected  void HttpMethodBase.addRequestHeaders(HttpState state, HttpConnection conn)
          Generates all the required request headers to be submitted via the given connection.
protected  void ConnectMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
protected  void HttpMethodBase.addUserAgentRequestHeader(HttpState state, HttpConnection conn)
          Generates default User-Agent request header, as long as no User-Agent request header already exists.
 int HttpMethodBase.execute(HttpState state, HttpConnection conn)
          Executes this method using the specified HttpConnection and HttpState.
 int ConnectMethod.execute(HttpState state, HttpConnection conn)
          Execute this method and create a tunneled HttpConnection.
 int HttpMethod.execute(HttpState state, HttpConnection connection)
          Executes this method using the specified HttpConnection and HttpState.
 int HttpClient.executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state)
          Executes the given HTTP method using the given custom host configuration with the given custom HTTP state.
protected  void HttpMethodBase.processCookieHeaders(CookieSpec parser, Header[] headers, HttpState state, HttpConnection conn)
          This method processes the specified cookie headers.
protected  void HttpMethodBase.processResponseBody(HttpState state, HttpConnection conn)
          This method is invoked immediately after HttpMethodBase.readResponseBody(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom body processing.
protected  void HttpMethodBase.processResponseHeaders(HttpState state, HttpConnection conn)
          This method is invoked immediately after HttpMethodBase.readResponseHeaders(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom response headers processing.
protected  void HttpMethodBase.processStatusLine(HttpState state, HttpConnection conn)
          This method is invoked immediately after HttpMethodBase.readStatusLine(HttpState,HttpConnection) and can be overridden by sub-classes in order to provide custom response status line processing.
protected  void HttpMethodBase.readResponse(HttpState state, HttpConnection conn)
          Reads the response from the given connection.
protected  void HttpMethodBase.readResponseBody(HttpState state, HttpConnection conn)
          Read the response body from the given HttpConnection.
protected  void HttpMethodBase.readResponseHeaders(HttpState state, HttpConnection conn)
          Reads the response headers from the given connection.
protected  void HttpMethodBase.readStatusLine(HttpState state, HttpConnection conn)
          Read the status line from the given HttpConnection, setting my status code and status text.
 void ProxyClient.setState(HttpState state)
          Assigns HTTP state for the ProxyClient.
 void HttpClient.setState(HttpState state)
          Assigns HTTP state for the HttpClient.
protected  void HttpMethodBase.writeRequest(HttpState state, HttpConnection conn)
           Sends the request via the given connection.
protected  boolean HttpMethodBase.writeRequestBody(HttpState state, HttpConnection conn)
          Writes the request body to the given connection.
protected  void HttpMethodBase.writeRequestHeaders(HttpState state, HttpConnection conn)
          Writes the request headers to the given connection.
protected  void HttpMethodBase.writeRequestLine(HttpState state, HttpConnection conn)
          Writes the request line to the given connection.
protected  void ConnectMethod.writeRequestLine(HttpState state, HttpConnection conn)
          Special Connect request.
 

Uses of HttpState in org.apache.commons.httpclient.auth
 

Methods in org.apache.commons.httpclient.auth with parameters of type HttpState
static boolean HttpAuthenticator.authenticate(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean HttpAuthenticator.authenticateDefault(HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean HttpAuthenticator.authenticateProxy(AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
static boolean HttpAuthenticator.authenticateProxyDefault(HttpMethod method, HttpConnection conn, HttpState state)
          Deprecated. use AuthScheme
 

Uses of HttpState in org.apache.commons.httpclient.methods
 

Methods in org.apache.commons.httpclient.methods with parameters of type HttpState
protected  void MultipartPostMethod.addContentLengthRequestHeader(HttpState state, HttpConnection conn)
          Deprecated. Adds a Content-Length request header, as long as no Content-Length request header already exists.
protected  void EntityEnclosingMethod.addContentLengthRequestHeader(HttpState state, HttpConnection conn)
          Generates Content-Length or Transfer-Encoding: Chunked request header, as long as no Content-Length request header already exists.
protected  void MultipartPostMethod.addContentTypeRequestHeader(HttpState state, HttpConnection conn)
          Deprecated. Adds a Content-Type request header.
protected  void MultipartPostMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Deprecated. Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
protected  void ExpectContinueMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Sets the Expect header if it has not already been set, in addition to the "standard" set of headers.
protected  void EntityEnclosingMethod.addRequestHeaders(HttpState state, HttpConnection conn)
          Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
protected  void OptionsMethod.processResponseHeaders(HttpState state, HttpConnection conn)
           This implementation will parse the Allow header to obtain the set of methods supported by the resource identified by the Request-URI.
protected  void HeadMethod.readResponseBody(HttpState state, HttpConnection conn)
          Overrides HttpMethodBase method to not read a response body, despite the presence of a Content-Length or Transfer-Encoding header.
protected  boolean MultipartPostMethod.writeRequestBody(HttpState state, HttpConnection conn)
          Deprecated. Writes the request body to the given connection.
protected  boolean EntityEnclosingMethod.writeRequestBody(HttpState state, HttpConnection conn)
          Writes the request body to the given connection.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpStatus.html100644 0 0 13561 10661532627 27514 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpStatus (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpStatus

No usage of org.apache.commons.httpclient.HttpStatus



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpURL.html100644 0 0 22562 10661532627 26674 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpURL (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpURL

Packages that use HttpURL
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of HttpURL in org.apache.commons.httpclient
 

Subclasses of HttpURL in org.apache.commons.httpclient
 class HttpsURL
          The HTTPS URL.
 

Constructors in org.apache.commons.httpclient with parameters of type HttpURL
HttpURL(HttpURL base, HttpURL relative)
          Construct a HTTP URL with a given relative URL.
HttpURL(HttpURL base, String relative)
          Construct a HTTP URL with a given relative URL string.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpVersion.html100644 0 0 43017 10661532627 27655 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpVersion (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpVersion

Packages that use HttpVersion
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.params HttpClient preferences framework. 
 

Uses of HttpVersion in org.apache.commons.httpclient
 

Fields in org.apache.commons.httpclient declared as HttpVersion
protected  HttpVersion HttpMethodBase.effectiveVersion
          HTTP protocol version used for execution of this method.
static HttpVersion HttpVersion.HTTP_0_9
          HTTP protocol version 0.9
static HttpVersion HttpVersion.HTTP_1_0
          HTTP protocol version 1.0
static HttpVersion HttpVersion.HTTP_1_1
          HTTP protocol version 1.1
 

Methods in org.apache.commons.httpclient that return HttpVersion
 HttpVersion HttpMethodBase.getEffectiveVersion()
          Returns the HTTP version used with this method (may be null if undefined, that is, the method has not been executed)
static HttpVersion HttpVersion.parse(String s)
          Parses the textual representation of the given HTTP protocol version.
 

Methods in org.apache.commons.httpclient with parameters of type HttpVersion
 int HttpVersion.compareTo(HttpVersion anotherVer)
          Compares this HTTP protocol version with another one.
 boolean HttpVersion.equals(HttpVersion version)
          Test if the HTTP protocol version is equal to the given number.
 boolean HttpVersion.greaterEquals(HttpVersion version)
          Test if the HTTP protocol version is greater or equal to the given number.
 boolean HttpVersion.lessEquals(HttpVersion version)
          Test if the HTTP protocol version is less or equal to the given number.
 

Uses of HttpVersion in org.apache.commons.httpclient.params
 

Methods in org.apache.commons.httpclient.params that return HttpVersion
 HttpVersion HttpMethodParams.getVersion()
          Returns HTTP protocol version to be used by the HTTP methods that this collection of parameters applies to.
 

Methods in org.apache.commons.httpclient.params with parameters of type HttpVersion
 void HttpMethodParams.setVersion(HttpVersion version)
          Assigns the HTTP protocol version to be used by the HTTP methods that this collection of parameters applies to.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/HttpsURL.html100644 0 0 21131 10661532627 27046 0ustar 0 0 Uses of Class org.apache.commons.httpclient.HttpsURL (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.HttpsURL

Packages that use HttpsURL
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of HttpsURL in org.apache.commons.httpclient
 

Constructors in org.apache.commons.httpclient with parameters of type HttpsURL
HttpsURL(HttpsURL base, HttpsURL relative)
          Construct a HTTPS URL with a given relative URL.
HttpsURL(HttpsURL base, String relative)
          Construct a HTTPS URL with a given relative HTTPS URL string.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 162 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/InvalidRedirectLocationException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/InvalidRedirectLocationE100644 0 0 14115 10661532627 31270 0ustar 0 0 Uses of Class org.apache.commons.httpclient.InvalidRedirectLocationException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.InvalidRedirectLocationException

No usage of org.apache.commons.httpclient.InvalidRedirectLocationException



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/MethodRetryHandler.html100644 0 0 25071 10661532627 31134 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.MethodRetryHandler (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.MethodRetryHandler

Packages that use MethodRetryHandler
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of MethodRetryHandler in org.apache.commons.httpclient
 

Classes in org.apache.commons.httpclient that implement MethodRetryHandler
 class DefaultMethodRetryHandler
          Deprecated. use DefaultHttpMethodRetryHandler
 

Methods in org.apache.commons.httpclient that return MethodRetryHandler
 MethodRetryHandler HttpMethodBase.getMethodRetryHandler()
          Deprecated. use HttpMethodParams
 

Methods in org.apache.commons.httpclient with parameters of type MethodRetryHandler
 void HttpMethodBase.setMethodRetryHandler(MethodRetryHandler handler)
          Deprecated. use HttpMethodParams
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 164 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/MultiThreadedHttpConnectionManager.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/MultiThreadedHttpConnect100644 0 0 14141 10661532627 31326 0ustar 0 0 Uses of Class org.apache.commons.httpclient.MultiThreadedHttpConnectionManager (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.MultiThreadedHttpConnectionManager

No usage of org.apache.commons.httpclient.MultiThreadedHttpConnectionManager



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/NTCredentials.html100644 0 0 23615 10661532627 30071 0ustar 0 0 Uses of Class org.apache.commons.httpclient.NTCredentials (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.NTCredentials

Packages that use NTCredentials
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Uses of NTCredentials in org.apache.commons.httpclient.auth
 

Methods in org.apache.commons.httpclient.auth with parameters of type NTCredentials
static String NTLMScheme.authenticate(NTCredentials credentials, String challenge)
          Deprecated. Use non-static NTLMScheme.authenticate(Credentials, HttpMethod)
static String NTLMScheme.authenticate(NTCredentials credentials, String challenge, String charset)
          Deprecated. Use non-static NTLMScheme.authenticate(Credentials, HttpMethod)
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/NameValuePair.html100644 0 0 73344 10661532627 30067 0ustar 0 0 Uses of Class org.apache.commons.httpclient.NameValuePair (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.NameValuePair

Packages that use NameValuePair
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient. 
 

Uses of NameValuePair in org.apache.commons.httpclient
 

Subclasses of NameValuePair in org.apache.commons.httpclient
 class Cookie
           HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.
 class Header
          An HTTP header.
 class HeaderElement
          One element of an HTTP header's value.
 

Methods in org.apache.commons.httpclient that return NameValuePair
 NameValuePair HeaderElement.getParameterByName(String name)
          Returns parameter with the given name, if found.
 NameValuePair[] HeaderElement.getParameters()
          Get parameters, if any.
 

Methods in org.apache.commons.httpclient with parameters of type NameValuePair
 void HttpMethodBase.setQueryString(NameValuePair[] params)
          Sets the query string of this HTTP method.
 void HttpMethod.setQueryString(NameValuePair[] params)
          Sets the query string of this HTTP method.
 

Constructors in org.apache.commons.httpclient with parameters of type NameValuePair
HeaderElement(String name, String value, NameValuePair[] parameters)
          Constructor with name, value and parameters.
 

Uses of NameValuePair in org.apache.commons.httpclient.cookie
 

Subclasses of NameValuePair in org.apache.commons.httpclient.cookie
 class Cookie2
           Cookie class for RFC2965Spec cookie specification.
 

Methods in org.apache.commons.httpclient.cookie with parameters of type NameValuePair
 void RFC2965Spec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse RFC 2965 specific cookie attribute and update the corresponsing Cookie properties.
 void RFC2109Spec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse RFC 2109 specific cookie attribute and update the corresponsing Cookie properties.
 void NetscapeDraftSpec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties as defined by the Netscape draft specification
 void IgnoreCookiesSpec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Does nothing.
 void CookieSpecBase.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties.
 void CookieSpec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties.
 

Uses of NameValuePair in org.apache.commons.httpclient.methods
 

Methods in org.apache.commons.httpclient.methods that return NameValuePair
 NameValuePair PostMethod.getParameter(String paramName)
          Gets the parameter of the specified name.
 NameValuePair[] PostMethod.getParameters()
          Gets the parameters currently added to the PostMethod.
 

Methods in org.apache.commons.httpclient.methods with parameters of type NameValuePair
 void PostMethod.addParameter(NameValuePair param)
          Adds a new parameter to be used in the POST request body.
 void PostMethod.addParameters(NameValuePair[] parameters)
          Adds an array of parameters to be used in the POST request body.
 void PostMethod.setRequestBody(NameValuePair[] parametersBody)
          Sets an array of parameters to be used in the POST request body
 

Uses of NameValuePair in org.apache.commons.httpclient.util
 

Methods in org.apache.commons.httpclient.util with parameters of type NameValuePair
 String ParameterFormatter.format(NameValuePair param)
          Produces textual representaion of the attribute/value pair using formatting rules defined in RFC 2616
 void ParameterFormatter.format(StringBuffer buffer, NameValuePair param)
          Produces textual representaion of the attribute/value pair using formatting rules defined in RFC 2616
static String EncodingUtil.formUrlEncode(NameValuePair[] pairs, String charset)
          Form-urlencoding routine.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/NoHttpResponseException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/NoHttpResponseException.100644 0 0 13763 10661532627 31322 0ustar 0 0 Uses of Class org.apache.commons.httpclient.NoHttpResponseException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.NoHttpResponseException

No usage of org.apache.commons.httpclient.NoHttpResponseException



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ProtocolException.html100644 0 0 36725 10661532627 31060 0ustar 0 0 Uses of Class org.apache.commons.httpclient.ProtocolException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.ProtocolException

Packages that use ProtocolException
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
 

Uses of ProtocolException in org.apache.commons.httpclient
 

Subclasses of ProtocolException in org.apache.commons.httpclient
 class CircularRedirectException
          Signals a circular redirect
 class InvalidRedirectLocationException
          Signals violation of HTTP specification caused by an invalid redirect location
 class RedirectException
          Signals violation of HTTP specification caused by an invalid redirect
 

Methods in org.apache.commons.httpclient that throw ProtocolException
static HttpVersion HttpVersion.parse(String s)
          Parses the textual representation of the given HTTP protocol version.
 

Uses of ProtocolException in org.apache.commons.httpclient.auth
 

Subclasses of ProtocolException in org.apache.commons.httpclient.auth
 class AuthChallengeException
          Signals a failure processing authentication challenge
 class AuthenticationException
          Signals a failure in authentication process
 class CredentialsNotAvailableException
          Authentication credentials required to respond to a authentication challenge are not available
 class InvalidCredentialsException
          Authentication credentials required to respond to a authentication challenge are invalid
 class MalformedChallengeException
          Signals that authentication challenge is in some way invalid or illegal in the given context
 

Uses of ProtocolException in org.apache.commons.httpclient.cookie
 

Subclasses of ProtocolException in org.apache.commons.httpclient.cookie
 class MalformedCookieException
          Signals that a cookie is in some way invalid or illegal in a given context
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ProxyClient.ConnectResponse.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ProxyClient.ConnectRespo100644 0 0 20243 10661532627 31302 0ustar 0 0 Uses of Class org.apache.commons.httpclient.ProxyClient.ConnectResponse (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.ProxyClient.ConnectResponse

Packages that use ProxyClient.ConnectResponse
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of ProxyClient.ConnectResponse in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return ProxyClient.ConnectResponse
 ProxyClient.ConnectResponse ProxyClient.connect()
          Creates a socket that is connected, via the HTTP CONNECT method, to a proxy.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ProxyClient.html100644 0 0 13573 10661532627 27654 0ustar 0 0 Uses of Class org.apache.commons.httpclient.ProxyClient (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.ProxyClient

No usage of org.apache.commons.httpclient.ProxyClient



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/ProxyHost.html100644 0 0 21476 10661532627 27354 0ustar 0 0 Uses of Class org.apache.commons.httpclient.ProxyHost (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.ProxyHost

Packages that use ProxyHost
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of ProxyHost in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient with parameters of type ProxyHost
 void HostConfiguration.setProxyHost(ProxyHost proxyHost)
          Sets the given proxy host
 

Constructors in org.apache.commons.httpclient with parameters of type ProxyHost
ProxyHost(ProxyHost httpproxy)
          Copy constructor for HttpHost
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/RedirectException.html100644 0 0 20526 10661532627 31010 0ustar 0 0 Uses of Class org.apache.commons.httpclient.RedirectException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.RedirectException

Packages that use RedirectException
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of RedirectException in org.apache.commons.httpclient
 

Subclasses of RedirectException in org.apache.commons.httpclient
 class CircularRedirectException
          Signals a circular redirect
 class InvalidRedirectLocationException
          Signals violation of HTTP specification caused by an invalid redirect location
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/SimpleHttpConnectionManager.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/SimpleHttpConnectionMana100644 0 0 14033 10661532627 31327 0ustar 0 0 Uses of Class org.apache.commons.httpclient.SimpleHttpConnectionManager (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.SimpleHttpConnectionManager

No usage of org.apache.commons.httpclient.SimpleHttpConnectionManager



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/StatusLine.html100644 0 0 22705 10661532627 27464 0ustar 0 0 Uses of Class org.apache.commons.httpclient.StatusLine (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.StatusLine

Packages that use StatusLine
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of StatusLine in org.apache.commons.httpclient
 

Fields in org.apache.commons.httpclient declared as StatusLine
protected  StatusLine HttpMethodBase.statusLine
          The Status-Line from the response.
 

Methods in org.apache.commons.httpclient that return StatusLine
 StatusLine HttpMethodBase.getStatusLine()
          Provides access to the response status line.
 StatusLine HttpMethod.getStatusLine()
          Returns the Status-Line from the most recent response for this method, or null if the method has not been executed.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 153 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/URI.DefaultCharsetChanged.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/URI.DefaultCharsetChange100644 0 0 21253 10661532627 31065 0ustar 0 0 Uses of Class org.apache.commons.httpclient.URI.DefaultCharsetChanged (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.URI.DefaultCharsetChanged

Packages that use URI.DefaultCharsetChanged
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of URI.DefaultCharsetChanged in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that throw URI.DefaultCharsetChanged
static void URI.setDefaultDocumentCharset(String charset)
          Set the default charset of the document.
static void URI.setDefaultProtocolCharset(String charset)
          Set the default charset of the protocol.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/URI.LocaleToCharsetMap.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/URI.LocaleToCharsetMap.h100644 0 0 13751 10661532627 30765 0ustar 0 0 Uses of Class org.apache.commons.httpclient.URI.LocaleToCharsetMap (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.URI.LocaleToCharsetMap

No usage of org.apache.commons.httpclient.URI.LocaleToCharsetMap



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/URI.html100644 0 0 40365 10661532627 26032 0ustar 0 0 Uses of Class org.apache.commons.httpclient.URI (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.URI

Packages that use URI
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient. 
 

Uses of URI in org.apache.commons.httpclient
 

Subclasses of URI in org.apache.commons.httpclient
 class HttpsURL
          The HTTPS URL.
 class HttpURL
          The HTTP URL.
 

Methods in org.apache.commons.httpclient that return URI
 URI HttpMethodBase.getURI()
          Returns the URI of the HTTP method
 URI ConnectMethod.getURI()
           
 URI HttpMethod.getURI()
          Returns the URI for this method.
 

Methods in org.apache.commons.httpclient with parameters of type URI
 void HostConfiguration.setHost(URI uri)
          Sets the protocol, host and port from the given URI.
 void HttpMethodBase.setURI(URI uri)
          Sets the URI for this method.
 void HttpMethod.setURI(URI uri)
          Sets the URI for this method.
 

Constructors in org.apache.commons.httpclient with parameters of type URI
HttpHost(URI uri)
          URI constructor for HttpHost.
URI(URI base, String relative)
          Deprecated. Use #URI(URI, String, boolean)
URI(URI base, String relative, boolean escaped)
          Construct a general URI with the given relative URI string.
URI(URI base, URI relative)
          Construct a general URI with the given relative URI.
 

Uses of URI in org.apache.commons.httpclient.util
 

Subclasses of URI in org.apache.commons.httpclient.util
protected static class URIUtil.Coder
          Deprecated. use org.apache.commons.codec.net.URLCodec
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/URIException.html100644 0 0 276060 10661532627 27734 0ustar 0 0 Uses of Class org.apache.commons.httpclient.URIException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.URIException

Packages that use URIException
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient. 
 

Uses of URIException in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that throw URIException
protected  void HttpsURL.checkValid()
          Verify the valid class use for construction.
protected  void HttpURL.checkValid()
          Verify the valid class use for construction.
protected static String URI.decode(char[] component, String charset)
          Decodes URI encoded string.
protected static String URI.decode(String component, String charset)
          Decodes URI encoded string.
protected static char[] URI.encode(String original, BitSet allowed, String charset)
          Encodes URI string.
 String URI.getAboveHierPath()
          Get the level above the this hierarchy level.
 String URI.getAuthority()
          Get the authority.
 String URI.getCurrentHierPath()
          Get the current hierarchy level.
 String URI.getEscapedAboveHierPath()
          Get the level above the this hierarchy level.
 String URI.getEscapedCurrentHierPath()
          Get the escaped current hierarchy level.
 String URI.getFragment()
          Get the fragment.
 String URI.getHost()
          Get the host.
 String URI.getName()
          Get the basename of the path.
 String HttpURL.getPassword()
          Get the password.
 String URI.getPath()
          Get the path.
 String URI.getPathQuery()
          Get the path and query.
 String URI.getQuery()
          Get the query.
 char[] HttpURL.getRawAboveHierPath()
          Get the level above the this hierarchy level.
 char[] URI.getRawAboveHierPath()
          Get the level above the this hierarchy level.
 char[] HttpURL.getRawCurrentHierPath()
          Get the raw-escaped current hierarchy level.
 char[] URI.getRawCurrentHierPath()
          Get the raw-escaped current hierarchy level.
protected  char[] URI.getRawCurrentHierPath(char[] path)
          Get the raw-escaped current hierarchy level in the given path.
 URI HttpMethodBase.getURI()
          Returns the URI of the HTTP method
 URI ConnectMethod.getURI()
           
 String URI.getURI()
          It can be gotten the URI character sequence.
 URI HttpMethod.getURI()
          Returns the URI for this method.
 String URI.getURIReference()
          Get the original URI reference string.
 String HttpURL.getUser()
          Get the user.
 String URI.getUserinfo()
          Get the userinfo.
 void URI.normalize()
          Normalizes the path part of this URI.
protected  char[] URI.normalize(char[] path)
          Normalize the given hier path part.
protected  void URI.parseAuthority(String original, boolean escaped)
          Parse the authority component.
protected  void URI.parseUriReference(String original, boolean escaped)
          In order to avoid any possilbity of conflict with non-ASCII characters, Parse a URI reference as a String with the character encoding of the local system or the document.
protected  char[] URI.resolvePath(char[] basePath, char[] relPath)
          Resolve the base and relative path.
 void URI.setEscapedAuthority(String escapedAuthority)
          Set the authority.
 void URI.setEscapedFragment(String escapedFragment)
          Set the escaped fragment string.
 void HttpURL.setEscapedPassword(String escapedPassword)
          Set the escaped password string.
 void URI.setEscapedPath(String escapedPath)
          Set the escaped path.
 void URI.setEscapedQuery(String escapedQuery)
          Set the escaped query string.
 void HttpURL.setEscapedUser(String escapedUser)
          Set the escaped user string.
 void HttpURL.setEscapedUserinfo(String escapedUser, String escapedPassword)
          Set the raw-escaped user and password.
 void URI.setFragment(String fragment)
          Set the fragment.
 void HttpURL.setPassword(String password)
          Set the password string.
 void URI.setPath(String path)
          Set the path.
 void URI.setQuery(String query)
          Set the query.
 void HttpURL.setQuery(String[] queryName, String[] queryValue)
          Set the query as the name and value pairs.
 void HttpURL.setQuery(String queryName, String queryValue)
          Set the query as the name and value pair.
 void URI.setRawAuthority(char[] escapedAuthority)
          Set the authority.
 void URI.setRawFragment(char[] escapedFragment)
          Set the raw-escaped fragment.
 void HttpURL.setRawPassword(char[] escapedPassword)
          Set the raw-escaped password.
 void URI.setRawPath(char[] escapedPath)
          Set the raw-escaped path.
 void URI.setRawQuery(char[] escapedQuery)
          Set the raw-escaped query.
 void HttpURL.setRawUser(char[] escapedUser)
          Set the raw-escaped user.
 void HttpURL.setRawUserinfo(char[] escapedUser, char[] escapedPassword)
          Set the raw-escaped user and password.
 void HttpMethodBase.setURI(URI uri)
          Sets the URI for this method.
 void HttpMethod.setURI(URI uri)
          Sets the URI for this method.
 void HttpURL.setUser(String user)
          Set the user string.
 void HttpURL.setUserinfo(String user, String password)
          Set the user and password.
protected static String HttpURL.toUserinfo(String user, String password)
           
 

Constructors in org.apache.commons.httpclient that throw URIException
HttpHost(URI uri)
          URI constructor for HttpHost.
HttpsURL(char[] escaped)
          Construct a HTTPS URL as an escaped form of a character array.
HttpsURL(char[] escaped, String charset)
          Construct a HTTPS URL as an escaped form of a character array with the given charset to do escape encoding.
HttpsURL(HttpsURL base, HttpsURL relative)
          Construct a HTTPS URL with a given relative URL.
HttpsURL(HttpsURL base, String relative)
          Construct a HTTPS URL with a given relative HTTPS URL string.
HttpsURL(String original)
          Construct a HTTPS URL from a given string.
HttpsURL(String host, int port, String path)
          Construct a HTTPS URL from given components.
HttpsURL(String host, int port, String path, String query)
          Construct a HTTPS URL from given components.
HttpsURL(String original, String charset)
          Construct a HTTPS URL from a given string with the given charset to do escape encoding.
HttpsURL(String userinfo, String host, int port, String path)
          Construct a HTTPS URL from given components.
HttpsURL(String userinfo, String host, int port, String path, String query)
          Construct a HTTPS URL from given components.
HttpsURL(String userinfo, String host, int port, String path, String query, String fragment)
          Construct a HTTPS URL from given components.
HttpsURL(String user, String password, String host)
          Construct a HTTPS URL from given components.
HttpsURL(String user, String password, String host, int port)
          Construct a HTTPS URL from given components.
HttpsURL(String user, String password, String host, int port, String path)
          Construct a HTTPS URL from given components.
HttpsURL(String user, String password, String host, int port, String path, String query)
          Construct a HTTPS URL from given components.
HttpsURL(String user, String password, String host, int port, String path, String query, String fragment)
          Construct a HTTP URL from given components.
HttpsURL(String host, String path, String query, String fragment)
          Construct a HTTPS URL from given components.
HttpsURL(String userinfo, String host, String path, String query, String fragment)
          Construct a HTTPS URL from given components.
HttpURL(char[] escaped)
          Construct a HTTP URL as an escaped form of a character array.
HttpURL(char[] escaped, String charset)
          Construct a HTTP URL as an escaped form of a character array with the given charset to do escape encoding.
HttpURL(HttpURL base, HttpURL relative)
          Construct a HTTP URL with a given relative URL.
HttpURL(HttpURL base, String relative)
          Construct a HTTP URL with a given relative URL string.
HttpURL(String original)
          Construct a HTTP URL from a given string.
HttpURL(String host, int port, String path)
          Construct a HTTP URL from given components.
HttpURL(String host, int port, String path, String query)
          Construct a HTTP URL from given components.
HttpURL(String original, String charset)
          Construct a HTTP URL from a given string with the given charset to do escape encoding.
HttpURL(String userinfo, String host, int port, String path)
          Construct a HTTP URL from given components.
HttpURL(String userinfo, String host, int port, String path, String query)
          Construct a HTTP URL from given components.
HttpURL(String userinfo, String host, int port, String path, String query, String fragment)
          Construct a HTTP URL from given components.
HttpURL(String user, String password, String host)
          Construct a HTTP URL from given components.
HttpURL(String user, String password, String host, int port)
          Construct a HTTP URL from given components.
HttpURL(String user, String password, String host, int port, String path)
          Construct a HTTP URL from given components.
HttpURL(String user, String password, String host, int port, String path, String query)
          Construct a HTTP URL from given components.
HttpURL(String user, String password, String host, int port, String path, String query, String fragment)
          Construct a HTTP URL from given components.
HttpURL(String host, String path, String query, String fragment)
          Construct a HTTP URL from given components.
HttpURL(String userinfo, String host, String path, String query, String fragment)
          Construct a HTTP URL from given components.
URI(char[] escaped)
          Deprecated. Use #URI(String, boolean)
URI(char[] escaped, String charset)
          Deprecated. Use #URI(String, boolean, String)
URI(String original)
          Deprecated. Use #URI(String, boolean)
URI(String s, boolean escaped)
          Construct a URI from a string with the given charset.
URI(String s, boolean escaped, String charset)
          Construct a URI from a string with the given charset.
URI(String original, String charset)
          Deprecated. Use #URI(String, boolean, String)
URI(String scheme, String schemeSpecificPart, String fragment)
          Construct a general URI from the given components.
URI(String scheme, String userinfo, String host, int port)
          Construct a general URI from the given components.
URI(String scheme, String userinfo, String host, int port, String path)
          Construct a general URI from the given components.
URI(String scheme, String userinfo, String host, int port, String path, String query)
          Construct a general URI from the given components.
URI(String scheme, String userinfo, String host, int port, String path, String query, String fragment)
          Construct a general URI from the given components.
URI(String scheme, String host, String path, String fragment)
          Construct a general URI from the given components.
URI(String scheme, String authority, String path, String query, String fragment)
          Construct a general URI from the given components.
URI(URI base, String relative)
          Deprecated. Use #URI(URI, String, boolean)
URI(URI base, String relative, boolean escaped)
          Construct a general URI with the given relative URI string.
URI(URI base, URI relative)
          Construct a general URI with the given relative URI.
 

Uses of URIException in org.apache.commons.httpclient.util
 

Methods in org.apache.commons.httpclient.util that throw URIException
static String URIUtil.Coder.decode(char[] escapedComponent, String charset)
          Deprecated. use org.apache.commons.codec.net.URLCodec
static String URIUtil.decode(String escaped)
          Unescape and decode a given string regarded as an escaped string with the default protocol charset.
static String URIUtil.decode(String escaped, String charset)
          Unescape and decode a given string regarded as an escaped string.
static String URIUtil.encode(String unescaped, BitSet allowed)
          Escape and encode a given string with allowed characters not to be escaped and the default protocol charset.
static String URIUtil.encode(String unescaped, BitSet allowed, String charset)
          Escape and encode a given string with allowed characters not to be escaped and a given charset.
static char[] URIUtil.Coder.encode(String unescapedComponent, BitSet allowed, String charset)
          Deprecated. use org.apache.commons.codec.net.URLCodec
static String URIUtil.encodeAll(String unescaped)
          Get the all escaped and encoded string with the default protocl charset.
static String URIUtil.encodeAll(String unescaped, String charset)
          Get the all escaped and encoded string with a given charset.
static String URIUtil.encodePath(String unescaped)
          Escape and encode a string regarded as the path component of an URI with the default protocol charset.
static String URIUtil.encodePath(String unescaped, String charset)
          Escape and encode a string regarded as the path component of an URI with a given charset.
static String URIUtil.encodePathQuery(String unescaped)
          Escape and encode a string regarded as the path and query components of an URI with the default protocol charset.
static String URIUtil.encodePathQuery(String unescaped, String charset)
          Escape and encode a string regarded as the path and query components of an URI with a given charset.
static String URIUtil.encodeQuery(String unescaped)
          Escape and encode a string regarded as the query component of an URI with the default protocol charset.
static String URIUtil.encodeQuery(String unescaped, String charset)
          Escape and encode a string regarded as the query component of an URI with a given charset.
static String URIUtil.encodeWithinAuthority(String unescaped)
          Escape and encode a string regarded as within the authority component of an URI with the default protocol charset.
static String URIUtil.encodeWithinAuthority(String unescaped, String charset)
          Escape and encode a string regarded as within the authority component of an URI with a given charset.
static String URIUtil.encodeWithinPath(String unescaped)
          Escape and encode a string regarded as within the path component of an URI with the default protocol charset.
static String URIUtil.encodeWithinPath(String unescaped, String charset)
          Escape and encode a string regarded as within the path component of an URI with a given charset.
static String URIUtil.encodeWithinQuery(String unescaped)
          Escape and encode a string regarded as within the query component of an URI with the default protocol charset.
static String URIUtil.encodeWithinQuery(String unescaped, String charset)
          Escape and encode a string regarded as within the query component of an URI with a given charset.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/UsernamePasswordCredentials.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/class-use/UsernamePasswordCredenti100644 0 0 27631 10661532627 31411 0ustar 0 0 Uses of Class org.apache.commons.httpclient.UsernamePasswordCredentials (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.UsernamePasswordCredentials

Packages that use UsernamePasswordCredentials
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
 

Uses of UsernamePasswordCredentials in org.apache.commons.httpclient
 

Subclasses of UsernamePasswordCredentials in org.apache.commons.httpclient
 class NTCredentials
          Credentials for use with the NTLM authentication scheme which requires additional information.
 

Uses of UsernamePasswordCredentials in org.apache.commons.httpclient.auth
 

Methods in org.apache.commons.httpclient.auth with parameters of type UsernamePasswordCredentials
static String BasicScheme.authenticate(UsernamePasswordCredentials credentials)
          Deprecated. Use BasicScheme.authenticate(UsernamePasswordCredentials, String) Returns a basic Authorization header value for the given UsernamePasswordCredentials.
static String BasicScheme.authenticate(UsernamePasswordCredentials credentials, String charset)
          Returns a basic Authorization header value for the given UsernamePasswordCredentials and charset.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/Cookie2.html100644 0 0 132026 10661532627 26254 0ustar 0 0 Cookie2 (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Class Cookie2

java.lang.Object
  extended by org.apache.commons.httpclient.NameValuePair
      extended by org.apache.commons.httpclient.Cookie
          extended by org.apache.commons.httpclient.cookie.Cookie2
All Implemented Interfaces:
Serializable, Comparator

public class Cookie2
extends Cookie

Cookie class for RFC2965Spec cookie specification. It extends Cookie class and adds newer cookie attributes and functions required for this specification.

Since:
3.1
Author:
Samit Jain (jain.samit@gmail.com)
See Also:
Serialized Form

Field Summary
static String COMMENT
           
static String COMMENTURL
           
static String DISCARD
           
static String DOMAIN
           
static String MAXAGE
           
static String PATH
           
static String PORT
           
static String SECURE
           
static String VERSION
           
 
Constructor Summary
Cookie2()
          Default constructor.
Cookie2(String domain, String name, String value)
          Creates a cookie with the given name, value and domain attribute.
Cookie2(String domain, String name, String value, String path, Date expires, boolean secure)
          Creates a cookie with the given name, value, domain attribute, path attribute, expiration attribute, and secure attribute
Cookie2(String domain, String name, String value, String path, Date expires, boolean secure, int[] ports)
          Creates a cookie with the given name, value, domain attribute, path attribute, expiration attribute, secure attribute, and ports attribute.
 
Method Summary
 String getCommentURL()
          If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL.
 int[] getPorts()
          Get the Port attribute.
 boolean isPersistent()
          Returns false if the cookie should be discarded at the end of the "session"; true otherwise.
 boolean isPortAttributeBlank()
           
 boolean isPortAttributeSpecified()
           
 boolean isVersionAttributeSpecified()
           
 void setCommentURL(String commentURL)
          If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL.
 void setDiscard(boolean toDiscard)
          Set the Discard attribute.
 void setPortAttributeBlank(boolean value)
          Indicates whether the Port attribute in Set-Cookie2 header contains no value (is of the form Port="").
 void setPortAttributeSpecified(boolean value)
          Indicates whether the cookie had a port attribute specified in the Set-Cookie2 response header.
 void setPorts(int[] ports)
          Set the Port attribute.
 void setVersionAttributeSpecified(boolean value)
          Indicates whether the cookie had a version attribute specified in the Set-Cookie2 response header.
 String toExternalForm()
          Return a textual representation of the cookie.
 
Methods inherited from class org.apache.commons.httpclient.Cookie
compare, equals, getComment, getDomain, getExpiryDate, getPath, getSecure, getVersion, hashCode, isDomainAttributeSpecified, isExpired, isExpired, isPathAttributeSpecified, setComment, setDomain, setDomainAttributeSpecified, setExpiryDate, setPath, setPathAttributeSpecified, setSecure, setVersion, toString
 
Methods inherited from class org.apache.commons.httpclient.NameValuePair
getName, getValue, setName, setValue
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

DOMAIN

public static final String DOMAIN
See Also:
Constant Field Values

PATH

public static final String PATH
See Also:
Constant Field Values

PORT

public static final String PORT
See Also:
Constant Field Values

VERSION

public static final String VERSION
See Also:
Constant Field Values

SECURE

public static final String SECURE
See Also:
Constant Field Values

MAXAGE

public static final String MAXAGE
See Also:
Constant Field Values

COMMENT

public static final String COMMENT
See Also:
Constant Field Values

COMMENTURL

public static final String COMMENTURL
See Also:
Constant Field Values

DISCARD

public static final String DISCARD
See Also:
Constant Field Values
Constructor Detail

Cookie2

public Cookie2()
Default constructor. Creates a blank cookie


Cookie2

public Cookie2(String domain,
               String name,
               String value)
Creates a cookie with the given name, value and domain attribute.

Parameters:
name - the cookie name
value - the cookie value
domain - the domain this cookie can be sent to

Cookie2

public Cookie2(String domain,
               String name,
               String value,
               String path,
               Date expires,
               boolean secure)
Creates a cookie with the given name, value, domain attribute, path attribute, expiration attribute, and secure attribute

Parameters:
name - the cookie name
value - the cookie value
domain - the domain this cookie can be sent to
path - the path prefix for which this cookie can be sent
expires - the Date at which this cookie expires, or null if the cookie expires at the end of the session
secure - if true this cookie can only be sent over secure connections
Throws:
IllegalArgumentException - If cookie name is null or blank, cookie name contains a blank, or cookie name starts with character $

Cookie2

public Cookie2(String domain,
               String name,
               String value,
               String path,
               Date expires,
               boolean secure,
               int[] ports)
Creates a cookie with the given name, value, domain attribute, path attribute, expiration attribute, secure attribute, and ports attribute.

Parameters:
name - the cookie name
value - the cookie value
domain - the domain this cookie can be sent to
path - the path prefix for which this cookie can be sent
expires - the Date at which this cookie expires, or null if the cookie expires at the end of the session
secure - if true this cookie can only be sent over secure connections
ports - the ports for which this cookie can be sent
Throws:
IllegalArgumentException - If cookie name is null or blank, cookie name contains a blank, or cookie name starts with character $
Method Detail

getCommentURL

public String getCommentURL()
If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL.

See Also:
setCommentURL(String)

setCommentURL

public void setCommentURL(String commentURL)
If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL.

Parameters:
commentURL -
See Also:
getCommentURL()

getPorts

public int[] getPorts()
Get the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header.

See Also:
setPorts(int[])

setPorts

public void setPorts(int[] ports)
Set the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header.

Parameters:
ports -
See Also:
getPorts()

setDiscard

public void setDiscard(boolean toDiscard)
Set the Discard attribute. Note: Discard attribute overrides Max-age.

See Also:
isPersistent()

isPersistent

public boolean isPersistent()
Returns false if the cookie should be discarded at the end of the "session"; true otherwise.

Overrides:
isPersistent in class Cookie
Returns:
false if the cookie should be discarded at the end of the "session"; true otherwise

setPortAttributeSpecified

public void setPortAttributeSpecified(boolean value)
Indicates whether the cookie had a port attribute specified in the Set-Cookie2 response header.

Parameters:
value - true if port attribute is specified in response header.
See Also:
isPortAttributeSpecified()

isPortAttributeSpecified

public boolean isPortAttributeSpecified()
Returns:
true if cookie port attribute was specified in the Set-Cookie2 header.
See Also:
setPortAttributeSpecified(boolean)

setPortAttributeBlank

public void setPortAttributeBlank(boolean value)
Indicates whether the Port attribute in Set-Cookie2 header contains no value (is of the form Port="").

This value is required for generating the Cookie request header because the specification requires that if Set-Cookie2 header contains a blank value for port attribute, the Cookie header should also contain a port attribute with no value.

Parameters:
value - true if port attribute is specified as blank in response header.
See Also:
isPortAttributeBlank

isPortAttributeBlank

public boolean isPortAttributeBlank()
Returns:
true if the port attribute in Set-Cookie2 header had no value (was of the form Port="").
See Also:
setPortAttributeBlank(boolean)

setVersionAttributeSpecified

public void setVersionAttributeSpecified(boolean value)
Indicates whether the cookie had a version attribute specified in the Set-Cookie2 response header.

Parameters:
value - true if version attribute is specified in response header.
See Also:
isVersionAttributeSpecified()

isVersionAttributeSpecified

public boolean isVersionAttributeSpecified()
Returns:
true if cookie version attribute was specified in the Set-Cookie2 header.
See Also:
setVersionAttributeSpecified(boolean)

toExternalForm

public String toExternalForm()
Return a textual representation of the cookie.

Overrides:
toExternalForm in class Cookie
Returns:
string.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/CookieAttributeHandler.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/CookieAttributeHandler.html100644 0 0 34455 10661532627 31343 0ustar 0 0 CookieAttributeHandler (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Interface CookieAttributeHandler


public interface CookieAttributeHandler

Ths interface represents a cookie attribute handler responsible for parsing, validating, and matching a specific cookie attribute, such as path, domain, port, etc. Different cookie specifications can provide a specific implementation for this class based on their cookie handling rules.

Since:
3.1
Author:
jain.samit@gmail.com (Samit Jain)

Method Summary
 boolean match(Cookie cookie, CookieOrigin origin)
          Matches the given value (property of the destination host where request is being submitted) with the corresponding cookie attribute.
 void parse(Cookie cookie, String value)
          Parse the given cookie attribute value and update the corresponding Cookie property.
 void validate(Cookie cookie, CookieOrigin origin)
          Peforms cookie validation for the given attribute value.
 

Method Detail

parse

void parse(Cookie cookie,
           String value)
           throws MalformedCookieException
Parse the given cookie attribute value and update the corresponding Cookie property.

Parameters:
cookie - Cookie to be updated
value - cookie attribute value from the cookie response header
Throws:
MalformedCookieException

validate

void validate(Cookie cookie,
              CookieOrigin origin)
              throws MalformedCookieException
Peforms cookie validation for the given attribute value.

Parameters:
cookie - Cookie to validate
origin - the cookie source to validate against
Throws:
MalformedCookieException - if cookie validation fails for this attribute

match

boolean match(Cookie cookie,
              CookieOrigin origin)
Matches the given value (property of the destination host where request is being submitted) with the corresponding cookie attribute.

Parameters:
cookie - Cookie to match
origin - the cookie source to match against
Returns:
true if the match is successful; false otherwise


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/CookieOrigin.html100644 0 0 35076 10661532627 27331 0ustar 0 0 CookieOrigin (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Class CookieOrigin

java.lang.Object
  extended by org.apache.commons.httpclient.cookie.CookieOrigin

public final class CookieOrigin
extends Object

CookieOrigin class incapsulates details of an origin server that are relevant when parsing, validating or matching HTTP cookies.

Since:
3.1
Author:
Oleg Kalnichevski

Constructor Summary
CookieOrigin(String host, int port, String path, boolean secure)
           
 
Method Summary
 String getHost()
           
 String getPath()
           
 int getPort()
           
 boolean isSecure()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

CookieOrigin

public CookieOrigin(String host,
                    int port,
                    String path,
                    boolean secure)
Method Detail

getHost

public String getHost()

getPath

public String getPath()

getPort

public int getPort()

isSecure

public boolean isSecure()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/CookiePathComparator.html100644 0 0 34246 10661532627 31024 0ustar 0 0 CookiePathComparator (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Class CookiePathComparator

java.lang.Object
  extended by org.apache.commons.httpclient.cookie.CookiePathComparator
All Implemented Interfaces:
Comparator

public class CookiePathComparator
extends Object
implements Comparator

This cookie comparator ensures that multiple cookies satisfying a common criteria are ordered in the Cookie header such that those with more specific Path attributes precede those with less specific.

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

Since:
3.1
Author:
Oleg Kalnichevski

Constructor Summary
CookiePathComparator()
           
 
Method Summary
 int compare(Object o1, Object o2)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface java.util.Comparator
equals
 

Constructor Detail

CookiePathComparator

public CookiePathComparator()
Method Detail

compare

public int compare(Object o1,
                   Object o2)
Specified by:
compare in interface Comparator


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/CookiePolicy.html100644 0 0 117504 10661532627 27356 0ustar 0 0 CookiePolicy (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Class CookiePolicy

java.lang.Object
  extended by org.apache.commons.httpclient.cookie.CookiePolicy

public abstract class CookiePolicy
extends Object

Cookie management policy class. The cookie policy provides corresponding cookie management interfrace for a given type or version of cookie.

RFC 2109 specification is used per default. Other supported specification can be chosen when appropriate or set default when desired

The following specifications are provided:

  • BROWSER_COMPATIBILITY: compatible with the common cookie management practices (even if they are not 100% standards compliant)
  • NETSCAPE: Netscape cookie draft compliant
  • RFC_2109: RFC2109 compliant (default)
  • IGNORE_COOKIES: do not automcatically process cookies

Since:
2.0
Author:
Oleg Kalnichevski, Mike Bowler

Field Summary
static String BROWSER_COMPATIBILITY
          The policy that provides high degree of compatibilty with common cookie management of popular HTTP agents.
static int COMPATIBILITY
          Deprecated. Use BROWSER_COMPATIBILITY
static String DEFAULT
          The default cookie policy.
static String IGNORE_COOKIES
          The policy that ignores cookies.
protected static Log LOG
          Log object.
static String NETSCAPE
          The Netscape cookie draft compliant policy.
static int NETSCAPE_DRAFT
          Deprecated. Use NETSCAPE
static String RFC_2109
          The RFC 2109 compliant policy.
static String RFC_2965
          The RFC 2965 compliant policy.
static int RFC2109
          Deprecated. Use RFC_2109
static int RFC2965
          Deprecated. Use RFC_2965
 
Constructor Summary
CookiePolicy()
           
 
Method Summary
static CookieSpec getCompatibilitySpec()
          Deprecated. Use getCookieSpec(String)
static CookieSpec getCookieSpec(String id)
          Gets the cookie specification with the given ID.
static int getDefaultPolicy()
          Deprecated. Use getDefaultSpec()
static CookieSpec getDefaultSpec()
          Returns cookie specification registered as DEFAULT.
static String[] getRegisteredCookieSpecs()
          Obtains the currently registered cookie policy names.
static CookieSpec getSpecByPolicy(int policy)
          Deprecated. Use getCookieSpec(String)
static CookieSpec getSpecByVersion(int ver)
          Deprecated. Use getCookieSpec(String)
static void registerCookieSpec(String id, Class clazz)
          Registers a new cookie specification with the given identifier.
static void setDefaultPolicy(int policy)
          Deprecated. Use registerCookieSpec(String, Class)
static void unregisterCookieSpec(String id)
          Unregisters the cookie specification with the given ID.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

BROWSER_COMPATIBILITY

public static final String BROWSER_COMPATIBILITY
The policy that provides high degree of compatibilty with common cookie management of popular HTTP agents.

Since:
3.0
See Also:
Constant Field Values

NETSCAPE

public static final String NETSCAPE
The Netscape cookie draft compliant policy.

Since:
3.0
See Also:
Constant Field Values

RFC_2109

public static final String RFC_2109
The RFC 2109 compliant policy.

Since:
3.0
See Also:
Constant Field Values

RFC_2965

public static final String RFC_2965
The RFC 2965 compliant policy.

Since:
3.0
See Also:
Constant Field Values

IGNORE_COOKIES

public static final String IGNORE_COOKIES
The policy that ignores cookies.

Since:
3.0
See Also:
Constant Field Values

DEFAULT

public static final String DEFAULT
The default cookie policy.

Since:
3.0
See Also:
Constant Field Values

COMPATIBILITY

public static final int COMPATIBILITY
Deprecated. Use BROWSER_COMPATIBILITY
The COMPATIBILITY policy provides high compatibilty with common cookie management of popular HTTP agents.

See Also:
Constant Field Values

NETSCAPE_DRAFT

public static final int NETSCAPE_DRAFT
Deprecated. Use NETSCAPE
The NETSCAPE_DRAFT Netscape draft compliant policy.

See Also:
Constant Field Values

RFC2109

public static final int RFC2109
Deprecated. Use RFC_2109
The RFC2109 RFC 2109 compliant policy.

See Also:
Constant Field Values

RFC2965

public static final int RFC2965
Deprecated. Use RFC_2965
The RFC2965 RFC 2965 compliant policy.

See Also:
Constant Field Values

LOG

protected static final Log LOG
Log object.

Constructor Detail

CookiePolicy

public CookiePolicy()
Method Detail

registerCookieSpec

public static void registerCookieSpec(String id,
                                      Class clazz)
Registers a new cookie specification with the given identifier. If a specification with the given ID already exists it will be overridden. This ID is the same one used to retrieve the cookie specification from getCookieSpec(String).

Parameters:
id - the identifier for this specification
clazz - the cookie specification class to register
Since:
3.0
See Also:
getCookieSpec(String)

unregisterCookieSpec

public static void unregisterCookieSpec(String id)
Unregisters the cookie specification with the given ID.

Parameters:
id - the ID of the cookie specification to unregister
Since:
3.0

getCookieSpec

public static CookieSpec getCookieSpec(String id)
                                throws IllegalStateException
Gets the cookie specification with the given ID.

Parameters:
id - the cookie specification ID
Returns:
cookie specification
Throws:
IllegalStateException - if a policy with the ID cannot be found
Since:
3.0

getDefaultPolicy

public static int getDefaultPolicy()
Deprecated. Use getDefaultSpec()

Returns:
default cookie policy
See Also:
getDefaultSpec()

setDefaultPolicy

public static void setDefaultPolicy(int policy)
Deprecated. Use registerCookieSpec(String, Class)

Parameters:
policy - new default cookie policy
See Also:
DEFAULT

getSpecByPolicy

public static CookieSpec getSpecByPolicy(int policy)
Deprecated. Use getCookieSpec(String)

Parameters:
policy - cookie policy to get the CookieSpec for
Returns:
cookie specification interface for the given policy

getDefaultSpec

public static CookieSpec getDefaultSpec()
Returns cookie specification registered as DEFAULT. If no default cookie specification has been registered, RFC2109 specification is returned.

Returns:
default cookie specification
See Also:
DEFAULT

getSpecByVersion

public static CookieSpec getSpecByVersion(int ver)
Deprecated. Use getCookieSpec(String)

Gets the CookieSpec for a particular cookie version.

Supported versions:

  • version 0 corresponds to the Netscape draft
  • version 1 corresponds to the RFC 2109
  • Any other cookie value coresponds to the default spec

      Parameters:
      ver - the cookie version to get the spec for
      Returns:
      cookie specification interface intended for processing cookies with the given version

getCompatibilitySpec

public static CookieSpec getCompatibilitySpec()
Deprecated. Use getCookieSpec(String)

Returns:
cookie specification interface that provides high compatibilty with common cookie management of popular HTTP agents

getRegisteredCookieSpecs

public static String[] getRegisteredCookieSpecs()
Obtains the currently registered cookie policy names. Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.

Returns:
array of registered cookie policy names
Since:
3.1


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/CookieSpec.html100644 0 0 122310 10661532627 27000 0ustar 0 0 CookieSpec (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Interface CookieSpec

All Known Implementing Classes:
CookieSpecBase, IgnoreCookiesSpec, NetscapeDraftSpec, RFC2109Spec, RFC2965Spec

public interface CookieSpec

Defines the cookie management specification.

Cookie management specification must define

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

Since:
2.0
Author:
Oleg Kalnichevski, Jeff Dever

Field Summary
static String PATH_DELIM
          Path delimiter
static char PATH_DELIM_CHAR
          Path delimiting charachter
 
Method Summary
 boolean domainMatch(String host, String domain)
          Performs domain-match as defined by the cookie specification.
 String formatCookie(Cookie cookie)
          Create a "Cookie" header value for an array of cookies.
 Header formatCookieHeader(Cookie cookie)
          Create a "Cookie" Header for single Cookie.
 Header formatCookieHeader(Cookie[] cookies)
          Create a "Cookie" Header for an array of Cookies.
 String formatCookies(Cookie[] cookies)
          Create a "Cookie" header value for an array of cookies.
 Collection getValidDateFormats()
          Returns the Collection of date patterns used for parsing.
 boolean match(String host, int port, String path, boolean secure, Cookie cookie)
          Determines if a Cookie matches a location.
 Cookie[] match(String host, int port, String path, boolean secure, Cookie[] cookies)
          Determines which of an array of Cookies matches a location.
 Cookie[] parse(String host, int port, String path, boolean secure, Header header)
          Parse the "Set-Cookie" Header into an array of Cookies.
 Cookie[] parse(String host, int port, String path, boolean secure, String header)
          Parse the "Set-Cookie" header value into Cookie array.
 void parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties.
 boolean pathMatch(String path, String topmostPath)
          Performs path-match as defined by the cookie specification.
 void setValidDateFormats(Collection datepatterns)
          Sets the Collection of date patterns used for parsing.
 void validate(String host, int port, String path, boolean secure, Cookie cookie)
          Validate the cookie according to validation rules defined by the cookie specification.
 

Field Detail

PATH_DELIM

static final String PATH_DELIM
Path delimiter

See Also:
Constant Field Values

PATH_DELIM_CHAR

static final char PATH_DELIM_CHAR
Path delimiting charachter

Method Detail

parse

Cookie[] parse(String host,
               int port,
               String path,
               boolean secure,
               String header)
               throws MalformedCookieException,
                      IllegalArgumentException
Parse the "Set-Cookie" header value into Cookie array.

This method will not perform the validation of the resultant Cookies

Parameters:
host - the host which sent the Set-Cookie header
port - the port which sent the Set-Cookie header
path - the path which sent the Set-Cookie header
secure - true when the Set-Cookie header was received over secure conection
header - the Set-Cookie received from the server
Returns:
an array of Cookies parsed from the Set-Cookie value
Throws:
MalformedCookieException - if an exception occurs during parsing
IllegalArgumentException - if an input parameter is illegal
See Also:
validate(String, int, String, boolean, Cookie)

parse

Cookie[] parse(String host,
               int port,
               String path,
               boolean secure,
               Header header)
               throws MalformedCookieException,
                      IllegalArgumentException
Parse the "Set-Cookie" Header into an array of Cookies.

This method will not perform the validation of the resultant Cookies

Parameters:
host - the host which sent the Set-Cookie header
port - the port which sent the Set-Cookie header
path - the path which sent the Set-Cookie header
secure - true when the Set-Cookie header was received over secure conection
header - the Set-Cookie received from the server
Returns:
an array of Cookies parsed from the header
Throws:
MalformedCookieException - if an exception occurs during parsing
IllegalArgumentException - if an input parameter is illegal
See Also:
validate(String, int, String, boolean, Cookie)

parseAttribute

void parseAttribute(NameValuePair attribute,
                    Cookie cookie)
                    throws MalformedCookieException,
                           IllegalArgumentException
Parse the cookie attribute and update the corresponsing Cookie properties.

Parameters:
attribute - cookie attribute from the Set-Cookie
cookie - the to be updated
Throws:
MalformedCookieException - if an exception occurs during parsing
IllegalArgumentException - if an input parameter is illegal

validate

void validate(String host,
              int port,
              String path,
              boolean secure,
              Cookie cookie)
              throws MalformedCookieException,
                     IllegalArgumentException
Validate the cookie according to validation rules defined by the cookie specification.

Parameters:
host - the host from which the Cookie was received
port - the port from which the Cookie was received
path - the path from which the Cookie was received
secure - true when the Cookie was received using a secure connection
cookie - the Cookie to validate
Throws:
MalformedCookieException - if the cookie is invalid
IllegalArgumentException - if an input parameter is illegal

setValidDateFormats

void setValidDateFormats(Collection datepatterns)
Sets the Collection of date patterns used for parsing. The String patterns must be compatible with SimpleDateFormat.

Parameters:
datepatterns - collection of date patterns

getValidDateFormats

Collection getValidDateFormats()
Returns the Collection of date patterns used for parsing. The String patterns are compatible with the SimpleDateFormat.

Returns:
collection of date patterns

match

boolean match(String host,
              int port,
              String path,
              boolean secure,
              Cookie cookie)
Determines if a Cookie matches a location.

Parameters:
host - the host to which the request is being submitted
port - the port to which the request is being submitted
path - the path to which the request is being submitted
secure - true if the request is using a secure connection
cookie - the Cookie to be matched
Returns:
true if the cookie should be submitted with a request with given attributes, false otherwise.

match

Cookie[] match(String host,
               int port,
               String path,
               boolean secure,
               Cookie[] cookies)
Determines which of an array of Cookies matches a location.

Parameters:
host - the host to which the request is being submitted
port - the port to which the request is being submitted (currenlty ignored)
path - the path to which the request is being submitted
secure - true if the request is using a secure protocol
cookies - an array of Cookies to be matched
Returns:
true if the cookie should be submitted with a request with given attributes, false otherwise.

domainMatch

boolean domainMatch(String host,
                    String domain)
Performs domain-match as defined by the cookie specification.

Parameters:
host - The target host.
domain - The cookie domain attribute.
Returns:
true if the specified host matches the given domain.
Since:
3.0

pathMatch

boolean pathMatch(String path,
                  String topmostPath)
Performs path-match as defined by the cookie specification.

Parameters:
path - The target path.
topmostPath - The cookie path attribute.
Returns:
true if the paths match
Since:
3.0

formatCookie

String formatCookie(Cookie cookie)
Create a "Cookie" header value for an array of cookies.

Parameters:
cookie - the cookie to be formatted as string
Returns:
a string suitable for sending in a "Cookie" header.

formatCookies

String formatCookies(Cookie[] cookies)
                     throws IllegalArgumentException
Create a "Cookie" header value for an array of cookies.

Parameters:
cookies - the Cookies to be formatted
Returns:
a string suitable for sending in a Cookie header.
Throws:
IllegalArgumentException - if an input parameter is illegal

formatCookieHeader

Header formatCookieHeader(Cookie[] cookies)
                          throws IllegalArgumentException
Create a "Cookie" Header for an array of Cookies.

Parameters:
cookies - the Cookies format into a Cookie header
Returns:
a Header for the given Cookies.
Throws:
IllegalArgumentException - if an input parameter is illegal

formatCookieHeader

Header formatCookieHeader(Cookie cookie)
                          throws IllegalArgumentException
Create a "Cookie" Header for single Cookie.

Parameters:
cookie - the Cookie format as a Cookie header
Returns:
a Cookie header.
Throws:
IllegalArgumentException - if an input parameter is illegal


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/CookieSpecBase.html100644 0 0 152141 10661532627 27600 0ustar 0 0 CookieSpecBase (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Class CookieSpecBase

java.lang.Object
  extended by org.apache.commons.httpclient.cookie.CookieSpecBase
All Implemented Interfaces:
CookieSpec
Direct Known Subclasses:
NetscapeDraftSpec, RFC2109Spec, RFC2965Spec

public class CookieSpecBase
extends Object
implements CookieSpec

Cookie management functions shared by all specification.

Since:
2.0
Author:
B.C. Holmes, Park, Sung-Gu, Doug Sale, Rod Waldhoff, dIon Gillard, Sean C. Sullivan, John Evans, Marc A. Saegesser, Oleg Kalnichevski, Mike Bowler

Field Summary
protected static Log LOG
          Log object
 
Fields inherited from interface org.apache.commons.httpclient.cookie.CookieSpec
PATH_DELIM, PATH_DELIM_CHAR
 
Constructor Summary
CookieSpecBase()
          Default constructor
 
Method Summary
 boolean domainMatch(String host, String domain)
          Performs domain-match as implemented in common browsers.
 String formatCookie(Cookie cookie)
          Return a string suitable for sending in a "Cookie" header
 Header formatCookieHeader(Cookie cookie)
          Create a "Cookie" Header containing the Cookie.
 Header formatCookieHeader(Cookie[] cookies)
          Create a "Cookie" Header containing all Cookies in cookies.
 String formatCookies(Cookie[] cookies)
          Create a "Cookie" header value containing all Cookies in cookies suitable for sending in a "Cookie" header
 Collection getValidDateFormats()
          Returns the Collection of date patterns used for parsing.
 boolean match(String host, int port, String path, boolean secure, Cookie cookie)
          Return true if the cookie should be submitted with a request with given attributes, false otherwise.
 Cookie[] match(String host, int port, String path, boolean secure, Cookie[] cookies)
          Return an array of Cookies that should be submitted with a request with given attributes, false otherwise.
 Cookie[] parse(String host, int port, String path, boolean secure, Header header)
          Parse the "Set-Cookie" Header into an array of Cookies.
 Cookie[] parse(String host, int port, String path, boolean secure, String header)
          Parses the Set-Cookie value into an array of Cookies.
 void parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties.
 boolean pathMatch(String path, String topmostPath)
          Performs path-match as implemented in common browsers.
 void setValidDateFormats(Collection datepatterns)
          Sets the Collection of date patterns used for parsing.
 void validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs most common Cookie validation
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

LOG

protected static final Log LOG
Log object

Constructor Detail

CookieSpecBase

public CookieSpecBase()
Default constructor

Method Detail

parse

public Cookie[] parse(String host,
                      int port,
                      String path,
                      boolean secure,
                      String header)
               throws MalformedCookieException
Parses the Set-Cookie value into an array of Cookies.

The syntax for the Set-Cookie response header is:

 set-cookie      =    "Set-Cookie:" cookies
 cookies         =    1#cookie
 cookie          =    NAME "=" VALUE * (";" cookie-av)
 NAME            =    attr
 VALUE           =    value
 cookie-av       =    "Comment" "=" value
                 |    "Domain" "=" value
                 |    "Max-Age" "=" value
                 |    "Path" "=" value
                 |    "Secure"
                 |    "Version" "=" 1*DIGIT
 

Specified by:
parse in interface CookieSpec
Parameters:
host - the host from which the Set-Cookie value was received
port - the port from which the Set-Cookie value was received
path - the path from which the Set-Cookie value was received
secure - true when the Set-Cookie value was received over secure conection
header - the Set-Cookie received from the server
Returns:
an array of Cookies parsed from the Set-Cookie value
Throws:
MalformedCookieException - if an exception occurs during parsing
See Also:
CookieSpec.validate(String, int, String, boolean, Cookie)

parse

public Cookie[] parse(String host,
                      int port,
                      String path,
                      boolean secure,
                      Header header)
               throws MalformedCookieException
Parse the "Set-Cookie" Header into an array of Cookies.

The syntax for the Set-Cookie response header is:

 set-cookie      =    "Set-Cookie:" cookies
 cookies         =    1#cookie
 cookie          =    NAME "=" VALUE * (";" cookie-av)
 NAME            =    attr
 VALUE           =    value
 cookie-av       =    "Comment" "=" value
                 |    "Domain" "=" value
                 |    "Max-Age" "=" value
                 |    "Path" "=" value
                 |    "Secure"
                 |    "Version" "=" 1*DIGIT
 

Specified by:
parse in interface CookieSpec
Parameters:
host - the host from which the Set-Cookie header was received
port - the port from which the Set-Cookie header was received
path - the path from which the Set-Cookie header was received
secure - true when the Set-Cookie header was received over secure conection
header - the Set-Cookie received from the server
Returns:
an array of Cookies parsed from the "Set-Cookie" header
Throws:
MalformedCookieException - if an exception occurs during parsing
See Also:
CookieSpec.validate(String, int, String, boolean, Cookie)

parseAttribute

public void parseAttribute(NameValuePair attribute,
                           Cookie cookie)
                    throws MalformedCookieException
Parse the cookie attribute and update the corresponsing Cookie properties.

Specified by:
parseAttribute in interface CookieSpec
Parameters:
attribute - HeaderElement cookie attribute from the Set- Cookie
cookie - Cookie to be updated
Throws:
MalformedCookieException - if an exception occurs during parsing

getValidDateFormats

public Collection getValidDateFormats()
Description copied from interface: CookieSpec
Returns the Collection of date patterns used for parsing. The String patterns are compatible with the SimpleDateFormat.

Specified by:
getValidDateFormats in interface CookieSpec
Returns:
collection of date patterns

setValidDateFormats

public void setValidDateFormats(Collection datepatterns)
Description copied from interface: CookieSpec
Sets the Collection of date patterns used for parsing. The String patterns must be compatible with SimpleDateFormat.

Specified by:
setValidDateFormats in interface CookieSpec
Parameters:
datepatterns - collection of date patterns

validate

public void validate(String host,
                     int port,
                     String path,
                     boolean secure,
                     Cookie cookie)
              throws MalformedCookieException
Performs most common Cookie validation

Specified by:
validate in interface CookieSpec
Parameters:
host - the host from which the Cookie was received
port - the port from which the Cookie was received
path - the path from which the Cookie was received
secure - true when the Cookie was received using a secure connection
cookie - The cookie to validate.
Throws:
MalformedCookieException - if an exception occurs during validation

match

public boolean match(String host,
                     int port,
                     String path,
                     boolean secure,
                     Cookie cookie)
Return true if the cookie should be submitted with a request with given attributes, false otherwise.

Specified by:
match in interface CookieSpec
Parameters:
host - the host to which the request is being submitted
port - the port to which the request is being submitted (ignored)
path - the path to which the request is being submitted
secure - true if the request is using a secure connection
cookie - Cookie to be matched
Returns:
true if the cookie matches the criterium

domainMatch

public boolean domainMatch(String host,
                           String domain)
Performs domain-match as implemented in common browsers.

Specified by:
domainMatch in interface CookieSpec
Parameters:
host - The target host.
domain - The cookie domain attribute.
Returns:
true if the specified host matches the given domain.

pathMatch

public boolean pathMatch(String path,
                         String topmostPath)
Performs path-match as implemented in common browsers.

Specified by:
pathMatch in interface CookieSpec
Parameters:
path - The target path.
topmostPath - The cookie path attribute.
Returns:
true if the paths match

match

public Cookie[] match(String host,
                      int port,
                      String path,
                      boolean secure,
                      Cookie[] cookies)
Return an array of Cookies that should be submitted with a request with given attributes, false otherwise.

Specified by:
match in interface CookieSpec
Parameters:
host - the host to which the request is being submitted
port - the port to which the request is being submitted (currently ignored)
path - the path to which the request is being submitted
secure - true if the request is using a secure protocol
cookies - an array of Cookies to be matched
Returns:
an array of Cookies matching the criterium

formatCookie

public String formatCookie(Cookie cookie)
Return a string suitable for sending in a "Cookie" header

Specified by:
formatCookie in interface CookieSpec
Parameters:
cookie - a Cookie to be formatted as string
Returns:
a string suitable for sending in a "Cookie" header.

formatCookies

public String formatCookies(Cookie[] cookies)
                     throws IllegalArgumentException
Create a "Cookie" header value containing all Cookies in cookies suitable for sending in a "Cookie" header

Specified by:
formatCookies in interface CookieSpec
Parameters:
cookies - an array of Cookies to be formatted
Returns:
a string suitable for sending in a Cookie header.
Throws:
IllegalArgumentException - if an input parameter is illegal

formatCookieHeader

public Header formatCookieHeader(Cookie[] cookies)
Create a "Cookie" Header containing all Cookies in cookies.

Specified by:
formatCookieHeader in interface CookieSpec
Parameters:
cookies - an array of Cookies to be formatted as a " Cookie" header
Returns:
a "Cookie" Header.

formatCookieHeader

public Header formatCookieHeader(Cookie cookie)
Create a "Cookie" Header containing the Cookie.

Specified by:
formatCookieHeader in interface CookieSpec
Parameters:
cookie - Cookies to be formatted as a Cookie header
Returns:
a Cookie header.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/CookieVersionSupport.html100644 0 0 22640 10661532627 31115 0ustar 0 0 CookieVersionSupport (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Interface CookieVersionSupport

All Known Implementing Classes:
RFC2965Spec

public interface CookieVersionSupport

Defines cookie specification specific capabilities

Since:
3.1
Author:
Oleg Kalnichevski

Method Summary
 int getVersion()
           
 Header getVersionHeader()
           
 

Method Detail

getVersion

int getVersion()

getVersionHeader

Header getVersionHeader()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.html100644 0 0 142344 10661532627 30340 0ustar 0 0 IgnoreCookiesSpec (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Class IgnoreCookiesSpec

java.lang.Object
  extended by org.apache.commons.httpclient.cookie.IgnoreCookiesSpec
All Implemented Interfaces:
CookieSpec

public class IgnoreCookiesSpec
extends Object
implements CookieSpec

A cookie spec that does nothing. Cookies are neither parsed, formatted nor matched. It can be used to effectively disable cookies altogether.

Since:
3.0

Field Summary
 
Fields inherited from interface org.apache.commons.httpclient.cookie.CookieSpec
PATH_DELIM, PATH_DELIM_CHAR
 
Constructor Summary
IgnoreCookiesSpec()
           
 
Method Summary
 boolean domainMatch(String host, String domain)
          Performs domain-match as defined by the cookie specification.
 String formatCookie(Cookie cookie)
          Create a "Cookie" header value for an array of cookies.
 Header formatCookieHeader(Cookie cookie)
          Create a "Cookie" Header for single Cookie.
 Header formatCookieHeader(Cookie[] cookies)
          Create a "Cookie" Header for an array of Cookies.
 String formatCookies(Cookie[] cookies)
          Create a "Cookie" header value for an array of cookies.
 Collection getValidDateFormats()
          Returns the Collection of date patterns used for parsing.
 boolean match(String host, int port, String path, boolean secure, Cookie cookie)
          Determines if a Cookie matches a location.
 Cookie[] match(String host, int port, String path, boolean secure, Cookie[] cookies)
          Returns an empty cookie array.
 Cookie[] parse(String host, int port, String path, boolean secure, Header header)
          Returns an empty cookie array.
 Cookie[] parse(String host, int port, String path, boolean secure, String header)
          Returns an empty cookie array.
 void parseAttribute(NameValuePair attribute, Cookie cookie)
          Does nothing.
 boolean pathMatch(String path, String topmostPath)
          Performs path-match as defined by the cookie specification.
 void setValidDateFormats(Collection datepatterns)
          Does nothing.
 void validate(String host, int port, String path, boolean secure, Cookie cookie)
          Does nothing.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

IgnoreCookiesSpec

public IgnoreCookiesSpec()
Method Detail

parse

public Cookie[] parse(String host,
                      int port,
                      String path,
                      boolean secure,
                      String header)
               throws MalformedCookieException
Returns an empty cookie array. All parameters are ignored.

Specified by:
parse in interface CookieSpec
Parameters:
host - the host which sent the Set-Cookie header
port - the port which sent the Set-Cookie header
path - the path which sent the Set-Cookie header
secure - true when the Set-Cookie header was received over secure conection
header - the Set-Cookie received from the server
Returns:
an array of Cookies parsed from the Set-Cookie value
Throws:
MalformedCookieException - if an exception occurs during parsing
See Also:
CookieSpec.validate(String, int, String, boolean, Cookie)

getValidDateFormats

public Collection getValidDateFormats()
Description copied from interface: CookieSpec
Returns the Collection of date patterns used for parsing. The String patterns are compatible with the SimpleDateFormat.

Specified by:
getValidDateFormats in interface CookieSpec
Returns:
null

setValidDateFormats

public void setValidDateFormats(Collection datepatterns)
Does nothing.

Specified by:
setValidDateFormats in interface CookieSpec
Parameters:
datepatterns - collection of date patterns

formatCookie

public String formatCookie(Cookie cookie)
Description copied from interface: CookieSpec
Create a "Cookie" header value for an array of cookies.

Specified by:
formatCookie in interface CookieSpec
Parameters:
cookie - the cookie to be formatted as string
Returns:
null

formatCookieHeader

public Header formatCookieHeader(Cookie cookie)
                          throws IllegalArgumentException
Description copied from interface: CookieSpec
Create a "Cookie" Header for single Cookie.

Specified by:
formatCookieHeader in interface CookieSpec
Parameters:
cookie - the Cookie format as a Cookie header
Returns:
null
Throws:
IllegalArgumentException - if an input parameter is illegal

formatCookieHeader

public Header formatCookieHeader(Cookie[] cookies)
                          throws IllegalArgumentException
Description copied from interface: CookieSpec
Create a "Cookie" Header for an array of Cookies.

Specified by:
formatCookieHeader in interface CookieSpec
Parameters:
cookies - the Cookies format into a Cookie header
Returns:
null
Throws:
IllegalArgumentException - if an input parameter is illegal

formatCookies

public String formatCookies(Cookie[] cookies)
                     throws IllegalArgumentException
Description copied from interface: CookieSpec
Create a "Cookie" header value for an array of cookies.

Specified by:
formatCookies in interface CookieSpec
Parameters:
cookies - the Cookies to be formatted
Returns:
null
Throws:
IllegalArgumentException - if an input parameter is illegal

match

public boolean match(String host,
                     int port,
                     String path,
                     boolean secure,
                     Cookie cookie)
Description copied from interface: CookieSpec
Determines if a Cookie matches a location.

Specified by:
match in interface CookieSpec
Parameters:
host - the host to which the request is being submitted
port - the port to which the request is being submitted
path - the path to which the request is being submitted
secure - true if the request is using a secure connection
cookie - the Cookie to be matched
Returns:
false

match

public Cookie[] match(String host,
                      int port,
                      String path,
                      boolean secure,
                      Cookie[] cookies)
Returns an empty cookie array. All parameters are ignored.

Specified by:
match in interface CookieSpec
Parameters:
host - the host to which the request is being submitted
port - the port to which the request is being submitted (currenlty ignored)
path - the path to which the request is being submitted
secure - true if the request is using a secure protocol
cookies - an array of Cookies to be matched
Returns:
true if the cookie should be submitted with a request with given attributes, false otherwise.

parse

public Cookie[] parse(String host,
                      int port,
                      String path,
                      boolean secure,
                      Header header)
               throws MalformedCookieException,
                      IllegalArgumentException
Returns an empty cookie array. All parameters are ignored.

Specified by:
parse in interface CookieSpec
Parameters:
host - the host which sent the Set-Cookie header
port - the port which sent the Set-Cookie header
path - the path which sent the Set-Cookie header
secure - true when the Set-Cookie header was received over secure conection
header - the Set-Cookie received from the server
Returns:
an array of Cookies parsed from the header
Throws:
MalformedCookieException - if an exception occurs during parsing
IllegalArgumentException - if an input parameter is illegal
See Also:
CookieSpec.validate(String, int, String, boolean, Cookie)

parseAttribute

public void parseAttribute(NameValuePair attribute,
                           Cookie cookie)
                    throws MalformedCookieException,
                           IllegalArgumentException
Does nothing.

Specified by:
parseAttribute in interface CookieSpec
Parameters:
attribute - cookie attribute from the Set-Cookie
cookie - the to be updated
Throws:
MalformedCookieException - if an exception occurs during parsing
IllegalArgumentException - if an input parameter is illegal

validate

public void validate(String host,
                     int port,
                     String path,
                     boolean secure,
                     Cookie cookie)
              throws MalformedCookieException,
                     IllegalArgumentException
Does nothing.

Specified by:
validate in interface CookieSpec
Parameters:
host - the host from which the Cookie was received
port - the port from which the Cookie was received
path - the path from which the Cookie was received
secure - true when the Cookie was received using a secure connection
cookie - the Cookie to validate
Throws:
MalformedCookieException - if the cookie is invalid
IllegalArgumentException - if an input parameter is illegal

domainMatch

public boolean domainMatch(String host,
                           String domain)
Description copied from interface: CookieSpec
Performs domain-match as defined by the cookie specification.

Specified by:
domainMatch in interface CookieSpec
Parameters:
host - The target host.
domain - The cookie domain attribute.
Returns:
false

pathMatch

public boolean pathMatch(String path,
                         String topmostPath)
Description copied from interface: CookieSpec
Performs path-match as defined by the cookie specification.

Specified by:
pathMatch in interface CookieSpec
Parameters:
path - The target path.
topmostPath - The cookie path attribute.
Returns:
false


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/MalformedCookieException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/MalformedCookieException.ht100644 0 0 44515 10661532627 31334 0ustar 0 0 MalformedCookieException (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Class MalformedCookieException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by java.io.IOException
              extended by org.apache.commons.httpclient.HttpException
                  extended by org.apache.commons.httpclient.ProtocolException
                      extended by org.apache.commons.httpclient.cookie.MalformedCookieException
All Implemented Interfaces:
Serializable

public class MalformedCookieException
extends ProtocolException

Signals that a cookie is in some way invalid or illegal in a given context

Since:
2.0
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
MalformedCookieException()
          Creates a new MalformedCookieException with a null detail message.
MalformedCookieException(String message)
          Creates a new MalformedCookieException with a specified message string.
MalformedCookieException(String message, Throwable cause)
          Creates a new MalformedCookieException with the specified detail message and cause.
 
Method Summary
 
Methods inherited from class org.apache.commons.httpclient.HttpException
getCause, getReason, getReasonCode, printStackTrace, printStackTrace, printStackTrace, setReason, setReasonCode
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, initCause, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

MalformedCookieException

public MalformedCookieException()
Creates a new MalformedCookieException with a null detail message.


MalformedCookieException

public MalformedCookieException(String message)
Creates a new MalformedCookieException with a specified message string.

Parameters:
message - The exception detail message

MalformedCookieException

public MalformedCookieException(String message,
                                Throwable cause)
Creates a new MalformedCookieException with the specified detail message and cause.

Parameters:
message - the exception detail message
cause - the Throwable that caused this exception, or null if the cause is unavailable, unknown, or not a Throwable
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/NetscapeDraftSpec.html100644 0 0 75107 10661532627 30305 0ustar 0 0 NetscapeDraftSpec (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Class NetscapeDraftSpec

java.lang.Object
  extended by org.apache.commons.httpclient.cookie.CookieSpecBase
      extended by org.apache.commons.httpclient.cookie.NetscapeDraftSpec
All Implemented Interfaces:
CookieSpec

public class NetscapeDraftSpec
extends CookieSpecBase

Netscape cookie draft specific cookie management functions

Since:
2.0
Author:
B.C. Holmes, Park, Sung-Gu, Doug Sale, Rod Waldhoff, dIon Gillard, Sean C. Sullivan, John Evans, Marc A. Saegesser, Oleg Kalnichevski, Mike Bowler

Field Summary
 
Fields inherited from class org.apache.commons.httpclient.cookie.CookieSpecBase
LOG
 
Fields inherited from interface org.apache.commons.httpclient.cookie.CookieSpec
PATH_DELIM, PATH_DELIM_CHAR
 
Constructor Summary
NetscapeDraftSpec()
          Default constructor
 
Method Summary
 boolean domainMatch(String host, String domain)
          Performs domain-match as described in the Netscape draft.
 Cookie[] parse(String host, int port, String path, boolean secure, String header)
          Parses the Set-Cookie value into an array of Cookies.
 void parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties as defined by the Netscape draft specification
 void validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs Netscape draft compliant Cookie validation
 
Methods inherited from class org.apache.commons.httpclient.cookie.CookieSpecBase
formatCookie, formatCookieHeader, formatCookieHeader, formatCookies, getValidDateFormats, match, match, parse, pathMatch, setValidDateFormats
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

NetscapeDraftSpec

public NetscapeDraftSpec()
Default constructor

Method Detail

parse

public Cookie[] parse(String host,
                      int port,
                      String path,
                      boolean secure,
                      String header)
               throws MalformedCookieException
Parses the Set-Cookie value into an array of Cookies.

Syntax of the Set-Cookie HTTP Response Header:

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

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

Please note that Netscape draft specification does not fully conform to the HTTP header format. Netscape draft does not specify whether multiple cookies may be sent in one header. Hence, comma character may be present in unquoted cookie value or unquoted parameter value.

Specified by:
parse in interface CookieSpec
Overrides:
parse in class CookieSpecBase
Parameters:
host - the host from which the Set-Cookie value was received
port - the port from which the Set-Cookie value was received
path - the path from which the Set-Cookie value was received
secure - true when the Set-Cookie value was received over secure conection
header - the Set-Cookie received from the server
Returns:
an array of Cookies parsed from the Set-Cookie value
Throws:
MalformedCookieException - if an exception occurs during parsing
Since:
3.0
See Also:
CookieSpec.validate(String, int, String, boolean, Cookie)

parseAttribute

public void parseAttribute(NameValuePair attribute,
                           Cookie cookie)
                    throws MalformedCookieException
Parse the cookie attribute and update the corresponsing Cookie properties as defined by the Netscape draft specification

Specified by:
parseAttribute in interface CookieSpec
Overrides:
parseAttribute in class CookieSpecBase
Parameters:
attribute - NameValuePair cookie attribute from the Set- Cookie
cookie - Cookie to be updated
Throws:
MalformedCookieException - if an exception occurs during parsing

domainMatch

public boolean domainMatch(String host,
                           String domain)
Performs domain-match as described in the Netscape draft.

Specified by:
domainMatch in interface CookieSpec
Overrides:
domainMatch in class CookieSpecBase
Parameters:
host - The target host.
domain - The cookie domain attribute.
Returns:
true if the specified host matches the given domain.

validate

public void validate(String host,
                     int port,
                     String path,
                     boolean secure,
                     Cookie cookie)
              throws MalformedCookieException
Performs Netscape draft compliant Cookie validation

Specified by:
validate in interface CookieSpec
Overrides:
validate in class CookieSpecBase
Parameters:
host - the host from which the Cookie was received
port - the port from which the Cookie was received
path - the path from which the Cookie was received
secure - true when the Cookie was received using a secure connection
cookie - The cookie to validate.
Throws:
MalformedCookieException - if an exception occurs during validation


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/RFC2109Spec.html100644 0 0 77507 10661532627 26516 0ustar 0 0 RFC2109Spec (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Class RFC2109Spec

java.lang.Object
  extended by org.apache.commons.httpclient.cookie.CookieSpecBase
      extended by org.apache.commons.httpclient.cookie.RFC2109Spec
All Implemented Interfaces:
CookieSpec

public class RFC2109Spec
extends CookieSpecBase

RFC 2109 specific cookie management functions

Since:
2.0
Author:
B.C. Holmes, Park, Sung-Gu, Doug Sale, Rod Waldhoff, dIon Gillard, Sean C. Sullivan, John Evans, Marc A. Saegesser, Oleg Kalnichevski, Mike Bowler

Field Summary
static String SET_COOKIE_KEY
          Cookie Response Header name for cookies processed by this spec.
 
Fields inherited from class org.apache.commons.httpclient.cookie.CookieSpecBase
LOG
 
Fields inherited from interface org.apache.commons.httpclient.cookie.CookieSpec
PATH_DELIM, PATH_DELIM_CHAR
 
Constructor Summary
RFC2109Spec()
          Default constructor
 
Method Summary
 boolean domainMatch(String host, String domain)
          Performs domain-match as defined by the RFC2109.
 String formatCookie(Cookie cookie)
          Return a string suitable for sending in a "Cookie" header as defined in RFC 2109
 String formatCookies(Cookie[] cookies)
          Create a RFC 2109 compliant "Cookie" header value containing all Cookies in cookies suitable for sending in a "Cookie" header
 void parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse RFC 2109 specific cookie attribute and update the corresponsing Cookie properties.
 void validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs RFC 2109 compliant Cookie validation
 
Methods inherited from class org.apache.commons.httpclient.cookie.CookieSpecBase
formatCookieHeader, formatCookieHeader, getValidDateFormats, match, match, parse, parse, pathMatch, setValidDateFormats
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SET_COOKIE_KEY

public static final String SET_COOKIE_KEY
Cookie Response Header name for cookies processed by this spec.

See Also:
Constant Field Values
Constructor Detail

RFC2109Spec

public RFC2109Spec()
Default constructor

Method Detail

parseAttribute

public void parseAttribute(NameValuePair attribute,
                           Cookie cookie)
                    throws MalformedCookieException
Parse RFC 2109 specific cookie attribute and update the corresponsing Cookie properties.

Specified by:
parseAttribute in interface CookieSpec
Overrides:
parseAttribute in class CookieSpecBase
Parameters:
attribute - NameValuePair cookie attribute from the Set- Cookie
cookie - Cookie to be updated
Throws:
MalformedCookieException - if an exception occurs during parsing

validate

public void validate(String host,
                     int port,
                     String path,
                     boolean secure,
                     Cookie cookie)
              throws MalformedCookieException
Performs RFC 2109 compliant Cookie validation

Specified by:
validate in interface CookieSpec
Overrides:
validate in class CookieSpecBase
Parameters:
host - the host from which the Cookie was received
port - the port from which the Cookie was received
path - the path from which the Cookie was received
secure - true when the Cookie was received using a secure connection
cookie - The cookie to validate
Throws:
MalformedCookieException - if an exception occurs during validation

domainMatch

public boolean domainMatch(String host,
                           String domain)
Performs domain-match as defined by the RFC2109.

Specified by:
domainMatch in interface CookieSpec
Overrides:
domainMatch in class CookieSpecBase
Parameters:
host - The target host.
domain - The cookie domain attribute.
Returns:
true if the specified host matches the given domain.
Since:
3.0

formatCookie

public String formatCookie(Cookie cookie)
Return a string suitable for sending in a "Cookie" header as defined in RFC 2109

Specified by:
formatCookie in interface CookieSpec
Overrides:
formatCookie in class CookieSpecBase
Parameters:
cookie - a Cookie to be formatted as string
Returns:
a string suitable for sending in a "Cookie" header.

formatCookies

public String formatCookies(Cookie[] cookies)
Create a RFC 2109 compliant "Cookie" header value containing all Cookies in cookies suitable for sending in a "Cookie" header

Specified by:
formatCookies in interface CookieSpec
Overrides:
formatCookies in class CookieSpecBase
Parameters:
cookies - an array of Cookies to be formatted
Returns:
a string suitable for sending in a Cookie header.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/RFC2965Spec.html100644 0 0 147612 10661532627 26543 0ustar 0 0 RFC2965Spec (HttpClient 3.1 API)

org.apache.commons.httpclient.cookie
Class RFC2965Spec

java.lang.Object
  extended by org.apache.commons.httpclient.cookie.CookieSpecBase
      extended by org.apache.commons.httpclient.cookie.RFC2965Spec
All Implemented Interfaces:
CookieSpec, CookieVersionSupport

public class RFC2965Spec
extends CookieSpecBase
implements CookieVersionSupport

RFC 2965 specific cookie management functions.

Since:
3.1
Author:
jain.samit@gmail.com (Samit Jain)

Field Summary
static String SET_COOKIE2_KEY
          Cookie Response Header name for cookies processed by this spec.
 
Fields inherited from class org.apache.commons.httpclient.cookie.CookieSpecBase
LOG
 
Fields inherited from interface org.apache.commons.httpclient.cookie.CookieSpec
PATH_DELIM, PATH_DELIM_CHAR
 
Constructor Summary
RFC2965Spec()
          Default constructor
 
Method Summary
 boolean domainMatch(String host, String domain)
          Performs domain-match as defined by the RFC2965.
protected  CookieAttributeHandler findAttribHandler(String name)
          Finds an attribute handler CookieAttributeHandler for the given attribute.
 String formatCookie(Cookie cookie)
          Return a string suitable for sending in a "Cookie" header as defined in RFC 2965
 String formatCookies(Cookie[] cookies)
          Create a RFC 2965 compliant "Cookie" header value containing all Cookies suitable for sending in a "Cookie" header
protected  CookieAttributeHandler getAttribHandler(String name)
          Gets attribute handler CookieAttributeHandler for the given attribute.
protected  Iterator getAttribHandlerIterator()
           
 int getVersion()
           
 Header getVersionHeader()
           
 boolean match(String host, int port, String path, boolean secure, Cookie cookie)
          Return true if the cookie should be submitted with a request with given attributes, false otherwise.
 Cookie[] parse(String host, int port, String path, boolean secure, Header header)
          Parses the Set-Cookie2 value into an array of Cookies.
 Cookie[] parse(String host, int port, String path, boolean secure, String header)
          Parses the Set-Cookie value into an array of Cookies.
 void parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse RFC 2965 specific cookie attribute and update the corresponsing Cookie properties.
protected  void registerAttribHandler(String name, CookieAttributeHandler handler)
           
 void validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs RFC 2965 compliant Cookie validation
 
Methods inherited from class org.apache.commons.httpclient.cookie.CookieSpecBase
formatCookieHeader, formatCookieHeader, getValidDateFormats, match, pathMatch, setValidDateFormats
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SET_COOKIE2_KEY

public static final String SET_COOKIE2_KEY
Cookie Response Header name for cookies processed by this spec.

See Also:
Constant Field Values
Constructor Detail

RFC2965Spec

public RFC2965Spec()
Default constructor

Method Detail

registerAttribHandler

protected void registerAttribHandler(String name,
                                     CookieAttributeHandler handler)

findAttribHandler

protected CookieAttributeHandler findAttribHandler(String name)
Finds an attribute handler CookieAttributeHandler for the given attribute. Returns null if no attribute handler is found for the specified attribute.

Parameters:
name - attribute name. e.g. Domain, Path, etc.
Returns:
an attribute handler or null

getAttribHandler

protected CookieAttributeHandler getAttribHandler(String name)
Gets attribute handler CookieAttributeHandler for the given attribute.

Parameters:
name - attribute name. e.g. Domain, Path, etc.
Throws:
IllegalStateException - if handler not found for the specified attribute.

getAttribHandlerIterator

protected Iterator getAttribHandlerIterator()

parse

public Cookie[] parse(String host,
                      int port,
                      String path,
                      boolean secure,
                      Header header)
               throws MalformedCookieException
Parses the Set-Cookie2 value into an array of Cookies.

The syntax for the Set-Cookie2 response header is:

 set-cookie      =    "Set-Cookie2:" cookies
 cookies         =    1#cookie
 cookie          =    NAME "=" VALUE * (";" cookie-av)
 NAME            =    attr
 VALUE           =    value
 cookie-av       =    "Comment" "=" value
                 |    "CommentURL" "=" <"> http_URL <">
                 |    "Discard"
                 |    "Domain" "=" value
                 |    "Max-Age" "=" value
                 |    "Path" "=" value
                 |    "Port" [ "=" <"> portlist <"> ]
                 |    "Secure"
                 |    "Version" "=" 1*DIGIT
 portlist        =       1#portnum
 portnum         =       1*DIGIT
 

Specified by:
parse in interface CookieSpec
Overrides:
parse in class CookieSpecBase
Parameters:
host - the host from which the Set-Cookie2 value was received
port - the port from which the Set-Cookie2 value was received
path - the path from which the Set-Cookie2 value was received
secure - true when the Set-Cookie2 value was received over secure conection
header - the Set-Cookie2 Header received from the server
Returns:
an array of Cookies parsed from the Set-Cookie2 value
Throws:
MalformedCookieException - if an exception occurs during parsing
See Also:
CookieSpec.validate(String, int, String, boolean, Cookie)

parse

public Cookie[] parse(String host,
                      int port,
                      String path,
                      boolean secure,
                      String header)
               throws MalformedCookieException
Description copied from class: CookieSpecBase
Parses the Set-Cookie value into an array of Cookies.

The syntax for the Set-Cookie response header is:

 set-cookie      =    "Set-Cookie:" cookies
 cookies         =    1#cookie
 cookie          =    NAME "=" VALUE * (";" cookie-av)
 NAME            =    attr
 VALUE           =    value
 cookie-av       =    "Comment" "=" value
                 |    "Domain" "=" value
                 |    "Max-Age" "=" value
                 |    "Path" "=" value
                 |    "Secure"
                 |    "Version" "=" 1*DIGIT
 

Specified by:
parse in interface CookieSpec
Overrides:
parse in class CookieSpecBase
Parameters:
host - the host from which the Set-Cookie value was received
port - the port from which the Set-Cookie value was received
path - the path from which the Set-Cookie value was received
secure - true when the Set-Cookie value was received over secure conection
header - the Set-Cookie received from the server
Returns:
an array of Cookies parsed from the Set-Cookie value
Throws:
MalformedCookieException - if an exception occurs during parsing
See Also:
parse(String, int, String, boolean, org.apache.commons.httpclient.Header)

parseAttribute

public void parseAttribute(NameValuePair attribute,
                           Cookie cookie)
                    throws MalformedCookieException
Parse RFC 2965 specific cookie attribute and update the corresponsing Cookie properties.

Specified by:
parseAttribute in interface CookieSpec
Overrides:
parseAttribute in class CookieSpecBase
Parameters:
attribute - NameValuePair cookie attribute from the Set-Cookie2 header.
cookie - Cookie to be updated
Throws:
MalformedCookieException - if an exception occurs during parsing

validate

public void validate(String host,
                     int port,
                     String path,
                     boolean secure,
                     Cookie cookie)
              throws MalformedCookieException
Performs RFC 2965 compliant Cookie validation

Specified by:
validate in interface CookieSpec
Overrides:
validate in class CookieSpecBase
Parameters:
host - the host from which the Cookie was received
port - the port from which the Cookie was received
path - the path from which the Cookie was received
secure - true when the Cookie was received using a secure connection
cookie - The cookie to validate
Throws:
MalformedCookieException - if an exception occurs during validation

match

public boolean match(String host,
                     int port,
                     String path,
                     boolean secure,
                     Cookie cookie)
Return true if the cookie should be submitted with a request with given attributes, false otherwise.

Specified by:
match in interface CookieSpec
Overrides:
match in class CookieSpecBase
Parameters:
host - the host to which the request is being submitted
port - the port to which the request is being submitted (ignored)
path - the path to which the request is being submitted
secure - true if the request is using a secure connection
cookie - Cookie to be matched
Returns:
true if the cookie matches the criterium

formatCookie

public String formatCookie(Cookie cookie)
Return a string suitable for sending in a "Cookie" header as defined in RFC 2965

Specified by:
formatCookie in interface CookieSpec
Overrides:
formatCookie in class CookieSpecBase
Parameters:
cookie - a Cookie to be formatted as string
Returns:
a string suitable for sending in a "Cookie" header.

formatCookies

public String formatCookies(Cookie[] cookies)
Create a RFC 2965 compliant "Cookie" header value containing all Cookies suitable for sending in a "Cookie" header

Specified by:
formatCookies in interface CookieSpec
Overrides:
formatCookies in class CookieSpecBase
Parameters:
cookies - an array of Cookies to be formatted
Returns:
a string suitable for sending in a Cookie header.

domainMatch

public boolean domainMatch(String host,
                           String domain)
Performs domain-match as defined by the RFC2965.

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

      their host name strings string-compare equal; or
      A is a HDN string and has the form NB, where N is a non-empty name string, B has the form .B', and B' is a HDN string. (So, x.y.com domain-matches .Y.com but not Y.com.)

Specified by:
domainMatch in interface CookieSpec
Overrides:
domainMatch in class CookieSpecBase
Parameters:
host - host name where cookie is received from or being sent to.
domain - The cookie domain attribute.
Returns:
true if the specified host matches the given domain.

getVersion

public int getVersion()
Specified by:
getVersion in interface CookieVersionSupport

getVersionHeader

public Header getVersionHeader()
Specified by:
getVersionHeader in interface CookieVersionSupport


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/Cookie2.html100644 0 0 13714 10661532627 30135 0ustar 0 0 Uses of Class org.apache.commons.httpclient.cookie.Cookie2 (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.cookie.Cookie2

No usage of org.apache.commons.httpclient.cookie.Cookie2



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 157 10661532634 10264 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookieAttributeHandler.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookieAttributeHa100644 0 0 26105 10661532627 31243 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.cookie.CookieAttributeHandler (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.cookie.CookieAttributeHandler

Packages that use CookieAttributeHandler
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
 

Uses of CookieAttributeHandler in org.apache.commons.httpclient.cookie
 

Methods in org.apache.commons.httpclient.cookie that return CookieAttributeHandler
protected  CookieAttributeHandler RFC2965Spec.findAttribHandler(String name)
          Finds an attribute handler CookieAttributeHandler for the given attribute.
protected  CookieAttributeHandler RFC2965Spec.getAttribHandler(String name)
          Gets attribute handler CookieAttributeHandler for the given attribute.
 

Methods in org.apache.commons.httpclient.cookie with parameters of type CookieAttributeHandler
protected  void RFC2965Spec.registerAttribHandler(String name, CookieAttributeHandler handler)
           
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookieOrigin.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookieOrigin.html100644 0 0 22661 10661532627 31224 0ustar 0 0 Uses of Class org.apache.commons.httpclient.cookie.CookieOrigin (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.cookie.CookieOrigin

Packages that use CookieOrigin
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
 

Uses of CookieOrigin in org.apache.commons.httpclient.cookie
 

Methods in org.apache.commons.httpclient.cookie with parameters of type CookieOrigin
 boolean CookieAttributeHandler.match(Cookie cookie, CookieOrigin origin)
          Matches the given value (property of the destination host where request is being submitted) with the corresponding cookie attribute.
 void CookieAttributeHandler.validate(Cookie cookie, CookieOrigin origin)
          Peforms cookie validation for the given attribute value.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookiePathComparator.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookiePathCompara100644 0 0 14116 10661532627 31225 0ustar 0 0 Uses of Class org.apache.commons.httpclient.cookie.CookiePathComparator (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.cookie.CookiePathComparator

No usage of org.apache.commons.httpclient.cookie.CookiePathComparator



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookiePolicy.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookiePolicy.html100644 0 0 13776 10661532627 31243 0ustar 0 0 Uses of Class org.apache.commons.httpclient.cookie.CookiePolicy (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.cookie.CookiePolicy

No usage of org.apache.commons.httpclient.cookie.CookiePolicy



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookieSpec.html100644 0 0 41433 10661532627 30665 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.cookie.CookieSpec (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.cookie.CookieSpec

Packages that use CookieSpec
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
 

Uses of CookieSpec in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient with parameters of type CookieSpec
protected  void HttpMethodBase.processCookieHeaders(CookieSpec parser, Header[] headers, HttpState state, HttpConnection conn)
          This method processes the specified cookie headers.
 

Uses of CookieSpec in org.apache.commons.httpclient.cookie
 

Classes in org.apache.commons.httpclient.cookie that implement CookieSpec
 class CookieSpecBase
          Cookie management functions shared by all specification.
 class IgnoreCookiesSpec
          A cookie spec that does nothing.
 class NetscapeDraftSpec
          Netscape cookie draft specific cookie management functions
 class RFC2109Spec
          RFC 2109 specific cookie management functions
 class RFC2965Spec
          RFC 2965 specific cookie management functions.
 

Methods in org.apache.commons.httpclient.cookie that return CookieSpec
static CookieSpec CookiePolicy.getCompatibilitySpec()
          Deprecated. Use CookiePolicy.getCookieSpec(String)
static CookieSpec CookiePolicy.getCookieSpec(String id)
          Gets the cookie specification with the given ID.
static CookieSpec CookiePolicy.getDefaultSpec()
          Returns cookie specification registered as CookiePolicy.DEFAULT.
static CookieSpec CookiePolicy.getSpecByPolicy(int policy)
          Deprecated. Use CookiePolicy.getCookieSpec(String)
static CookieSpec CookiePolicy.getSpecByVersion(int ver)
          Deprecated. Use CookiePolicy.getCookieSpec(String)
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookieSpecBase.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookieSpecBase.ht100644 0 0 22024 10661532627 31122 0ustar 0 0 Uses of Class org.apache.commons.httpclient.cookie.CookieSpecBase (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.cookie.CookieSpecBase

Packages that use CookieSpecBase
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
 

Uses of CookieSpecBase in org.apache.commons.httpclient.cookie
 

Subclasses of CookieSpecBase in org.apache.commons.httpclient.cookie
 class NetscapeDraftSpec
          Netscape cookie draft specific cookie management functions
 class RFC2109Spec
          RFC 2109 specific cookie management functions
 class RFC2965Spec
          RFC 2965 specific cookie management functions.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookieVersionSupport.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/CookieVersionSupp100644 0 0 20422 10661532627 31320 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.cookie.CookieVersionSupport (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.cookie.CookieVersionSupport

Packages that use CookieVersionSupport
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
 

Uses of CookieVersionSupport in org.apache.commons.httpclient.cookie
 

Classes in org.apache.commons.httpclient.cookie that implement CookieVersionSupport
 class RFC2965Spec
          RFC 2965 specific cookie management functions.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/IgnoreCookiesSpec.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/IgnoreCookiesSpec100644 0 0 14060 10661532627 31245 0ustar 0 0 Uses of Class org.apache.commons.httpclient.cookie.IgnoreCookiesSpec (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.cookie.IgnoreCookiesSpec

No usage of org.apache.commons.httpclient.cookie.IgnoreCookiesSpec



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 161 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/MalformedCookieException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/MalformedCookieEx100644 0 0 76665 10661532627 31252 0ustar 0 0 Uses of Class org.apache.commons.httpclient.cookie.MalformedCookieException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.cookie.MalformedCookieException

Packages that use MalformedCookieException
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
 

Uses of MalformedCookieException in org.apache.commons.httpclient.cookie
 

Methods in org.apache.commons.httpclient.cookie that throw MalformedCookieException
 void CookieAttributeHandler.parse(Cookie cookie, String value)
          Parse the given cookie attribute value and update the corresponding Cookie property.
 Cookie[] RFC2965Spec.parse(String host, int port, String path, boolean secure, Header header)
          Parses the Set-Cookie2 value into an array of Cookies.
 Cookie[] IgnoreCookiesSpec.parse(String host, int port, String path, boolean secure, Header header)
          Returns an empty cookie array.
 Cookie[] CookieSpecBase.parse(String host, int port, String path, boolean secure, Header header)
          Parse the "Set-Cookie" Header into an array of Cookies.
 Cookie[] CookieSpec.parse(String host, int port, String path, boolean secure, Header header)
          Parse the "Set-Cookie" Header into an array of Cookies.
 Cookie[] RFC2965Spec.parse(String host, int port, String path, boolean secure, String header)
           
 Cookie[] NetscapeDraftSpec.parse(String host, int port, String path, boolean secure, String header)
          Parses the Set-Cookie value into an array of Cookies.
 Cookie[] IgnoreCookiesSpec.parse(String host, int port, String path, boolean secure, String header)
          Returns an empty cookie array.
 Cookie[] CookieSpecBase.parse(String host, int port, String path, boolean secure, String header)
          Parses the Set-Cookie value into an array of Cookies.
 Cookie[] CookieSpec.parse(String host, int port, String path, boolean secure, String header)
          Parse the "Set-Cookie" header value into Cookie array.
 void RFC2965Spec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse RFC 2965 specific cookie attribute and update the corresponsing Cookie properties.
 void RFC2109Spec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse RFC 2109 specific cookie attribute and update the corresponsing Cookie properties.
 void NetscapeDraftSpec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties as defined by the Netscape draft specification
 void IgnoreCookiesSpec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Does nothing.
 void CookieSpecBase.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties.
 void CookieSpec.parseAttribute(NameValuePair attribute, Cookie cookie)
          Parse the cookie attribute and update the corresponsing Cookie properties.
 void CookieAttributeHandler.validate(Cookie cookie, CookieOrigin origin)
          Peforms cookie validation for the given attribute value.
 void RFC2965Spec.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs RFC 2965 compliant Cookie validation
 void RFC2109Spec.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs RFC 2109 compliant Cookie validation
 void NetscapeDraftSpec.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs Netscape draft compliant Cookie validation
 void IgnoreCookiesSpec.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Does nothing.
 void CookieSpecBase.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Performs most common Cookie validation
 void CookieSpec.validate(String host, int port, String path, boolean secure, Cookie cookie)
          Validate the cookie according to validation rules defined by the cookie specification.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/NetscapeDraftSpec.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/NetscapeDraftSpec100644 0 0 14060 10661532627 31230 0ustar 0 0 Uses of Class org.apache.commons.httpclient.cookie.NetscapeDraftSpec (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.cookie.NetscapeDraftSpec

No usage of org.apache.commons.httpclient.cookie.NetscapeDraftSpec



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/RFC2109Spec.html100644 0 0 13764 10661532627 30410 0ustar 0 0 Uses of Class org.apache.commons.httpclient.cookie.RFC2109Spec (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.cookie.RFC2109Spec

No usage of org.apache.commons.httpclient.cookie.RFC2109Spec



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/class-use/RFC2965Spec.html100644 0 0 13764 10661532627 30422 0ustar 0 0 Uses of Class org.apache.commons.httpclient.cookie.RFC2965Spec (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.cookie.RFC2965Spec

No usage of org.apache.commons.httpclient.cookie.RFC2965Spec



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/package-frame.html100644 0 0 5746 10661532627 27414 0ustar 0 0 org.apache.commons.httpclient.cookie (HttpClient 3.1 API) org.apache.commons.httpclient.cookie
Interfaces 
CookieAttributeHandler
CookieSpec
CookieVersionSupport
Classes 
Cookie2
CookieOrigin
CookiePathComparator
CookiePolicy
CookieSpecBase
IgnoreCookiesSpec
NetscapeDraftSpec
RFC2109Spec
RFC2965Spec
Exceptions 
MalformedCookieException
commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/package-summary.html100644 0 0 27037 10661532627 30034 0ustar 0 0 org.apache.commons.httpclient.cookie (HttpClient 3.1 API)

Package org.apache.commons.httpclient.cookie

Provides cookie handling in conjunction with Cookie.

See:
          Description

Interface Summary
CookieAttributeHandler Ths interface represents a cookie attribute handler responsible for parsing, validating, and matching a specific cookie attribute, such as path, domain, port, etc.
CookieSpec Defines the cookie management specification.
CookieVersionSupport Defines cookie specification specific capabilities
 

Class Summary
Cookie2 Cookie class for RFC2965Spec cookie specification.
CookieOrigin CookieOrigin class incapsulates details of an origin server that are relevant when parsing, validating or matching HTTP cookies.
CookiePathComparator This cookie comparator ensures that multiple cookies satisfying a common criteria are ordered in the Cookie header such that those with more specific Path attributes precede those with less specific.
CookiePolicy Cookie management policy class.
CookieSpecBase Cookie management functions shared by all specification.
IgnoreCookiesSpec A cookie spec that does nothing.
NetscapeDraftSpec Netscape cookie draft specific cookie management functions
RFC2109Spec RFC 2109 specific cookie management functions
RFC2965Spec RFC 2965 specific cookie management functions.
 

Exception Summary
MalformedCookieException Signals that a cookie is in some way invalid or illegal in a given context
 

Package org.apache.commons.httpclient.cookie Description

Provides cookie handling in conjunction with Cookie.

Since:
2.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/package-tree.html100644 0 0 27175 10661532627 27301 0ustar 0 0 org.apache.commons.httpclient.cookie Class Hierarchy (HttpClient 3.1 API)

Hierarchy For Package org.apache.commons.httpclient.cookie

Package Hierarchies:
All Packages

Class Hierarchy

Interface Hierarchy



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/cookie/package-use.html100644 0 0 24001 10661532627 27117 0ustar 0 0 Uses of Package org.apache.commons.httpclient.cookie (HttpClient 3.1 API)

Uses of Package
org.apache.commons.httpclient.cookie

Packages that use org.apache.commons.httpclient.cookie
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
 

Classes in org.apache.commons.httpclient.cookie used by org.apache.commons.httpclient
CookieSpec
          Defines the cookie management specification.
 

Classes in org.apache.commons.httpclient.cookie used by org.apache.commons.httpclient.cookie
CookieAttributeHandler
          Ths interface represents a cookie attribute handler responsible for parsing, validating, and matching a specific cookie attribute, such as path, domain, port, etc.
CookieOrigin
          CookieOrigin class incapsulates details of an origin server that are relevant when parsing, validating or matching HTTP cookies.
CookieSpec
          Defines the cookie management specification.
CookieSpecBase
          Cookie management functions shared by all specification.
CookieVersionSupport
          Defines cookie specification specific capabilities
MalformedCookieException
          Signals that a cookie is in some way invalid or illegal in a given context
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/ByteArrayRequestEntity.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/ByteArrayRequestEntity.htm100644 0 0 47617 10661532627 31442 0ustar 0 0 ByteArrayRequestEntity (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class ByteArrayRequestEntity

java.lang.Object
  extended by org.apache.commons.httpclient.methods.ByteArrayRequestEntity
All Implemented Interfaces:
RequestEntity

public class ByteArrayRequestEntity
extends Object
implements RequestEntity

A RequestEntity that contains an array of bytes.

Since:
3.0

Constructor Summary
ByteArrayRequestEntity(byte[] content)
          Creates a new entity with the given content.
ByteArrayRequestEntity(byte[] content, String contentType)
          Creates a new entity with the given content and content type.
 
Method Summary
 byte[] getContent()
           
 long getContentLength()
          Gets the request entity's length.
 String getContentType()
          Gets the entity's content type.
 boolean isRepeatable()
          Tests if RequestEntity.writeRequest(OutputStream) can be called more than once.
 void writeRequest(OutputStream out)
          Writes the request entity to the given stream.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ByteArrayRequestEntity

public ByteArrayRequestEntity(byte[] content)
Creates a new entity with the given content.

Parameters:
content - The content to set.

ByteArrayRequestEntity

public ByteArrayRequestEntity(byte[] content,
                              String contentType)
Creates a new entity with the given content and content type.

Parameters:
content - The content to set.
contentType - The content type to set or null.
Method Detail

isRepeatable

public boolean isRepeatable()
Description copied from interface: RequestEntity
Tests if RequestEntity.writeRequest(OutputStream) can be called more than once.

Specified by:
isRepeatable in interface RequestEntity
Returns:
true

getContentType

public String getContentType()
Description copied from interface: RequestEntity
Gets the entity's content type. This content type will be used as the value for the "Content-Type" header.

Specified by:
getContentType in interface RequestEntity
Returns:
the entity's content type
See Also:
HttpMethod.setRequestHeader(String, String)

writeRequest

public void writeRequest(OutputStream out)
                  throws IOException
Description copied from interface: RequestEntity
Writes the request entity to the given stream.

Specified by:
writeRequest in interface RequestEntity
Throws:
IOException

getContentLength

public long getContentLength()
Description copied from interface: RequestEntity
Gets the request entity's length. This method should return a non-negative value if the content length is known or a negative value if it is not. In the latter case the EntityEnclosingMethod will use chunk encoding to transmit the request entity.

Specified by:
getContentLength in interface RequestEntity
Returns:
The length of the content.

getContent

public byte[] getContent()
Returns:
Returns the content.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/DeleteMethod.html100644 0 0 72304 10661532627 27500 0ustar 0 0 DeleteMethod (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class DeleteMethod

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
      extended by org.apache.commons.httpclient.methods.DeleteMethod
All Implemented Interfaces:
HttpMethod

public class DeleteMethod
extends HttpMethodBase

Implements the HTTP DELETE method.

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

The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server.

Since:
1.0
Version:
$Revision: 480424 $
Author:
Remy Maucherat, B.C. Holmes, Jeff Dever

Field Summary
 
Fields inherited from class org.apache.commons.httpclient.HttpMethodBase
effectiveVersion, statusLine
 
Constructor Summary
DeleteMethod()
          No-arg constructor.
DeleteMethod(String uri)
          Constructor specifying a URI.
 
Method Summary
 String getName()
          Returns "DELETE".
 
Methods inherited from class org.apache.commons.httpclient.HttpMethodBase
abort, addCookieRequestHeader, addHostRequestHeader, addProxyConnectionHeader, addRequestHeader, addRequestHeader, addRequestHeaders, addResponseFooter, addUserAgentRequestHeader, checkNotUsed, checkUsed, execute, generateRequestLine, getAuthenticationRealm, getContentCharSet, getDoAuthentication, getEffectiveVersion, getFollowRedirects, getHostAuthState, getHostConfiguration, getMethodRetryHandler, getParams, getPath, getProxyAuthenticationRealm, getProxyAuthState, getQueryString, getRecoverableExceptionCount, getRequestCharSet, getRequestHeader, getRequestHeaderGroup, getRequestHeaders, getRequestHeaders, getResponseBody, getResponseBody, getResponseBodyAsStream, getResponseBodyAsString, getResponseBodyAsString, getResponseCharSet, getResponseContentLength, getResponseFooter, getResponseFooters, getResponseHeader, getResponseHeaderGroup, getResponseHeaders, getResponseHeaders, getResponseStream, getResponseTrailerHeaderGroup, getStatusCode, getStatusLine, getStatusText, getURI, hasBeenUsed, isAborted, isConnectionCloseForced, isHttp11, isRequestSent, isStrictMode, processCookieHeaders, processResponseBody, processResponseHeaders, processStatusLine, readResponse, readResponseBody, readResponseHeaders, readStatusLine, recycle, releaseConnection, removeRequestHeader, removeRequestHeader, responseBodyConsumed, setConnectionCloseForced, setDoAuthentication, setFollowRedirects, setHostConfiguration, setHttp11, setMethodRetryHandler, setParams, setPath, setQueryString, setQueryString, setRequestHeader, setRequestHeader, setResponseStream, setStrictMode, setURI, shouldCloseConnection, validate, writeRequest, writeRequestBody, writeRequestHeaders, writeRequestLine
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

DeleteMethod

public DeleteMethod()
No-arg constructor.

Since:
1.0

DeleteMethod

public DeleteMethod(String uri)
Constructor specifying a URI.

Parameters:
uri - either an absolute or relative URI
Since:
1.0
Method Detail

getName

public String getName()
Returns "DELETE".

Specified by:
getName in interface HttpMethod
Specified by:
getName in class HttpMethodBase
Returns:
"DELETE"
Since:
2.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/EntityEnclosingMethod.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/EntityEnclosingMethod.html100644 0 0 175755 10661532627 31452 0ustar 0 0 EntityEnclosingMethod (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class EntityEnclosingMethod

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
      extended by org.apache.commons.httpclient.methods.ExpectContinueMethod
          extended by org.apache.commons.httpclient.methods.EntityEnclosingMethod
All Implemented Interfaces:
HttpMethod
Direct Known Subclasses:
PostMethod, PutMethod

public abstract class EntityEnclosingMethod
extends ExpectContinueMethod

This abstract class serves as a foundation for all HTTP methods that can enclose an entity within requests

Since:
2.0beta1
Version:
$Revision: 480424 $
Author:
Oleg Kalnichevski, Jeff Dever

Field Summary
static long CONTENT_LENGTH_AUTO
          Deprecated. Use InputStreamRequestEntity.CONTENT_LENGTH_AUTO.
static long CONTENT_LENGTH_CHUNKED
          Deprecated. Use setContentChunked(boolean).
 
Fields inherited from class org.apache.commons.httpclient.HttpMethodBase
effectiveVersion, statusLine
 
Constructor Summary
EntityEnclosingMethod()
          No-arg constructor.
EntityEnclosingMethod(String uri)
          Constructor specifying a URI.
 
Method Summary
protected  void addContentLengthRequestHeader(HttpState state, HttpConnection conn)
          Generates Content-Length or Transfer-Encoding: Chunked request header, as long as no Content-Length request header already exists.
protected  void addRequestHeaders(HttpState state, HttpConnection conn)
          Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
protected  void clearRequestBody()
          Clears the request body.
protected  byte[] generateRequestBody()
          Generates the request body.
protected  RequestEntity generateRequestEntity()
           
 boolean getFollowRedirects()
          Entity enclosing requests cannot be redirected without user intervention according to RFC 2616.
 String getRequestCharSet()
          Returns the request's charset.
protected  long getRequestContentLength()
          Returns the length of the request body.
 RequestEntity getRequestEntity()
           
protected  boolean hasRequestContent()
          Returns true if there is a request body to be sent.
 void recycle()
          Deprecated. no longer supported and will be removed in the future version of HttpClient
 void setContentChunked(boolean chunked)
          Sets whether or not the content should be chunked.
 void setFollowRedirects(boolean followRedirects)
          Entity enclosing requests cannot be redirected without user intervention according to RFC 2616.
 void setRequestBody(InputStream body)
          Deprecated. use setRequestEntity(RequestEntity)
 void setRequestBody(String body)
          Deprecated. use setRequestEntity(RequestEntity)
 void setRequestContentLength(int length)
          Deprecated. Use setContentChunked(boolean) or setRequestEntity(RequestEntity)
 void setRequestContentLength(long length)
          Deprecated. Use setContentChunked(boolean) or setRequestEntity(RequestEntity)
 void setRequestEntity(RequestEntity requestEntity)
           
protected  boolean writeRequestBody(HttpState state, HttpConnection conn)
          Writes the request body to the given connection.
 
Methods inherited from class org.apache.commons.httpclient.methods.ExpectContinueMethod
getUseExpectHeader, setUseExpectHeader
 
Methods inherited from class org.apache.commons.httpclient.HttpMethodBase
abort, addCookieRequestHeader, addHostRequestHeader, addProxyConnectionHeader, addRequestHeader, addRequestHeader, addResponseFooter, addUserAgentRequestHeader, checkNotUsed, checkUsed, execute, generateRequestLine, getAuthenticationRealm, getContentCharSet, getDoAuthentication, getEffectiveVersion, getHostAuthState, getHostConfiguration, getMethodRetryHandler, getName, getParams, getPath, getProxyAuthenticationRealm, getProxyAuthState, getQueryString, getRecoverableExceptionCount, getRequestHeader, getRequestHeaderGroup, getRequestHeaders, getRequestHeaders, getResponseBody, getResponseBody, getResponseBodyAsStream, getResponseBodyAsString, getResponseBodyAsString, getResponseCharSet, getResponseContentLength, getResponseFooter, getResponseFooters, getResponseHeader, getResponseHeaderGroup, getResponseHeaders, getResponseHeaders, getResponseStream, getResponseTrailerHeaderGroup, getStatusCode, getStatusLine, getStatusText, getURI, hasBeenUsed, isAborted, isConnectionCloseForced, isHttp11, isRequestSent, isStrictMode, processCookieHeaders, processResponseBody, processResponseHeaders, processStatusLine, readResponse, readResponseBody, readResponseHeaders, readStatusLine, releaseConnection, removeRequestHeader, removeRequestHeader, responseBodyConsumed, setConnectionCloseForced, setDoAuthentication, setHostConfiguration, setHttp11, setMethodRetryHandler, setParams, setPath, setQueryString, setQueryString, setRequestHeader, setRequestHeader, setResponseStream, setStrictMode, setURI, shouldCloseConnection, validate, writeRequest, writeRequestHeaders, writeRequestLine
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

CONTENT_LENGTH_AUTO

public static final long CONTENT_LENGTH_AUTO
Deprecated. Use InputStreamRequestEntity.CONTENT_LENGTH_AUTO.
The content length will be calculated automatically. This implies buffering of the content.

See Also:
Constant Field Values

CONTENT_LENGTH_CHUNKED

public static final long CONTENT_LENGTH_CHUNKED
Deprecated. Use setContentChunked(boolean).
The request will use chunked transfer encoding. Content length is not calculated and the content is not buffered.

See Also:
Constant Field Values
Constructor Detail

EntityEnclosingMethod

public EntityEnclosingMethod()
No-arg constructor.

Since:
2.0

EntityEnclosingMethod

public EntityEnclosingMethod(String uri)
Constructor specifying a URI.

Parameters:
uri - either an absolute or relative URI
Since:
2.0
Method Detail

hasRequestContent

protected boolean hasRequestContent()
Returns true if there is a request body to be sent.

This method must be overridden by sub-classes that implement alternative request content input methods

Specified by:
hasRequestContent in class ExpectContinueMethod
Returns:
boolean
Since:
2.0beta1

clearRequestBody

protected void clearRequestBody()
Clears the request body.

This method must be overridden by sub-classes that implement alternative request content input methods.

Since:
2.0beta1

generateRequestBody

protected byte[] generateRequestBody()
Generates the request body.

This method must be overridden by sub-classes that implement alternative request content input methods.

Returns:
request body as an array of bytes. If the request content has not been set, returns null.
Since:
2.0beta1

generateRequestEntity

protected RequestEntity generateRequestEntity()

getFollowRedirects

public boolean getFollowRedirects()
Entity enclosing requests cannot be redirected without user intervention according to RFC 2616.

Specified by:
getFollowRedirects in interface HttpMethod
Overrides:
getFollowRedirects in class HttpMethodBase
Returns:
false.
Since:
2.0

setFollowRedirects

public void setFollowRedirects(boolean followRedirects)
Entity enclosing requests cannot be redirected without user intervention according to RFC 2616.

Specified by:
setFollowRedirects in interface HttpMethod
Overrides:
setFollowRedirects in class HttpMethodBase
Parameters:
followRedirects - must always be false

setRequestContentLength

public void setRequestContentLength(int length)
Deprecated. Use setContentChunked(boolean) or setRequestEntity(RequestEntity)

Sets length information about the request body.

Note: If you specify a content length the request is unbuffered. This prevents redirection and automatic retry if a request fails the first time. This means that the HttpClient can not perform authorization automatically but will throw an Exception. You will have to set the necessary 'Authorization' or 'Proxy-Authorization' headers manually.

Parameters:
length - size in bytes or any of CONTENT_LENGTH_AUTO, CONTENT_LENGTH_CHUNKED. If number of bytes or CONTENT_LENGTH_CHUNKED is specified the content will not be buffered internally and the Content-Length header of the request will be used. In this case the user is responsible to supply the correct content length. If CONTENT_LENGTH_AUTO is specified the request will be buffered before it is sent over the network.

getRequestCharSet

public String getRequestCharSet()
Returns the request's charset. The charset is parsed from the request entity's content type, unless the content type header has been set manually.

Overrides:
getRequestCharSet in class HttpMethodBase
Returns:
String The character set.
Since:
3.0
See Also:
RequestEntity.getContentType()

setRequestContentLength

public void setRequestContentLength(long length)
Deprecated. Use setContentChunked(boolean) or setRequestEntity(RequestEntity)

Sets length information about the request body.

Note: If you specify a content length the request is unbuffered. This prevents redirection and automatic retry if a request fails the first time. This means that the HttpClient can not perform authorization automatically but will throw an Exception. You will have to set the necessary 'Authorization' or 'Proxy-Authorization' headers manually.

Parameters:
length - size in bytes or any of CONTENT_LENGTH_AUTO, CONTENT_LENGTH_CHUNKED. If number of bytes or CONTENT_LENGTH_CHUNKED is specified the content will not be buffered internally and the Content-Length header of the request will be used. In this case the user is responsible to supply the correct content length. If CONTENT_LENGTH_AUTO is specified the request will be buffered before it is sent over the network.

setContentChunked

public void setContentChunked(boolean chunked)
Sets whether or not the content should be chunked.

Parameters:
chunked - true if the content should be chunked
Since:
3.0

getRequestContentLength

protected long getRequestContentLength()
Returns the length of the request body.

Returns:
number of bytes in the request body

addRequestHeaders

protected void addRequestHeaders(HttpState state,
                                 HttpConnection conn)
                          throws IOException,
                                 HttpException
Populates the request headers map to with additional headers to be submitted to the given HttpConnection.

This implementation adds tt>Content-Length or Transfer-Encoding headers.

Subclasses may want to override this method to to add additional headers, and may choose to invoke this implementation (via super) to add the "standard" headers.

Overrides:
addRequestHeaders in class ExpectContinueMethod
Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
Since:
3.0
See Also:
HttpMethodBase.writeRequestHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)

addContentLengthRequestHeader

protected void addContentLengthRequestHeader(HttpState state,
                                             HttpConnection conn)
                                      throws IOException,
                                             HttpException
Generates Content-Length or Transfer-Encoding: Chunked request header, as long as no Content-Length request header already exists.

Parameters:
state - current state of http requests
conn - the connection to use for I/O
Throws:
IOException - when errors occur reading or writing to/from the connection
HttpException - when a recoverable error occurs

setRequestBody

public void setRequestBody(InputStream body)
Deprecated. use setRequestEntity(RequestEntity)

Sets the request body to be the specified inputstream.

Parameters:
body - Request body content as InputStream

setRequestBody

public void setRequestBody(String body)
Deprecated. use setRequestEntity(RequestEntity)

Sets the request body to be the specified string. The string will be submitted, using the encoding specified in the Content-Type request header.
Example: setRequestHeader("Content-type", "text/xml; charset=UTF-8");
Would use the UTF-8 encoding. If no charset is specified, the default content encoding is used (ISO-8859-1).

Parameters:
body - Request body content as a string

writeRequestBody

protected boolean writeRequestBody(HttpState state,
                                   HttpConnection conn)
                            throws IOException,
                                   HttpException
Writes the request body to the given connection.

Overrides:
writeRequestBody in class HttpMethodBase
Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Returns:
true
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.

recycle

public void recycle()
Deprecated. no longer supported and will be removed in the future version of HttpClient

Recycles the HTTP method so that it can be used again. Note that all of the instance variables will be reset once this method has been called. This method will also release the connection being used by this HTTP method.

Specified by:
recycle in interface HttpMethod
Overrides:
recycle in class HttpMethodBase
See Also:
HttpMethodBase.releaseConnection()

getRequestEntity

public RequestEntity getRequestEntity()
Returns:
Returns the requestEntity.
Since:
3.0

setRequestEntity

public void setRequestEntity(RequestEntity requestEntity)
Parameters:
requestEntity - The requestEntity to set.
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/ExpectContinueMethod.html100644 0 0 112157 10661532627 31254 0ustar 0 0 ExpectContinueMethod (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class ExpectContinueMethod

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
      extended by org.apache.commons.httpclient.methods.ExpectContinueMethod
All Implemented Interfaces:
HttpMethod
Direct Known Subclasses:
EntityEnclosingMethod, MultipartPostMethod

public abstract class ExpectContinueMethod
extends HttpMethodBase

This abstract class serves as a foundation for all HTTP methods that support 'Expect: 100-continue' handshake.

The purpose of the 100 (Continue) status (refer to section 10.1.1 of the RFC 2616 for more details) 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. In some cases, it might either be inappropriate or highly inefficient for the client to send the body if the server will reject the message without looking at the body.

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

Since:
2.0beta1
Author:
Oleg Kalnichevski

Field Summary
 
Fields inherited from class org.apache.commons.httpclient.HttpMethodBase
effectiveVersion, statusLine
 
Constructor Summary
ExpectContinueMethod()
          No-arg constructor.
ExpectContinueMethod(String uri)
          Constructor specifying a URI.
 
Method Summary
protected  void addRequestHeaders(HttpState state, HttpConnection conn)
          Sets the Expect header if it has not already been set, in addition to the "standard" set of headers.
 boolean getUseExpectHeader()
          Deprecated. Use HttpMethodParams
protected abstract  boolean hasRequestContent()
          Returns true if there is a request body to be sent.
 void setUseExpectHeader(boolean value)
          Deprecated. Use HttpMethodParams
 
Methods inherited from class org.apache.commons.httpclient.HttpMethodBase
abort, addCookieRequestHeader, addHostRequestHeader, addProxyConnectionHeader, addRequestHeader, addRequestHeader, addResponseFooter, addUserAgentRequestHeader, checkNotUsed, checkUsed, execute, generateRequestLine, getAuthenticationRealm, getContentCharSet, getDoAuthentication, getEffectiveVersion, getFollowRedirects, getHostAuthState, getHostConfiguration, getMethodRetryHandler, getName, getParams, getPath, getProxyAuthenticationRealm, getProxyAuthState, getQueryString, getRecoverableExceptionCount, getRequestCharSet, getRequestHeader, getRequestHeaderGroup, getRequestHeaders, getRequestHeaders, getResponseBody, getResponseBody, getResponseBodyAsStream, getResponseBodyAsString, getResponseBodyAsString, getResponseCharSet, getResponseContentLength, getResponseFooter, getResponseFooters, getResponseHeader, getResponseHeaderGroup, getResponseHeaders, getResponseHeaders, getResponseStream, getResponseTrailerHeaderGroup, getStatusCode, getStatusLine, getStatusText, getURI, hasBeenUsed, isAborted, isConnectionCloseForced, isHttp11, isRequestSent, isStrictMode, processCookieHeaders, processResponseBody, processResponseHeaders, processStatusLine, readResponse, readResponseBody, readResponseHeaders, readStatusLine, recycle, releaseConnection, removeRequestHeader, removeRequestHeader, responseBodyConsumed, setConnectionCloseForced, setDoAuthentication, setFollowRedirects, setHostConfiguration, setHttp11, setMethodRetryHandler, setParams, setPath, setQueryString, setQueryString, setRequestHeader, setRequestHeader, setResponseStream, setStrictMode, setURI, shouldCloseConnection, validate, writeRequest, writeRequestBody, writeRequestHeaders, writeRequestLine
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ExpectContinueMethod

public ExpectContinueMethod()
No-arg constructor.

Since:
2.0

ExpectContinueMethod

public ExpectContinueMethod(String uri)
Constructor specifying a URI.

Parameters:
uri - either an absolute or relative URI
Since:
2.0
Method Detail

getUseExpectHeader

public boolean getUseExpectHeader()
Deprecated. Use HttpMethodParams

Returns true if the 'Expect: 100-Continue' handshake is activated. The purpose of the 'Expect: 100-Continue' handshake 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.

Returns:
true if 'Expect: 100-Continue' handshake is to be used, false otherwise.
Since:
2.0beta1
See Also:
HttpMethodBase.getParams(), HttpMethodParams, HttpMethodParams.USE_EXPECT_CONTINUE

setUseExpectHeader

public void setUseExpectHeader(boolean value)
Deprecated. Use HttpMethodParams

Activates 'Expect: 100-Continue' handshake. The purpose of the 'Expect: 100-Continue' handshake 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 noticable peformance 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.

Parameters:
value - boolean value
Since:
2.0beta1
See Also:
HttpMethodBase.getParams(), HttpMethodParams, HttpMethodParams.USE_EXPECT_CONTINUE

hasRequestContent

protected abstract boolean hasRequestContent()
Returns true if there is a request body to be sent. 'Expect: 100-continue' handshake may not be used if request body is not present

Returns:
boolean
Since:
2.0beta1

addRequestHeaders

protected void addRequestHeaders(HttpState state,
                                 HttpConnection conn)
                          throws IOException,
                                 HttpException
Sets the Expect header if it has not already been set, in addition to the "standard" set of headers.

Overrides:
addRequestHeaders in class HttpMethodBase
Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
See Also:
HttpMethodBase.writeRequestHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/FileRequestEntity.html100644 0 0 46124 10661532627 30563 0ustar 0 0 FileRequestEntity (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class FileRequestEntity

java.lang.Object
  extended by org.apache.commons.httpclient.methods.FileRequestEntity
All Implemented Interfaces:
RequestEntity

public class FileRequestEntity
extends Object
implements RequestEntity

A RequestEntity that represents a File.

Since:
3.1

Constructor Summary
FileRequestEntity(File file, String contentType)
           
 
Method Summary
 long getContentLength()
          Gets the request entity's length.
 String getContentType()
          Gets the entity's content type.
 boolean isRepeatable()
          Tests if RequestEntity.writeRequest(OutputStream) can be called more than once.
 void writeRequest(OutputStream out)
          Writes the request entity to the given stream.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

FileRequestEntity

public FileRequestEntity(File file,
                         String contentType)
Method Detail

getContentLength

public long getContentLength()
Description copied from interface: RequestEntity
Gets the request entity's length. This method should return a non-negative value if the content length is known or a negative value if it is not. In the latter case the EntityEnclosingMethod will use chunk encoding to transmit the request entity.

Specified by:
getContentLength in interface RequestEntity
Returns:
a non-negative value when content length is known or a negative value when content length is not known

getContentType

public String getContentType()
Description copied from interface: RequestEntity
Gets the entity's content type. This content type will be used as the value for the "Content-Type" header.

Specified by:
getContentType in interface RequestEntity
Returns:
the entity's content type
See Also:
HttpMethod.setRequestHeader(String, String)

isRepeatable

public boolean isRepeatable()
Description copied from interface: RequestEntity
Tests if RequestEntity.writeRequest(OutputStream) can be called more than once.

Specified by:
isRepeatable in interface RequestEntity
Returns:
true if the entity can be written to OutputStream more than once, false otherwise.

writeRequest

public void writeRequest(OutputStream out)
                  throws IOException
Description copied from interface: RequestEntity
Writes the request entity to the given stream.

Specified by:
writeRequest in interface RequestEntity
Throws:
IOException


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/GetMethod.html100644 0 0 76055 10661532627 27024 0ustar 0 0 GetMethod (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class GetMethod

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
      extended by org.apache.commons.httpclient.methods.GetMethod
All Implemented Interfaces:
HttpMethod

public class GetMethod
extends HttpMethodBase

Implements the HTTP GET method.

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

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.

GetMethods will follow redirect requests from the http server by default. This behavour can be disabled by calling setFollowRedirects(false).

Since:
1.0
Version:
$Revision: 480424 $
Author:
Remy Maucherat, Sung-Gu Park, Sean C. Sullivan, Mike Bowler, Jeff Dever

Field Summary
 
Fields inherited from class org.apache.commons.httpclient.HttpMethodBase
effectiveVersion, statusLine
 
Constructor Summary
GetMethod()
          No-arg constructor.
GetMethod(String uri)
          Constructor specifying a URI.
 
Method Summary
 String getName()
          Returns "GET".
 void recycle()
          Deprecated. no longer supported and will be removed in the future version of HttpClient
 
Methods inherited from class org.apache.commons.httpclient.HttpMethodBase
abort, addCookieRequestHeader, addHostRequestHeader, addProxyConnectionHeader, addRequestHeader, addRequestHeader, addRequestHeaders, addResponseFooter, addUserAgentRequestHeader, checkNotUsed, checkUsed, execute, generateRequestLine, getAuthenticationRealm, getContentCharSet, getDoAuthentication, getEffectiveVersion, getFollowRedirects, getHostAuthState, getHostConfiguration, getMethodRetryHandler, getParams, getPath, getProxyAuthenticationRealm, getProxyAuthState, getQueryString, getRecoverableExceptionCount, getRequestCharSet, getRequestHeader, getRequestHeaderGroup, getRequestHeaders, getRequestHeaders, getResponseBody, getResponseBody, getResponseBodyAsStream, getResponseBodyAsString, getResponseBodyAsString, getResponseCharSet, getResponseContentLength, getResponseFooter, getResponseFooters, getResponseHeader, getResponseHeaderGroup, getResponseHeaders, getResponseHeaders, getResponseStream, getResponseTrailerHeaderGroup, getStatusCode, getStatusLine, getStatusText, getURI, hasBeenUsed, isAborted, isConnectionCloseForced, isHttp11, isRequestSent, isStrictMode, processCookieHeaders, processResponseBody, processResponseHeaders, processStatusLine, readResponse, readResponseBody, readResponseHeaders, readStatusLine, releaseConnection, removeRequestHeader, removeRequestHeader, responseBodyConsumed, setConnectionCloseForced, setDoAuthentication, setFollowRedirects, setHostConfiguration, setHttp11, setMethodRetryHandler, setParams, setPath, setQueryString, setQueryString, setRequestHeader, setRequestHeader, setResponseStream, setStrictMode, setURI, shouldCloseConnection, validate, writeRequest, writeRequestBody, writeRequestHeaders, writeRequestLine
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

GetMethod

public GetMethod()
No-arg constructor.

Since:
1.0

GetMethod

public GetMethod(String uri)
Constructor specifying a URI.

Parameters:
uri - either an absolute or relative URI
Since:
1.0
Method Detail

getName

public String getName()
Returns "GET".

Specified by:
getName in interface HttpMethod
Specified by:
getName in class HttpMethodBase
Returns:
"GET"
Since:
2.0

recycle

public void recycle()
Deprecated. no longer supported and will be removed in the future version of HttpClient

Recycles the HTTP method so that it can be used again. Note that all of the instance variables will be reset once this method has been called. This method will also release the connection being used by this HTTP method.

Specified by:
recycle in interface HttpMethod
Overrides:
recycle in class HttpMethodBase
Since:
1.0
See Also:
HttpMethodBase.releaseConnection()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/HeadMethod.html100644 0 0 115140 10661532627 27153 0ustar 0 0 HeadMethod (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class HeadMethod

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
      extended by org.apache.commons.httpclient.methods.HeadMethod
All Implemented Interfaces:
HttpMethod

public class HeadMethod
extends HttpMethodBase

Implements the HTTP HEAD method.

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

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

Since:
1.0
Version:
$Revision: 480424 $
Author:
Remy Maucherat, Mike Bowler, Jeff Dever, oleg Kalnichevski

Field Summary
 
Fields inherited from class org.apache.commons.httpclient.HttpMethodBase
effectiveVersion, statusLine
 
Constructor Summary
HeadMethod()
          No-arg constructor.
HeadMethod(String uri)
          Constructor specifying a URI.
 
Method Summary
 int getBodyCheckTimeout()
          Deprecated. Use HttpMethodParams
 String getName()
          Returns "HEAD".
protected  void readResponseBody(HttpState state, HttpConnection conn)
          Overrides HttpMethodBase method to not read a response body, despite the presence of a Content-Length or Transfer-Encoding header.
 void recycle()
          Deprecated. no longer supported and will be removed in the future version of HttpClient
 void setBodyCheckTimeout(int timeout)
          Deprecated. Use HttpMethodParams
 
Methods inherited from class org.apache.commons.httpclient.HttpMethodBase
abort, addCookieRequestHeader, addHostRequestHeader, addProxyConnectionHeader, addRequestHeader, addRequestHeader, addRequestHeaders, addResponseFooter, addUserAgentRequestHeader, checkNotUsed, checkUsed, execute, generateRequestLine, getAuthenticationRealm, getContentCharSet, getDoAuthentication, getEffectiveVersion, getFollowRedirects, getHostAuthState, getHostConfiguration, getMethodRetryHandler, getParams, getPath, getProxyAuthenticationRealm, getProxyAuthState, getQueryString, getRecoverableExceptionCount, getRequestCharSet, getRequestHeader, getRequestHeaderGroup, getRequestHeaders, getRequestHeaders, getResponseBody, getResponseBody, getResponseBodyAsStream, getResponseBodyAsString, getResponseBodyAsString, getResponseCharSet, getResponseContentLength, getResponseFooter, getResponseFooters, getResponseHeader, getResponseHeaderGroup, getResponseHeaders, getResponseHeaders, getResponseStream, getResponseTrailerHeaderGroup, getStatusCode, getStatusLine, getStatusText, getURI, hasBeenUsed, isAborted, isConnectionCloseForced, isHttp11, isRequestSent, isStrictMode, processCookieHeaders, processResponseBody, processResponseHeaders, processStatusLine, readResponse, readResponseHeaders, readStatusLine, releaseConnection, removeRequestHeader, removeRequestHeader, responseBodyConsumed, setConnectionCloseForced, setDoAuthentication, setFollowRedirects, setHostConfiguration, setHttp11, setMethodRetryHandler, setParams, setPath, setQueryString, setQueryString, setRequestHeader, setRequestHeader, setResponseStream, setStrictMode, setURI, shouldCloseConnection, validate, writeRequest, writeRequestBody, writeRequestHeaders, writeRequestLine
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

HeadMethod

public HeadMethod()
No-arg constructor.

Since:
1.0

HeadMethod

public HeadMethod(String uri)
Constructor specifying a URI.

Parameters:
uri - either an absolute or relative URI
Since:
1.0
Method Detail

getName

public String getName()
Returns "HEAD".

Specified by:
getName in interface HttpMethod
Specified by:
getName in class HttpMethodBase
Returns:
"HEAD"
Since:
2.0

recycle

public void recycle()
Deprecated. no longer supported and will be removed in the future version of HttpClient

Recycles the HTTP method so that it can be used again. Note that all of the instance variables will be reset once this method has been called. This method will also release the connection being used by this HTTP method.

Specified by:
recycle in interface HttpMethod
Overrides:
recycle in class HttpMethodBase
Since:
1.0
See Also:
HttpMethodBase.releaseConnection()

readResponseBody

protected void readResponseBody(HttpState state,
                                HttpConnection conn)
                         throws HttpException,
                                IOException
Overrides HttpMethodBase method to not read a response body, despite the presence of a Content-Length or Transfer-Encoding header.

Overrides:
readResponseBody in class HttpMethodBase
Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
Since:
2.0
See Also:
HttpMethodBase.readResponse(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection), HttpMethodBase.processResponseBody(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)

getBodyCheckTimeout

public int getBodyCheckTimeout()
Deprecated. Use HttpMethodParams

Returns non-compliant response body check timeout.

Returns:
The period of time in milliseconds to wait for a response body from a non-compliant server. -1 returned when non-compliant response body check is disabled
See Also:
HttpMethodBase.getParams(), HttpMethodParams, HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT

setBodyCheckTimeout

public void setBodyCheckTimeout(int timeout)
Deprecated. Use HttpMethodParams

Sets non-compliant response body check timeout.

Parameters:
timeout - The period of time in milliseconds to wait for a response body from a non-compliant server. -1 can be used to disable non-compliant response body check
See Also:
HttpMethodBase.getParams(), HttpMethodParams, HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/InputStreamRequestEntity.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/InputStreamRequestEntity.h100644 0 0 64771 10661532627 31452 0ustar 0 0 InputStreamRequestEntity (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class InputStreamRequestEntity

java.lang.Object
  extended by org.apache.commons.httpclient.methods.InputStreamRequestEntity
All Implemented Interfaces:
RequestEntity

public class InputStreamRequestEntity
extends Object
implements RequestEntity

A RequestEntity that contains an InputStream.

Since:
3.0

Field Summary
static int CONTENT_LENGTH_AUTO
          The content length will be calculated automatically.
 
Constructor Summary
InputStreamRequestEntity(InputStream content)
          Creates a new InputStreamRequestEntity with the given content and a content type of CONTENT_LENGTH_AUTO.
InputStreamRequestEntity(InputStream content, long contentLength)
          Creates a new InputStreamRequestEntity with the given content and content length.
InputStreamRequestEntity(InputStream content, long contentLength, String contentType)
          Creates a new InputStreamRequestEntity with the given content, content length, and content type.
InputStreamRequestEntity(InputStream content, String contentType)
          Creates a new InputStreamRequestEntity with the given content, content type, and a content length of CONTENT_LENGTH_AUTO.
 
Method Summary
 InputStream getContent()
           
 long getContentLength()
          Gets the content length.
 String getContentType()
          Gets the entity's content type.
 boolean isRepeatable()
          Tests if this method is repeatable.
 void writeRequest(OutputStream out)
          Writes the request entity to the given stream.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

CONTENT_LENGTH_AUTO

public static final int CONTENT_LENGTH_AUTO
The content length will be calculated automatically. This implies buffering of the content.

See Also:
Constant Field Values
Constructor Detail

InputStreamRequestEntity

public InputStreamRequestEntity(InputStream content)
Creates a new InputStreamRequestEntity with the given content and a content type of CONTENT_LENGTH_AUTO.

Parameters:
content - The content to set.

InputStreamRequestEntity

public InputStreamRequestEntity(InputStream content,
                                String contentType)
Creates a new InputStreamRequestEntity with the given content, content type, and a content length of CONTENT_LENGTH_AUTO.

Parameters:
content - The content to set.
contentType - The type of the content, or null.

InputStreamRequestEntity

public InputStreamRequestEntity(InputStream content,
                                long contentLength)
Creates a new InputStreamRequestEntity with the given content and content length.

Parameters:
content - The content to set.
contentLength - The content size in bytes or a negative number if not known. If CONTENT_LENGTH_AUTO is given the content will be buffered in order to determine its size when getContentLength() is called.

InputStreamRequestEntity

public InputStreamRequestEntity(InputStream content,
                                long contentLength,
                                String contentType)
Creates a new InputStreamRequestEntity with the given content, content length, and content type.

Parameters:
content - The content to set.
contentLength - The content size in bytes or a negative number if not known. If CONTENT_LENGTH_AUTO is given the content will be buffered in order to determine its size when getContentLength() is called.
contentType - The type of the content, or null.
Method Detail

getContentType

public String getContentType()
Description copied from interface: RequestEntity
Gets the entity's content type. This content type will be used as the value for the "Content-Type" header.

Specified by:
getContentType in interface RequestEntity
Returns:
the entity's content type
See Also:
HttpMethod.setRequestHeader(String, String)

isRepeatable

public boolean isRepeatable()
Tests if this method is repeatable. Only true if the content has been buffered.

Specified by:
isRepeatable in interface RequestEntity
Returns:
true if the entity can be written to OutputStream more than once, false otherwise.
See Also:
getContentLength()

writeRequest

public void writeRequest(OutputStream out)
                  throws IOException
Description copied from interface: RequestEntity
Writes the request entity to the given stream.

Specified by:
writeRequest in interface RequestEntity
Throws:
IOException

getContentLength

public long getContentLength()
Gets the content length. If the content length has not been set, the content will be buffered to determine the actual content length.

Specified by:
getContentLength in interface RequestEntity
Returns:
a non-negative value when content length is known or a negative value when content length is not known

getContent

public InputStream getContent()
Returns:
Returns the content.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/MultipartPostMethod.html100644 0 0 161710 10661532627 31145 0ustar 0 0 MultipartPostMethod (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class MultipartPostMethod

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
      extended by org.apache.commons.httpclient.methods.ExpectContinueMethod
          extended by org.apache.commons.httpclient.methods.MultipartPostMethod
All Implemented Interfaces:
HttpMethod

Deprecated. Use MultipartRequestEntity in conjunction with PostMethod instead.

public class MultipartPostMethod
extends ExpectContinueMethod

Implements the HTTP multipart POST method.

The HTTP multipart POST method is defined in section 3.3 of RFC1867:

The media-type multipart/form-data follows the rules of all multipart MIME data streams as outlined in RFC 1521. The multipart/form-data contains a series of parts. Each part is expected to contain a content-disposition header where the value is "form-data" and a name attribute specifies the field name within the form, e.g., 'content-disposition: form-data; name="xxxxx"', where xxxxx is the field name corresponding to that field. Field names originally in non-ASCII character sets may be encoded using the method outlined in RFC 1522.

Since:
2.0
Author:
Matthew Albright, Jeff Dever, Adrian Sutton, Mark Diggory, Mike Bowler, Oleg Kalnichevski

Field Summary
static String MULTIPART_FORM_CONTENT_TYPE
          Deprecated. The Content-Type for multipart/form-data.
 
Fields inherited from class org.apache.commons.httpclient.HttpMethodBase
effectiveVersion, statusLine
 
Constructor Summary
MultipartPostMethod()
          Deprecated. No-arg constructor.
MultipartPostMethod(String uri)
          Deprecated. Constructor specifying a URI.
 
Method Summary
protected  void addContentLengthRequestHeader(HttpState state, HttpConnection conn)
          Deprecated. Adds a Content-Length request header, as long as no Content-Length request header already exists.
protected  void addContentTypeRequestHeader(HttpState state, HttpConnection conn)
          Deprecated. Adds a Content-Type request header.
 void addParameter(String parameterName, File parameterFile)
          Deprecated. Adds a binary file part
 void addParameter(String parameterName, String parameterValue)
          Deprecated. Adds a text field part
 void addParameter(String parameterName, String fileName, File parameterFile)
          Deprecated. Adds a binary file part with the given file name
 void addPart(Part part)
          Deprecated. Adds a part.
protected  void addRequestHeaders(HttpState state, HttpConnection conn)
          Deprecated. Populates the request headers map to with additional headers to be submitted to the given HttpConnection.
 String getName()
          Deprecated. Returns "POST".
 Part[] getParts()
          Deprecated. Returns all parts.
protected  long getRequestContentLength()
          Deprecated. Return the length of the request body.
protected  boolean hasRequestContent()
          Deprecated. Returns true
 void recycle()
          Deprecated. no longer supported and will be removed in the future version of HttpClient
protected  boolean writeRequestBody(HttpState state, HttpConnection conn)
          Deprecated. Writes the request body to the given connection.
 
Methods inherited from class org.apache.commons.httpclient.methods.ExpectContinueMethod
getUseExpectHeader, setUseExpectHeader
 
Methods inherited from class org.apache.commons.httpclient.HttpMethodBase
abort, addCookieRequestHeader, addHostRequestHeader, addProxyConnectionHeader, addRequestHeader, addRequestHeader, addResponseFooter, addUserAgentRequestHeader, checkNotUsed, checkUsed, execute, generateRequestLine, getAuthenticationRealm, getContentCharSet, getDoAuthentication, getEffectiveVersion, getFollowRedirects, getHostAuthState, getHostConfiguration, getMethodRetryHandler, getParams, getPath, getProxyAuthenticationRealm, getProxyAuthState, getQueryString, getRecoverableExceptionCount, getRequestCharSet, getRequestHeader, getRequestHeaderGroup, getRequestHeaders, getRequestHeaders, getResponseBody, getResponseBody, getResponseBodyAsStream, getResponseBodyAsString, getResponseBodyAsString, getResponseCharSet, getResponseContentLength, getResponseFooter, getResponseFooters, getResponseHeader, getResponseHeaderGroup, getResponseHeaders, getResponseHeaders, getResponseStream, getResponseTrailerHeaderGroup, getStatusCode, getStatusLine, getStatusText, getURI, hasBeenUsed, isAborted, isConnectionCloseForced, isHttp11, isRequestSent, isStrictMode, processCookieHeaders, processResponseBody, processResponseHeaders, processStatusLine, readResponse, readResponseBody, readResponseHeaders, readStatusLine, releaseConnection, removeRequestHeader, removeRequestHeader, responseBodyConsumed, setConnectionCloseForced, setDoAuthentication, setFollowRedirects, setHostConfiguration, setHttp11, setMethodRetryHandler, setParams, setPath, setQueryString, setQueryString, setRequestHeader, setRequestHeader, setResponseStream, setStrictMode, setURI, shouldCloseConnection, validate, writeRequest, writeRequestHeaders, writeRequestLine
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

MULTIPART_FORM_CONTENT_TYPE

public static final String MULTIPART_FORM_CONTENT_TYPE
Deprecated. 
The Content-Type for multipart/form-data.

See Also:
Constant Field Values
Constructor Detail

MultipartPostMethod

public MultipartPostMethod()
Deprecated. 
No-arg constructor.


MultipartPostMethod

public MultipartPostMethod(String uri)
Deprecated. 
Constructor specifying a URI.

Parameters:
uri - either an absolute or relative URI
Method Detail

hasRequestContent

protected boolean hasRequestContent()
Deprecated. 
Returns true

Specified by:
hasRequestContent in class ExpectContinueMethod
Returns:
true
Since:
2.0beta1

getName

public String getName()
Deprecated. 
Returns "POST".

Specified by:
getName in interface HttpMethod
Specified by:
getName in class HttpMethodBase
Returns:
"POST"

addParameter

public void addParameter(String parameterName,
                         String parameterValue)
Deprecated. 
Adds a text field part

Parameters:
parameterName - The name of the parameter.
parameterValue - The value of the parameter.

addParameter

public void addParameter(String parameterName,
                         File parameterFile)
                  throws FileNotFoundException
Deprecated. 
Adds a binary file part

Parameters:
parameterName - The name of the parameter
parameterFile - The name of the file.
Throws:
FileNotFoundException - If the file cannot be found.

addParameter

public void addParameter(String parameterName,
                         String fileName,
                         File parameterFile)
                  throws FileNotFoundException
Deprecated. 
Adds a binary file part with the given file name

Parameters:
parameterName - The name of the parameter
fileName - The file name
parameterFile - The file
Throws:
FileNotFoundException - If the file cannot be found.

addPart

public void addPart(Part part)
Deprecated. 
Adds a part.

Parameters:
part - The part to add.

getParts

public Part[] getParts()
Deprecated. 
Returns all parts.

Returns:
an array of containing all parts

addContentLengthRequestHeader

protected void addContentLengthRequestHeader(HttpState state,
                                             HttpConnection conn)
                                      throws IOException,
                                             HttpException
Deprecated. 
Adds a Content-Length request header, as long as no Content-Length request header already exists.

Parameters:
state - current state of http requests
conn - the connection to use for I/O
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
Since:
3.0

addContentTypeRequestHeader

protected void addContentTypeRequestHeader(HttpState state,
                                           HttpConnection conn)
                                    throws IOException,
                                           HttpException
Deprecated. 
Adds a Content-Type request header.

Parameters:
state - current state of http requests
conn - the connection to use for I/O
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
Since:
3.0

addRequestHeaders

protected void addRequestHeaders(HttpState state,
                                 HttpConnection conn)
                          throws IOException,
                                 HttpException
Deprecated. 
Populates the request headers map to with additional headers to be submitted to the given HttpConnection.

This implementation adds tt>Content-Length and Content-Type headers, when appropriate.

Subclasses may want to override this method to to add additional headers, and may choose to invoke this implementation (via super) to add the "standard" headers.

Overrides:
addRequestHeaders in class ExpectContinueMethod
Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
See Also:
HttpMethodBase.writeRequestHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)

writeRequestBody

protected boolean writeRequestBody(HttpState state,
                                   HttpConnection conn)
                            throws IOException,
                                   HttpException
Deprecated. 
Writes the request body to the given connection.

Overrides:
writeRequestBody in class HttpMethodBase
Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Returns:
true
Throws:
IOException - if an I/O (transport) error occurs. Some transport exceptions can be recovered from.
HttpException - if a protocol exception occurs. Usually protocol exceptions cannot be recovered from.

getRequestContentLength

protected long getRequestContentLength()
                                throws IOException
Deprecated. 

Return the length of the request body.

Once this method has been invoked, the request parameters cannot be altered until the method is recycled.

Returns:
The request content length.
Throws:
IOException

recycle

public void recycle()
Deprecated. no longer supported and will be removed in the future version of HttpClient

Recycles the HTTP method so that it can be used again. Note that all of the instance variables will be reset once this method has been called. This method will also release the connection being used by this HTTP method.

Specified by:
recycle in interface HttpMethod
Overrides:
recycle in class HttpMethodBase
See Also:
HttpMethodBase.releaseConnection()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/OptionsMethod.html100644 0 0 106244 10661532627 27752 0ustar 0 0 OptionsMethod (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class OptionsMethod

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
      extended by org.apache.commons.httpclient.methods.OptionsMethod
All Implemented Interfaces:
HttpMethod

public class OptionsMethod
extends HttpMethodBase

Implements the HTTP OPTIONS method.

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

The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

Since:
1.0
Version:
$Revision: 480424 $
Author:
Remy Maucherat, Mike Bowler, Jeff Dever

Field Summary
 
Fields inherited from class org.apache.commons.httpclient.HttpMethodBase
effectiveVersion, statusLine
 
Constructor Summary
OptionsMethod()
          Method constructor.
OptionsMethod(String uri)
          Constructor specifying a URI.
 
Method Summary
 Enumeration getAllowedMethods()
          Get a list of allowed methods.
 String getName()
          Get the name.
 boolean isAllowed(String method)
          Is the specified method allowed ?
 boolean needContentLength()
          Deprecated. only entity enclosing methods set content length header
protected  void processResponseHeaders(HttpState state, HttpConnection conn)
           This implementation will parse the Allow header to obtain the set of methods supported by the resource identified by the Request-URI.
 
Methods inherited from class org.apache.commons.httpclient.HttpMethodBase
abort, addCookieRequestHeader, addHostRequestHeader, addProxyConnectionHeader, addRequestHeader, addRequestHeader, addRequestHeaders, addResponseFooter, addUserAgentRequestHeader, checkNotUsed, checkUsed, execute, generateRequestLine, getAuthenticationRealm, getContentCharSet, getDoAuthentication, getEffectiveVersion, getFollowRedirects, getHostAuthState, getHostConfiguration, getMethodRetryHandler, getParams, getPath, getProxyAuthenticationRealm, getProxyAuthState, getQueryString, getRecoverableExceptionCount, getRequestCharSet, getRequestHeader, getRequestHeaderGroup, getRequestHeaders, getRequestHeaders, getResponseBody, getResponseBody, getResponseBodyAsStream, getResponseBodyAsString, getResponseBodyAsString, getResponseCharSet, getResponseContentLength, getResponseFooter, getResponseFooters, getResponseHeader, getResponseHeaderGroup, getResponseHeaders, getResponseHeaders, getResponseStream, getResponseTrailerHeaderGroup, getStatusCode, getStatusLine, getStatusText, getURI, hasBeenUsed, isAborted, isConnectionCloseForced, isHttp11, isRequestSent, isStrictMode, processCookieHeaders, processResponseBody, processStatusLine, readResponse, readResponseBody, readResponseHeaders, readStatusLine, recycle, releaseConnection, removeRequestHeader, removeRequestHeader, responseBodyConsumed, setConnectionCloseForced, setDoAuthentication, setFollowRedirects, setHostConfiguration, setHttp11, setMethodRetryHandler, setParams, setPath, setQueryString, setQueryString, setRequestHeader, setRequestHeader, setResponseStream, setStrictMode, setURI, shouldCloseConnection, validate, writeRequest, writeRequestBody, writeRequestHeaders, writeRequestLine
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

OptionsMethod

public OptionsMethod()
Method constructor.

Since:
1.0

OptionsMethod

public OptionsMethod(String uri)
Constructor specifying a URI.

Parameters:
uri - either an absolute or relative URI
Since:
1.0
Method Detail

getName

public String getName()
Get the name.

Specified by:
getName in interface HttpMethod
Specified by:
getName in class HttpMethodBase
Returns:
"OPTIONS"
Since:
2.0

isAllowed

public boolean isAllowed(String method)
Is the specified method allowed ?

Parameters:
method - The method to check.
Returns:
true if the specified method is allowed.
Since:
1.0

getAllowedMethods

public Enumeration getAllowedMethods()
Get a list of allowed methods.

Returns:
An enumeration of all the allowed methods.
Since:
1.0

processResponseHeaders

protected void processResponseHeaders(HttpState state,
                                      HttpConnection conn)

This implementation will parse the Allow header to obtain the set of methods supported by the resource identified by the Request-URI.

Overrides:
processResponseHeaders in class HttpMethodBase
Parameters:
state - the state information associated with this method
conn - the connection used to execute this HTTP method
Since:
2.0
See Also:
HttpMethodBase.readResponse(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection), HttpMethodBase.readResponseHeaders(org.apache.commons.httpclient.HttpState, org.apache.commons.httpclient.HttpConnection)

needContentLength

public boolean needContentLength()
Deprecated. only entity enclosing methods set content length header

Return true if the method needs a content-length header in the request.

Returns:
true if a content-length header will be expected by the server
Since:
1.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/PostMethod.html100644 0 0 152354 10661532627 27247 0ustar 0 0 PostMethod (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class PostMethod

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
      extended by org.apache.commons.httpclient.methods.ExpectContinueMethod
          extended by org.apache.commons.httpclient.methods.EntityEnclosingMethod
              extended by org.apache.commons.httpclient.methods.PostMethod
All Implemented Interfaces:
HttpMethod

public class PostMethod
extends EntityEnclosingMethod

Implements the HTTP POST method.

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

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:
  • Annotation of existing resources
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles
  • Providing a block of data, such as the result of submitting a form, to a data-handling process
  • Extending a database through an append operation

Since:
1.0
Version:
$Revision: 480424 $
Author:
Remy Maucherat, Doug Sale, Jeff Dever, Ortwin Gl???ck, Mike Bowler, Oleg Kalnichevski

Field Summary
static String FORM_URL_ENCODED_CONTENT_TYPE
          The Content-Type for www-form-urlencoded.
 
Fields inherited from class org.apache.commons.httpclient.methods.EntityEnclosingMethod
CONTENT_LENGTH_AUTO, CONTENT_LENGTH_CHUNKED
 
Fields inherited from class org.apache.commons.httpclient.HttpMethodBase
effectiveVersion, statusLine
 
Constructor Summary
PostMethod()
          No-arg constructor.
PostMethod(String uri)
          Constructor specifying a URI.
 
Method Summary
 void addParameter(NameValuePair param)
          Adds a new parameter to be used in the POST request body.
 void addParameter(String paramName, String paramValue)
          Adds a new parameter to be used in the POST request body.
 void addParameters(NameValuePair[] parameters)
          Adds an array of parameters to be used in the POST request body.
protected  void clearRequestBody()
          Clears request body.
protected  RequestEntity generateRequestEntity()
          Generates a request entity from the post parameters, if present.
 String getName()
          Returns "POST".
 NameValuePair getParameter(String paramName)
          Gets the parameter of the specified name.
 NameValuePair[] getParameters()
          Gets the parameters currently added to the PostMethod.
protected  boolean hasRequestContent()
          Returns true if there is a request body to be sent.
 boolean removeParameter(String paramName)
          Removes all parameters with the given paramName.
 boolean removeParameter(String paramName, String paramValue)
          Removes all parameter with the given paramName and paramValue.
 void setParameter(String parameterName, String parameterValue)
          Sets the value of parameter with parameterName to parameterValue.
 void setRequestBody(NameValuePair[] parametersBody)
          Sets an array of parameters to be used in the POST request body
 
Methods inherited from class org.apache.commons.httpclient.methods.EntityEnclosingMethod
addContentLengthRequestHeader, addRequestHeaders, generateRequestBody, getFollowRedirects, getRequestCharSet, getRequestContentLength, getRequestEntity, recycle, setContentChunked, setFollowRedirects, setRequestBody, setRequestBody, setRequestContentLength, setRequestContentLength, setRequestEntity, writeRequestBody
 
Methods inherited from class org.apache.commons.httpclient.methods.ExpectContinueMethod
getUseExpectHeader, setUseExpectHeader
 
Methods inherited from class org.apache.commons.httpclient.HttpMethodBase
abort, addCookieRequestHeader, addHostRequestHeader, addProxyConnectionHeader, addRequestHeader, addRequestHeader, addResponseFooter, addUserAgentRequestHeader, checkNotUsed, checkUsed, execute, generateRequestLine, getAuthenticationRealm, getContentCharSet, getDoAuthentication, getEffectiveVersion, getHostAuthState, getHostConfiguration, getMethodRetryHandler, getParams, getPath, getProxyAuthenticationRealm, getProxyAuthState, getQueryString, getRecoverableExceptionCount, getRequestHeader, getRequestHeaderGroup, getRequestHeaders, getRequestHeaders, getResponseBody, getResponseBody, getResponseBodyAsStream, getResponseBodyAsString, getResponseBodyAsString, getResponseCharSet, getResponseContentLength, getResponseFooter, getResponseFooters, getResponseHeader, getResponseHeaderGroup, getResponseHeaders, getResponseHeaders, getResponseStream, getResponseTrailerHeaderGroup, getStatusCode, getStatusLine, getStatusText, getURI, hasBeenUsed, isAborted, isConnectionCloseForced, isHttp11, isRequestSent, isStrictMode, processCookieHeaders, processResponseBody, processResponseHeaders, processStatusLine, readResponse, readResponseBody, readResponseHeaders, readStatusLine, releaseConnection, removeRequestHeader, removeRequestHeader, responseBodyConsumed, setConnectionCloseForced, setDoAuthentication, setHostConfiguration, setHttp11, setMethodRetryHandler, setParams, setPath, setQueryString, setQueryString, setRequestHeader, setRequestHeader, setResponseStream, setStrictMode, setURI, shouldCloseConnection, validate, writeRequest, writeRequestHeaders, writeRequestLine
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

FORM_URL_ENCODED_CONTENT_TYPE

public static final String FORM_URL_ENCODED_CONTENT_TYPE
The Content-Type for www-form-urlencoded.

See Also:
Constant Field Values
Constructor Detail

PostMethod

public PostMethod()
No-arg constructor.

Since:
1.0

PostMethod

public PostMethod(String uri)
Constructor specifying a URI.

Parameters:
uri - either an absolute or relative URI
Since:
1.0
Method Detail

getName

public String getName()
Returns "POST".

Specified by:
getName in interface HttpMethod
Specified by:
getName in class HttpMethodBase
Returns:
"POST"
Since:
2.0

hasRequestContent

protected boolean hasRequestContent()
Returns true if there is a request body to be sent.

This method must be overwritten by sub-classes that implement alternative request content input methods

Overrides:
hasRequestContent in class EntityEnclosingMethod
Returns:
boolean
Since:
2.0beta1

clearRequestBody

protected void clearRequestBody()
Clears request body.

This method must be overwritten by sub-classes that implement alternative request content input methods

Overrides:
clearRequestBody in class EntityEnclosingMethod
Since:
2.0beta1

generateRequestEntity

protected RequestEntity generateRequestEntity()
Generates a request entity from the post parameters, if present. Calls EntityEnclosingMethod.generateRequestBody() if parameters have not been set.

Overrides:
generateRequestEntity in class EntityEnclosingMethod
Since:
3.0

setParameter

public void setParameter(String parameterName,
                         String parameterValue)
Sets the value of parameter with parameterName to parameterValue. This method does not preserve the initial insertion order.

Parameters:
parameterName - name of the parameter
parameterValue - value of the parameter
Since:
2.0

getParameter

public NameValuePair getParameter(String paramName)
Gets the parameter of the specified name. If there exists more than one parameter with the name paramName, then only the first one is returned.

Parameters:
paramName - name of the parameter
Returns:
If a parameter exists with the name argument, the coresponding NameValuePair is returned. Otherwise null.
Since:
2.0

getParameters

public NameValuePair[] getParameters()
Gets the parameters currently added to the PostMethod. If there are no parameters, a valid array is returned with zero elements. The returned array object contains an array of pointers to the internal data members.

Returns:
An array of the current parameters
Since:
2.0

addParameter

public void addParameter(String paramName,
                         String paramValue)
                  throws IllegalArgumentException
Adds a new parameter to be used in the POST request body.

Parameters:
paramName - The parameter name to add.
paramValue - The parameter value to add.
Throws:
IllegalArgumentException - if either argument is null
Since:
1.0

addParameter

public void addParameter(NameValuePair param)
                  throws IllegalArgumentException
Adds a new parameter to be used in the POST request body.

Parameters:
param - The parameter to add.
Throws:
IllegalArgumentException - if the argument is null or contains null values
Since:
2.0

addParameters

public void addParameters(NameValuePair[] parameters)
Adds an array of parameters to be used in the POST request body. Logs a warning if the parameters argument is null.

Parameters:
parameters - The array of parameters to add.
Since:
2.0

removeParameter

public boolean removeParameter(String paramName)
                        throws IllegalArgumentException
Removes all parameters with the given paramName. If there is more than one parameter with the given paramName, all of them are removed. If there is just one, it is removed. If there are none, then the request is ignored.

Parameters:
paramName - The parameter name to remove.
Returns:
true if at least one parameter was removed
Throws:
IllegalArgumentException - When the parameter name passed is null
Since:
2.0

removeParameter

public boolean removeParameter(String paramName,
                               String paramValue)
                        throws IllegalArgumentException
Removes all parameter with the given paramName and paramValue. If there is more than one parameter with the given paramName, only one is removed. If there are none, then the request is ignored.

Parameters:
paramName - The parameter name to remove.
paramValue - The parameter value to remove.
Returns:
true if a parameter was removed.
Throws:
IllegalArgumentException - when param name or value are null
Since:
2.0

setRequestBody

public void setRequestBody(NameValuePair[] parametersBody)
                    throws IllegalArgumentException
Sets an array of parameters to be used in the POST request body

Parameters:
parametersBody - The array of parameters to add.
Throws:
IllegalArgumentException - when param parameters are null
Since:
2.0beta1


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/PutMethod.html100644 0 0 104154 10661532627 27065 0ustar 0 0 PutMethod (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class PutMethod

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
      extended by org.apache.commons.httpclient.methods.ExpectContinueMethod
          extended by org.apache.commons.httpclient.methods.EntityEnclosingMethod
              extended by org.apache.commons.httpclient.methods.PutMethod
All Implemented Interfaces:
HttpMethod

public class PutMethod
extends EntityEnclosingMethod

Implements the HTTP PUT method.

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

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server.

Since:
1.0
Version:
$Revision: 480424 $
Author:
Remy Maucherat, Mike Bowler, Oleg Kalnichevski, Jeff Dever

Field Summary
 
Fields inherited from class org.apache.commons.httpclient.methods.EntityEnclosingMethod
CONTENT_LENGTH_AUTO, CONTENT_LENGTH_CHUNKED
 
Fields inherited from class org.apache.commons.httpclient.HttpMethodBase
effectiveVersion, statusLine
 
Constructor Summary
PutMethod()
          No-arg constructor.
PutMethod(String uri)
          Constructor specifying a URI.
 
Method Summary
 String getName()
          Return "PUT".
 
Methods inherited from class org.apache.commons.httpclient.methods.EntityEnclosingMethod
addContentLengthRequestHeader, addRequestHeaders, clearRequestBody, generateRequestBody, generateRequestEntity, getFollowRedirects, getRequestCharSet, getRequestContentLength, getRequestEntity, hasRequestContent, recycle, setContentChunked, setFollowRedirects, setRequestBody, setRequestBody, setRequestContentLength, setRequestContentLength, setRequestEntity, writeRequestBody
 
Methods inherited from class org.apache.commons.httpclient.methods.ExpectContinueMethod
getUseExpectHeader, setUseExpectHeader
 
Methods inherited from class org.apache.commons.httpclient.HttpMethodBase
abort, addCookieRequestHeader, addHostRequestHeader, addProxyConnectionHeader, addRequestHeader, addRequestHeader, addResponseFooter, addUserAgentRequestHeader, checkNotUsed, checkUsed, execute, generateRequestLine, getAuthenticationRealm, getContentCharSet, getDoAuthentication, getEffectiveVersion, getHostAuthState, getHostConfiguration, getMethodRetryHandler, getParams, getPath, getProxyAuthenticationRealm, getProxyAuthState, getQueryString, getRecoverableExceptionCount, getRequestHeader, getRequestHeaderGroup, getRequestHeaders, getRequestHeaders, getResponseBody, getResponseBody, getResponseBodyAsStream, getResponseBodyAsString, getResponseBodyAsString, getResponseCharSet, getResponseContentLength, getResponseFooter, getResponseFooters, getResponseHeader, getResponseHeaderGroup, getResponseHeaders, getResponseHeaders, getResponseStream, getResponseTrailerHeaderGroup, getStatusCode, getStatusLine, getStatusText, getURI, hasBeenUsed, isAborted, isConnectionCloseForced, isHttp11, isRequestSent, isStrictMode, processCookieHeaders, processResponseBody, processResponseHeaders, processStatusLine, readResponse, readResponseBody, readResponseHeaders, readStatusLine, releaseConnection, removeRequestHeader, removeRequestHeader, responseBodyConsumed, setConnectionCloseForced, setDoAuthentication, setHostConfiguration, setHttp11, setMethodRetryHandler, setParams, setPath, setQueryString, setQueryString, setRequestHeader, setRequestHeader, setResponseStream, setStrictMode, setURI, shouldCloseConnection, validate, writeRequest, writeRequestHeaders, writeRequestLine
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

PutMethod

public PutMethod()
No-arg constructor.

Since:
1.0

PutMethod

public PutMethod(String uri)
Constructor specifying a URI.

Parameters:
uri - either an absolute or relative URI
Since:
1.0
Method Detail

getName

public String getName()
Return "PUT".

Specified by:
getName in interface HttpMethod
Specified by:
getName in class HttpMethodBase
Returns:
"PUT"
Since:
2.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/RequestEntity.html100644 0 0 32367 10661532627 27767 0ustar 0 0 RequestEntity (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Interface RequestEntity

All Known Implementing Classes:
ByteArrayRequestEntity, FileRequestEntity, InputStreamRequestEntity, MultipartRequestEntity, StringRequestEntity

public interface RequestEntity

Since:
3.0

Method Summary
 long getContentLength()
          Gets the request entity's length.
 String getContentType()
          Gets the entity's content type.
 boolean isRepeatable()
          Tests if writeRequest(OutputStream) can be called more than once.
 void writeRequest(OutputStream out)
          Writes the request entity to the given stream.
 

Method Detail

isRepeatable

boolean isRepeatable()
Tests if writeRequest(OutputStream) can be called more than once.

Returns:
true if the entity can be written to OutputStream more than once, false otherwise.

writeRequest

void writeRequest(OutputStream out)
                  throws IOException
Writes the request entity to the given stream.

Parameters:
out -
Throws:
IOException

getContentLength

long getContentLength()
Gets the request entity's length. This method should return a non-negative value if the content length is known or a negative value if it is not. In the latter case the EntityEnclosingMethod will use chunk encoding to transmit the request entity.

Returns:
a non-negative value when content length is known or a negative value when content length is not known

getContentType

String getContentType()
Gets the entity's content type. This content type will be used as the value for the "Content-Type" header.

Returns:
the entity's content type
See Also:
HttpMethod.setRequestHeader(String, String)


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/StringRequestEntity.html100644 0 0 57461 10661532627 31160 0ustar 0 0 StringRequestEntity (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class StringRequestEntity

java.lang.Object
  extended by org.apache.commons.httpclient.methods.StringRequestEntity
All Implemented Interfaces:
RequestEntity

public class StringRequestEntity
extends Object
implements RequestEntity

A RequestEntity that contains a String.

Since:
3.0

Constructor Summary
StringRequestEntity(String content)
          Deprecated. use StringRequestEntity(String, String, String) instead
StringRequestEntity(String content, String contentType, String charset)
          Creates a new entity with the given content, content type, and charset.
 
Method Summary
 String getCharset()
           
 String getContent()
           
 long getContentLength()
          Gets the request entity's length.
 String getContentType()
          Gets the entity's content type.
 boolean isRepeatable()
          Tests if RequestEntity.writeRequest(OutputStream) can be called more than once.
 void writeRequest(OutputStream out)
          Writes the request entity to the given stream.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

StringRequestEntity

public StringRequestEntity(String content)
Deprecated. use StringRequestEntity(String, String, String) instead

Creates a new entity with the given content. This constructor will use the default platform charset to convert the content string and will provide no content type.

Parameters:
content - The content to set.
See Also:
StringRequestEntity(String, String, String)

StringRequestEntity

public StringRequestEntity(String content,
                           String contentType,
                           String charset)
                    throws UnsupportedEncodingException
Creates a new entity with the given content, content type, and charset.

Parameters:
content - The content to set.
contentType - The type of the content, or null. The value retured by getContentType(). If this content type contains a charset and the charset parameter is null, the content's type charset will be used.
charset - The charset of the content, or null. Used to convert the content to bytes. If the content type does not contain a charset and charset is not null, then the charset will be appended to the content type.
Throws:
UnsupportedEncodingException
Method Detail

getContentType

public String getContentType()
Description copied from interface: RequestEntity
Gets the entity's content type. This content type will be used as the value for the "Content-Type" header.

Specified by:
getContentType in interface RequestEntity
Returns:
the entity's content type
See Also:
HttpMethod.setRequestHeader(String, String)

isRepeatable

public boolean isRepeatable()
Description copied from interface: RequestEntity
Tests if RequestEntity.writeRequest(OutputStream) can be called more than once.

Specified by:
isRepeatable in interface RequestEntity
Returns:
true

writeRequest

public void writeRequest(OutputStream out)
                  throws IOException
Description copied from interface: RequestEntity
Writes the request entity to the given stream.

Specified by:
writeRequest in interface RequestEntity
Throws:
IOException

getContentLength

public long getContentLength()
Description copied from interface: RequestEntity
Gets the request entity's length. This method should return a non-negative value if the content length is known or a negative value if it is not. In the latter case the EntityEnclosingMethod will use chunk encoding to transmit the request entity.

Specified by:
getContentLength in interface RequestEntity
Returns:
The length of the content.

getContent

public String getContent()
Returns:
Returns the content.

getCharset

public String getCharset()
Returns:
Returns the charset used to convert the content to bytes. null if no charset as been specified.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/TraceMethod.html100644 0 0 74401 10661532627 27334 0ustar 0 0 TraceMethod (HttpClient 3.1 API)

org.apache.commons.httpclient.methods
Class TraceMethod

java.lang.Object
  extended by org.apache.commons.httpclient.HttpMethodBase
      extended by org.apache.commons.httpclient.methods.TraceMethod
All Implemented Interfaces:
HttpMethod

public class TraceMethod
extends HttpMethodBase

Implements the HTTP TRACE method.

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

The TRACE method is used to invoke a remote, application-layer loop- back of the request message. The final recipient of the request SHOULD reflect the message received back to the client as the entity-body of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive a Max-Forwards value of zero (0) in the request (see section 14.31). A TRACE request MUST NOT include an entity.

Since:
2.0
Version:
$Revision: 480424 $
Author:
Sean C. Sullivan, Mike Bowler, Jeff Dever

Field Summary
 
Fields inherited from class org.apache.commons.httpclient.HttpMethodBase
effectiveVersion, statusLine
 
Constructor Summary
TraceMethod(String uri)
          Constructor specifying a URI.
 
Method Summary
 String getName()
          Returns "TRACE".
 void recycle()
          Deprecated. no longer supported and will be removed in the future version of HttpClient
 
Methods inherited from class org.apache.commons.httpclient.HttpMethodBase
abort, addCookieRequestHeader, addHostRequestHeader, addProxyConnectionHeader, addRequestHeader, addRequestHeader, addRequestHeaders, addResponseFooter, addUserAgentRequestHeader, checkNotUsed, checkUsed, execute, generateRequestLine, getAuthenticationRealm, getContentCharSet, getDoAuthentication, getEffectiveVersion, getFollowRedirects, getHostAuthState, getHostConfiguration, getMethodRetryHandler, getParams, getPath, getProxyAuthenticationRealm, getProxyAuthState, getQueryString, getRecoverableExceptionCount, getRequestCharSet, getRequestHeader, getRequestHeaderGroup, getRequestHeaders, getRequestHeaders, getResponseBody, getResponseBody, getResponseBodyAsStream, getResponseBodyAsString, getResponseBodyAsString, getResponseCharSet, getResponseContentLength, getResponseFooter, getResponseFooters, getResponseHeader, getResponseHeaderGroup, getResponseHeaders, getResponseHeaders, getResponseStream, getResponseTrailerHeaderGroup, getStatusCode, getStatusLine, getStatusText, getURI, hasBeenUsed, isAborted, isConnectionCloseForced, isHttp11, isRequestSent, isStrictMode, processCookieHeaders, processResponseBody, processResponseHeaders, processStatusLine, readResponse, readResponseBody, readResponseHeaders, readStatusLine, releaseConnection, removeRequestHeader, removeRequestHeader, responseBodyConsumed, setConnectionCloseForced, setDoAuthentication, setFollowRedirects, setHostConfiguration, setHttp11, setMethodRetryHandler, setParams, setPath, setQueryString, setQueryString, setRequestHeader, setRequestHeader, setResponseStream, setStrictMode, setURI, shouldCloseConnection, validate, writeRequest, writeRequestBody, writeRequestHeaders, writeRequestLine
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

TraceMethod

public TraceMethod(String uri)
Constructor specifying a URI.

Parameters:
uri - either an absolute or relative URI
Since:
2.0
Method Detail

getName

public String getName()
Returns "TRACE".

Specified by:
getName in interface HttpMethod
Specified by:
getName in class HttpMethodBase
Returns:
"TRACE"
Since:
2.0

recycle

public void recycle()
Deprecated. no longer supported and will be removed in the future version of HttpClient

Recycles the HTTP method so that it can be used again. Note that all of the instance variables will be reset once this method has been called. This method will also release the connection being used by this HTTP method.

Specified by:
recycle in interface HttpMethod
Overrides:
recycle in class HttpMethodBase
Since:
2.0
See Also:
HttpMethodBase.releaseConnection()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 160 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/ByteArrayRequestEntity.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/ByteArrayRequest100644 0 0 14154 10661532627 31343 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.ByteArrayRequestEntity (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.ByteArrayRequestEntity

No usage of org.apache.commons.httpclient.methods.ByteArrayRequestEntity



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/DeleteMethod.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/DeleteMethod.htm100644 0 0 14010 10661532627 31211 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.DeleteMethod (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.DeleteMethod

No usage of org.apache.commons.httpclient.methods.DeleteMethod



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 157 10661532634 10264 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/EntityEnclosingMethod.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/EntityEnclosingM100644 0 0 21264 10661532627 31323 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.EntityEnclosingMethod (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.EntityEnclosingMethod

Packages that use EntityEnclosingMethod
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
 

Uses of EntityEnclosingMethod in org.apache.commons.httpclient.methods
 

Subclasses of EntityEnclosingMethod in org.apache.commons.httpclient.methods
 class PostMethod
          Implements the HTTP POST method.
 class PutMethod
          Implements the HTTP PUT method.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 156 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/ExpectContinueMethod.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/ExpectContinueMe100644 0 0 24001 10661532627 31277 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.ExpectContinueMethod (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.ExpectContinueMethod

Packages that use ExpectContinueMethod
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
 

Uses of ExpectContinueMethod in org.apache.commons.httpclient.methods
 

Subclasses of ExpectContinueMethod in org.apache.commons.httpclient.methods
 class EntityEnclosingMethod
          This abstract class serves as a foundation for all HTTP methods that can enclose an entity within requests
 class MultipartPostMethod
          Deprecated. Use MultipartRequestEntity in conjunction with PostMethod instead.
 class PostMethod
          Implements the HTTP POST method.
 class PutMethod
          Implements the HTTP PUT method.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 153 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/FileRequestEntity.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/FileRequestEntit100644 0 0 14072 10661532627 31323 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.FileRequestEntity (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.FileRequestEntity

No usage of org.apache.commons.httpclient.methods.FileRequestEntity



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/GetMethod.html100644 0 0 13752 10661532627 30716 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.GetMethod (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.GetMethod

No usage of org.apache.commons.httpclient.methods.GetMethod



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/HeadMethod.html100644 0 0 13764 10661532627 31043 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.HeadMethod (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.HeadMethod

No usage of org.apache.commons.httpclient.methods.HeadMethod



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 162 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/InputStreamRequestEntity.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/InputStreamReque100644 0 0 14200 10661532627 31335 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.InputStreamRequestEntity (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.InputStreamRequestEntity

No usage of org.apache.commons.httpclient.methods.InputStreamRequestEntity



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/MultipartPostMethod.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/MultipartPostMet100644 0 0 14116 10661532627 31363 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.MultipartPostMethod (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.MultipartPostMethod

No usage of org.apache.commons.httpclient.methods.MultipartPostMethod



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/OptionsMethod.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/OptionsMethod.ht100644 0 0 14022 10661532627 31270 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.OptionsMethod (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.OptionsMethod

No usage of org.apache.commons.httpclient.methods.OptionsMethod



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/PostMethod.html100644 0 0 13764 10661532627 31127 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.PostMethod (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.PostMethod

No usage of org.apache.commons.httpclient.methods.PostMethod



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/PutMethod.html100644 0 0 13752 10661532627 30747 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.PutMethod (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.PutMethod

No usage of org.apache.commons.httpclient.methods.PutMethod



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/RequestEntity.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/RequestEntity.ht100644 0 0 35674 10661532627 31341 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.methods.RequestEntity (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.methods.RequestEntity

Packages that use RequestEntity
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
org.apache.commons.httpclient.methods.multipart Provides Multipart support classes for the MultipartPostMethod
 

Uses of RequestEntity in org.apache.commons.httpclient.methods
 

Classes in org.apache.commons.httpclient.methods that implement RequestEntity
 class ByteArrayRequestEntity
          A RequestEntity that contains an array of bytes.
 class FileRequestEntity
          A RequestEntity that represents a File.
 class InputStreamRequestEntity
          A RequestEntity that contains an InputStream.
 class StringRequestEntity
          A RequestEntity that contains a String.
 

Methods in org.apache.commons.httpclient.methods that return RequestEntity
protected  RequestEntity PostMethod.generateRequestEntity()
          Generates a request entity from the post parameters, if present.
protected  RequestEntity EntityEnclosingMethod.generateRequestEntity()
           
 RequestEntity EntityEnclosingMethod.getRequestEntity()
           
 

Methods in org.apache.commons.httpclient.methods with parameters of type RequestEntity
 void EntityEnclosingMethod.setRequestEntity(RequestEntity requestEntity)
           
 

Uses of RequestEntity in org.apache.commons.httpclient.methods.multipart
 

Classes in org.apache.commons.httpclient.methods.multipart that implement RequestEntity
 class MultipartRequestEntity
          Implements a request entity suitable for an HTTP multipart POST method.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/StringRequestEntity.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/StringRequestEnt100644 0 0 14116 10661532627 31354 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.StringRequestEntity (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.StringRequestEntity

No usage of org.apache.commons.httpclient.methods.StringRequestEntity



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/TraceMethod.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/class-use/TraceMethod.html100644 0 0 13776 10661532627 31243 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.TraceMethod (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.TraceMethod

No usage of org.apache.commons.httpclient.methods.TraceMethod



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/ByteArrayPartSource.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/ByteArrayPartSou100644 0 0 43040 10661532627 31426 0ustar 0 0 ByteArrayPartSource (HttpClient 3.1 API)

org.apache.commons.httpclient.methods.multipart
Class ByteArrayPartSource

java.lang.Object
  extended by org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource
All Implemented Interfaces:
PartSource

public class ByteArrayPartSource
extends Object
implements PartSource

A PartSource that reads from a byte array. This class should be used when the data to post is already loaded into memory.

Since:
2.0
Author:
Michael Becke

Constructor Summary
ByteArrayPartSource(String fileName, byte[] bytes)
          Constructor for ByteArrayPartSource.
 
Method Summary
 InputStream createInputStream()
          Gets a new InputStream for reading this source.
 String getFileName()
          Gets the name of the file this source represents.
 long getLength()
          Gets the number of bytes contained in this source.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ByteArrayPartSource

public ByteArrayPartSource(String fileName,
                           byte[] bytes)
Constructor for ByteArrayPartSource.

Parameters:
fileName - the name of the file these bytes represent
bytes - the content of this part
Method Detail

getLength

public long getLength()
Description copied from interface: PartSource
Gets the number of bytes contained in this source.

Specified by:
getLength in interface PartSource
Returns:
a value >= 0
See Also:
PartSource.getLength()

getFileName

public String getFileName()
Description copied from interface: PartSource
Gets the name of the file this source represents.

Specified by:
getFileName in interface PartSource
Returns:
the fileName used for posting a MultiPart file part
See Also:
PartSource.getFileName()

createInputStream

public InputStream createInputStream()
                              throws IOException
Description copied from interface: PartSource
Gets a new InputStream for reading this source. This method can be called more than once and should therefore return a new stream every time.

Specified by:
createInputStream in interface PartSource
Returns:
a new InputStream
Throws:
IOException - if an error occurs when creating the InputStream
See Also:
PartSource.createInputStream()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/FilePart.html100644 0 0 125065 10661532627 30707 0ustar 0 0 FilePart (HttpClient 3.1 API)

org.apache.commons.httpclient.methods.multipart
Class FilePart

java.lang.Object
  extended by org.apache.commons.httpclient.methods.multipart.Part
      extended by org.apache.commons.httpclient.methods.multipart.PartBase
          extended by org.apache.commons.httpclient.methods.multipart.FilePart

public class FilePart
extends PartBase

This class implements a part of a Multipart post object that consists of a file.

Since:
2.0
Author:
Matthew Albright, Jeff Dever, Adrian Sutton, Michael Becke, Mark Diggory, Mike Bowler, Oleg Kalnichevski

Field Summary
static String DEFAULT_CHARSET
          Default charset of file attachments.
static String DEFAULT_CONTENT_TYPE
          Default content encoding of file attachments.
static String DEFAULT_TRANSFER_ENCODING
          Default transfer encoding of file attachments.
protected static String FILE_NAME
          Attachment's file name
 
Fields inherited from class org.apache.commons.httpclient.methods.multipart.Part
BOUNDARY, BOUNDARY_BYTES, CHARSET, CHARSET_BYTES, CONTENT_DISPOSITION, CONTENT_DISPOSITION_BYTES, CONTENT_TRANSFER_ENCODING, CONTENT_TRANSFER_ENCODING_BYTES, CONTENT_TYPE, CONTENT_TYPE_BYTES, CRLF, CRLF_BYTES, EXTRA, EXTRA_BYTES, QUOTE, QUOTE_BYTES
 
Constructor Summary
FilePart(String name, File file)
          FilePart Constructor.
FilePart(String name, File file, String contentType, String charset)
          FilePart Constructor.
FilePart(String name, PartSource partSource)
          FilePart Constructor.
FilePart(String name, PartSource partSource, String contentType, String charset)
          FilePart Constructor.
FilePart(String name, String fileName, File file)
          FilePart Constructor.
FilePart(String name, String fileName, File file, String contentType, String charset)
          FilePart Constructor.
 
Method Summary
protected  PartSource getSource()
          Returns the source of the file part.
protected  long lengthOfData()
          Return the length of the data.
protected  void sendData(OutputStream out)
          Write the data in "source" to the specified stream.
protected  void sendDispositionHeader(OutputStream out)
          Write the disposition header to the output stream
 
Methods inherited from class org.apache.commons.httpclient.methods.multipart.PartBase
getCharSet, getContentType, getName, getTransferEncoding, setCharSet, setContentType, setName, setTransferEncoding
 
Methods inherited from class org.apache.commons.httpclient.methods.multipart.Part
getBoundary, getLengthOfParts, getLengthOfParts, getPartBoundary, isRepeatable, length, send, sendContentTypeHeader, sendEnd, sendEndOfHeader, sendParts, sendParts, sendStart, sendTransferEncodingHeader, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

DEFAULT_CONTENT_TYPE

public static final String DEFAULT_CONTENT_TYPE
Default content encoding of file attachments.

See Also:
Constant Field Values

DEFAULT_CHARSET

public static final String DEFAULT_CHARSET
Default charset of file attachments.

See Also:
Constant Field Values

DEFAULT_TRANSFER_ENCODING

public static final String DEFAULT_TRANSFER_ENCODING
Default transfer encoding of file attachments.

See Also:
Constant Field Values

FILE_NAME

protected static final String FILE_NAME
Attachment's file name

See Also:
Constant Field Values
Constructor Detail

FilePart

public FilePart(String name,
                PartSource partSource,
                String contentType,
                String charset)
FilePart Constructor.

Parameters:
name - the name for this part
partSource - the source for this part
contentType - the content type for this part, if null the default is used
charset - the charset encoding for this part, if null the default is used

FilePart

public FilePart(String name,
                PartSource partSource)
FilePart Constructor.

Parameters:
name - the name for this part
partSource - the source for this part

FilePart

public FilePart(String name,
                File file)
         throws FileNotFoundException
FilePart Constructor.

Parameters:
name - the name of the file part
file - the file to post
Throws:
FileNotFoundException - if the file is not a normal file or if it is not readable.

FilePart

public FilePart(String name,
                File file,
                String contentType,
                String charset)
         throws FileNotFoundException
FilePart Constructor.

Parameters:
name - the name of the file part
file - the file to post
contentType - the content type for this part, if null the default is used
charset - the charset encoding for this part, if null the default is used
Throws:
FileNotFoundException - if the file is not a normal file or if it is not readable.

FilePart

public FilePart(String name,
                String fileName,
                File file)
         throws FileNotFoundException
FilePart Constructor.

Parameters:
name - the name of the file part
fileName - the file name
file - the file to post
Throws:
FileNotFoundException - if the file is not a normal file or if it is not readable.

FilePart

public FilePart(String name,
                String fileName,
                File file,
                String contentType,
                String charset)
         throws FileNotFoundException
FilePart Constructor.

Parameters:
name - the name of the file part
fileName - the file name
file - the file to post
contentType - the content type for this part, if null the default is used
charset - the charset encoding for this part, if null the default is used
Throws:
FileNotFoundException - if the file is not a normal file or if it is not readable.
Method Detail

sendDispositionHeader

protected void sendDispositionHeader(OutputStream out)
                              throws IOException
Write the disposition header to the output stream

Overrides:
sendDispositionHeader in class Part
Parameters:
out - The output stream
Throws:
IOException - If an IO problem occurs
See Also:
Part.sendDispositionHeader(OutputStream)

sendData

protected void sendData(OutputStream out)
                 throws IOException
Write the data in "source" to the specified stream.

Specified by:
sendData in class Part
Parameters:
out - The output stream.
Throws:
IOException - if an IO problem occurs.
See Also:
Part.sendData(OutputStream)

getSource

protected PartSource getSource()
Returns the source of the file part.

Returns:
The source.

lengthOfData

protected long lengthOfData()
                     throws IOException
Return the length of the data.

Specified by:
lengthOfData in class Part
Returns:
The length.
Throws:
IOException - if an IO problem occurs
See Also:
Part.lengthOfData()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/FilePartSource.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/FilePartSource.h100644 0 0 46167 10661532627 31340 0ustar 0 0 FilePartSource (HttpClient 3.1 API)

org.apache.commons.httpclient.methods.multipart
Class FilePartSource

java.lang.Object
  extended by org.apache.commons.httpclient.methods.multipart.FilePartSource
All Implemented Interfaces:
PartSource

public class FilePartSource
extends Object
implements PartSource

A PartSource that reads from a File.

Since:
2.0
Author:
Michael Becke, Mark Diggory, Mike Bowler

Constructor Summary
FilePartSource(File file)
          Constructor for FilePartSource.
FilePartSource(String fileName, File file)
          Constructor for FilePartSource.
 
Method Summary
 InputStream createInputStream()
          Return a new FileInputStream for the current filename.
 String getFileName()
          Return the current filename
 long getLength()
          Return the length of the file
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

FilePartSource

public FilePartSource(File file)
               throws FileNotFoundException
Constructor for FilePartSource.

Parameters:
file - the FilePart source File.
Throws:
FileNotFoundException - if the file does not exist or cannot be read

FilePartSource

public FilePartSource(String fileName,
                      File file)
               throws FileNotFoundException
Constructor for FilePartSource.

Parameters:
fileName - the file name of the FilePart
file - the source File for the FilePart
Throws:
FileNotFoundException - if the file does not exist or cannot be read
Method Detail

getLength

public long getLength()
Return the length of the file

Specified by:
getLength in interface PartSource
Returns:
the length of the file.
See Also:
PartSource.getLength()

getFileName

public String getFileName()
Return the current filename

Specified by:
getFileName in interface PartSource
Returns:
the filename.
See Also:
PartSource.getFileName()

createInputStream

public InputStream createInputStream()
                              throws IOException
Return a new FileInputStream for the current filename.

Specified by:
createInputStream in interface PartSource
Returns:
the new input stream.
Throws:
IOException - If an IO problem occurs.
See Also:
PartSource.createInputStream()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 160 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/MultipartRequestEntity.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/MultipartRequest100644 0 0 57476 10661532627 31562 0ustar 0 0 MultipartRequestEntity (HttpClient 3.1 API)

org.apache.commons.httpclient.methods.multipart
Class MultipartRequestEntity

java.lang.Object
  extended by org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity
All Implemented Interfaces:
RequestEntity

public class MultipartRequestEntity
extends Object
implements RequestEntity

Implements a request entity suitable for an HTTP multipart POST method.

The HTTP multipart POST method is defined in section 3.3 of RFC1867:

The media-type multipart/form-data follows the rules of all multipart MIME data streams as outlined in RFC 1521. The multipart/form-data contains a series of parts. Each part is expected to contain a content-disposition header where the value is "form-data" and a name attribute specifies the field name within the form, e.g., 'content-disposition: form-data; name="xxxxx"', where xxxxx is the field name corresponding to that field. Field names originally in non-ASCII character sets may be encoded using the method outlined in RFC 1522.

This entity is designed to be used in conjunction with the post method to provide multipart posts. Example usage:

  File f = new File("/path/fileToUpload.txt");
  PostMethod filePost = new PostMethod("http://host/some_path");
  Part[] parts = {
      new StringPart("param_name", "value"),
      new FilePart(f.getName(), f)
  };
  filePost.setRequestEntity(
      new MultipartRequestEntity(parts, filePost.getParams())
      );
  HttpClient client = new HttpClient();
  int status = client.executeMethod(filePost);
 

Since:
3.0

Field Summary
protected  Part[] parts
          The MIME parts as set by the constructor
 
Constructor Summary
MultipartRequestEntity(Part[] parts, HttpMethodParams params)
          Creates a new multipart entity containing the given parts.
 
Method Summary
 long getContentLength()
          Gets the request entity's length.
 String getContentType()
          Gets the entity's content type.
protected  byte[] getMultipartBoundary()
          Returns the MIME boundary string that is used to demarcate boundaries of this part.
 boolean isRepeatable()
          Returns true if all parts are repeatable, false otherwise.
 void writeRequest(OutputStream out)
          Writes the request entity to the given stream.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

parts

protected Part[] parts
The MIME parts as set by the constructor

Constructor Detail

MultipartRequestEntity

public MultipartRequestEntity(Part[] parts,
                              HttpMethodParams params)
Creates a new multipart entity containing the given parts.

Parameters:
parts - The parts to include.
params - The params of the HttpMethod using this entity.
Method Detail

getMultipartBoundary

protected byte[] getMultipartBoundary()
Returns the MIME boundary string that is used to demarcate boundaries of this part. The first call to this method will implicitly create a new boundary string. To create a boundary string first the HttpMethodParams.MULTIPART_BOUNDARY parameter is considered. Otherwise a random one is generated.

Returns:
The boundary string of this entity in ASCII encoding.

isRepeatable

public boolean isRepeatable()
Returns true if all parts are repeatable, false otherwise.

Specified by:
isRepeatable in interface RequestEntity
Returns:
true if the entity can be written to OutputStream more than once, false otherwise.
See Also:
RequestEntity.isRepeatable()

writeRequest

public void writeRequest(OutputStream out)
                  throws IOException
Description copied from interface: RequestEntity
Writes the request entity to the given stream.

Specified by:
writeRequest in interface RequestEntity
Throws:
IOException

getContentLength

public long getContentLength()
Description copied from interface: RequestEntity
Gets the request entity's length. This method should return a non-negative value if the content length is known or a negative value if it is not. In the latter case the EntityEnclosingMethod will use chunk encoding to transmit the request entity.

Specified by:
getContentLength in interface RequestEntity
Returns:
a non-negative value when content length is known or a negative value when content length is not known

getContentType

public String getContentType()
Description copied from interface: RequestEntity
Gets the entity's content type. This content type will be used as the value for the "Content-Type" header.

Specified by:
getContentType in interface RequestEntity
Returns:
the entity's content type
See Also:
HttpMethod.setRequestHeader(String, String)


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/Part.html100644 0 0 152240 10661532627 30102 0ustar 0 0 Part (HttpClient 3.1 API)

org.apache.commons.httpclient.methods.multipart
Class Part

java.lang.Object
  extended by org.apache.commons.httpclient.methods.multipart.Part
Direct Known Subclasses:
PartBase

public abstract class Part
extends Object

Abstract class for one Part of a multipart post object.

Since:
2.0
Author:
Matthew Albright, Jeff Dever, Adrian Sutton, Mike Bowler, Oleg Kalnichevski

Field Summary
protected static String BOUNDARY
          Deprecated. use HttpMethodParams.MULTIPART_BOUNDARY
protected static byte[] BOUNDARY_BYTES
          Deprecated.  
protected static String CHARSET
          Content charset
protected static byte[] CHARSET_BYTES
          Content charset as a byte array
protected static String CONTENT_DISPOSITION
          Content dispostion characters
protected static byte[] CONTENT_DISPOSITION_BYTES
          Content dispostion as a byte array
protected static String CONTENT_TRANSFER_ENCODING
          Content type header
protected static byte[] CONTENT_TRANSFER_ENCODING_BYTES
          Content type header as a byte array
protected static String CONTENT_TYPE
          Content type header
protected static byte[] CONTENT_TYPE_BYTES
          Content type header as a byte array
protected static String CRLF
          Carriage return/linefeed
protected static byte[] CRLF_BYTES
          Carriage return/linefeed as a byte array
protected static String EXTRA
          Extra characters
protected static byte[] EXTRA_BYTES
          Extra characters as a byte array
protected static String QUOTE
          Content dispostion characters
protected static byte[] QUOTE_BYTES
          Content dispostion as a byte array
 
Constructor Summary
Part()
           
 
Method Summary
static String getBoundary()
          Deprecated. uses a constant string. Rather use getPartBoundary()
abstract  String getCharSet()
          Return the character encoding of this part.
abstract  String getContentType()
          Returns the content type of this part.
static long getLengthOfParts(Part[] parts)
          Return the total sum of all parts and that of the last boundary
static long getLengthOfParts(Part[] parts, byte[] partBoundary)
          Gets the length of the multipart message including the given parts.
abstract  String getName()
          Return the name of this part.
protected  byte[] getPartBoundary()
          Gets the part boundary to be used.
abstract  String getTransferEncoding()
          Return the transfer encoding of this part.
 boolean isRepeatable()
          Tests if this part can be sent more than once.
 long length()
          Return the full length of all the data.
protected abstract  long lengthOfData()
          Return the length of the main content
 void send(OutputStream out)
          Write all the data to the output stream.
protected  void sendContentTypeHeader(OutputStream out)
          Write the content type header to the specified output stream
protected abstract  void sendData(OutputStream out)
          Write the data to the specified output stream
protected  void sendDispositionHeader(OutputStream out)
          Write the content disposition header to the specified output stream
protected  void sendEnd(OutputStream out)
          Write the end data to the output stream.
protected  void sendEndOfHeader(OutputStream out)
          Write the end of the header to the output stream
static void sendParts(OutputStream out, Part[] parts)
          Write all parts and the last boundary to the specified output stream.
static void sendParts(OutputStream out, Part[] parts, byte[] partBoundary)
          Write all parts and the last boundary to the specified output stream.
protected  void sendStart(OutputStream out)
          Write the start to the specified output stream
protected  void sendTransferEncodingHeader(OutputStream out)
          Write the content transfer encoding header to the specified output stream
 String toString()
          Return a string representation of this object.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

BOUNDARY

protected static final String BOUNDARY
Deprecated. use HttpMethodParams.MULTIPART_BOUNDARY
The boundary

See Also:
Constant Field Values

BOUNDARY_BYTES

protected static final byte[] BOUNDARY_BYTES
Deprecated. 
The boundary as a byte array.


CRLF

protected static final String CRLF
Carriage return/linefeed

See Also:
Constant Field Values

CRLF_BYTES

protected static final byte[] CRLF_BYTES
Carriage return/linefeed as a byte array


QUOTE

protected static final String QUOTE
Content dispostion characters

See Also:
Constant Field Values

QUOTE_BYTES

protected static final byte[] QUOTE_BYTES
Content dispostion as a byte array


EXTRA

protected static final String EXTRA
Extra characters

See Also:
Constant Field Values

EXTRA_BYTES

protected static final byte[] EXTRA_BYTES
Extra characters as a byte array


CONTENT_DISPOSITION

protected static final String CONTENT_DISPOSITION
Content dispostion characters

See Also:
Constant Field Values

CONTENT_DISPOSITION_BYTES

protected static final byte[] CONTENT_DISPOSITION_BYTES
Content dispostion as a byte array


CONTENT_TYPE

protected static final String CONTENT_TYPE
Content type header

See Also:
Constant Field Values

CONTENT_TYPE_BYTES

protected static final byte[] CONTENT_TYPE_BYTES
Content type header as a byte array


CHARSET

protected static final String CHARSET
Content charset

See Also:
Constant Field Values

CHARSET_BYTES

protected static final byte[] CHARSET_BYTES
Content charset as a byte array


CONTENT_TRANSFER_ENCODING

protected static final String CONTENT_TRANSFER_ENCODING
Content type header

See Also:
Constant Field Values

CONTENT_TRANSFER_ENCODING_BYTES

protected static final byte[] CONTENT_TRANSFER_ENCODING_BYTES
Content type header as a byte array

Constructor Detail

Part

public Part()
Method Detail

getBoundary

public static String getBoundary()
Deprecated. uses a constant string. Rather use getPartBoundary()

Return the boundary string.

Returns:
the boundary string

getName

public abstract String getName()
Return the name of this part.

Returns:
The name.

getContentType

public abstract String getContentType()
Returns the content type of this part.

Returns:
the content type, or null to exclude the content type header

getCharSet

public abstract String getCharSet()
Return the character encoding of this part.

Returns:
the character encoding, or null to exclude the character encoding header

getTransferEncoding

public abstract String getTransferEncoding()
Return the transfer encoding of this part.

Returns:
the transfer encoding, or null to exclude the transfer encoding header

getPartBoundary

protected byte[] getPartBoundary()
Gets the part boundary to be used.

Returns:
the part boundary as an array of bytes.
Since:
3.0

isRepeatable

public boolean isRepeatable()
Tests if this part can be sent more than once.

Returns:
true if sendData(OutputStream) can be successfully called more than once.
Since:
3.0

sendStart

protected void sendStart(OutputStream out)
                  throws IOException
Write the start to the specified output stream

Parameters:
out - The output stream
Throws:
IOException - If an IO problem occurs.

sendDispositionHeader

protected void sendDispositionHeader(OutputStream out)
                              throws IOException
Write the content disposition header to the specified output stream

Parameters:
out - The output stream
Throws:
IOException - If an IO problem occurs.

sendContentTypeHeader

protected void sendContentTypeHeader(OutputStream out)
                              throws IOException
Write the content type header to the specified output stream

Parameters:
out - The output stream
Throws:
IOException - If an IO problem occurs.

sendTransferEncodingHeader

protected void sendTransferEncodingHeader(OutputStream out)
                                   throws IOException
Write the content transfer encoding header to the specified output stream

Parameters:
out - The output stream
Throws:
IOException - If an IO problem occurs.

sendEndOfHeader

protected void sendEndOfHeader(OutputStream out)
                        throws IOException
Write the end of the header to the output stream

Parameters:
out - The output stream
Throws:
IOException - If an IO problem occurs.

sendData

protected abstract void sendData(OutputStream out)
                          throws IOException
Write the data to the specified output stream

Parameters:
out - The output stream
Throws:
IOException - If an IO problem occurs.

lengthOfData

protected abstract long lengthOfData()
                              throws IOException
Return the length of the main content

Returns:
long The length.
Throws:
IOException - If an IO problem occurs

sendEnd

protected void sendEnd(OutputStream out)
                throws IOException
Write the end data to the output stream.

Parameters:
out - The output stream
Throws:
IOException - If an IO problem occurs.

send

public void send(OutputStream out)
          throws IOException
Write all the data to the output stream. If you override this method make sure to override #length() as well

Parameters:
out - The output stream
Throws:
IOException - If an IO problem occurs.

length

public long length()
            throws IOException
Return the full length of all the data. If you override this method make sure to override #send(OutputStream) as well

Returns:
long The length.
Throws:
IOException - If an IO problem occurs

toString

public String toString()
Return a string representation of this object.

Overrides:
toString in class Object
Returns:
A string representation of this object.
See Also:
Object.toString()

sendParts

public static void sendParts(OutputStream out,
                             Part[] parts)
                      throws IOException
Write all parts and the last boundary to the specified output stream.

Parameters:
out - The stream to write to.
parts - The parts to write.
Throws:
IOException - If an I/O error occurs while writing the parts.

sendParts

public static void sendParts(OutputStream out,
                             Part[] parts,
                             byte[] partBoundary)
                      throws IOException
Write all parts and the last boundary to the specified output stream.

Parameters:
out - The stream to write to.
parts - The parts to write.
partBoundary - The ASCII bytes to use as the part boundary.
Throws:
IOException - If an I/O error occurs while writing the parts.
Since:
3.0

getLengthOfParts

public static long getLengthOfParts(Part[] parts)
                             throws IOException
Return the total sum of all parts and that of the last boundary

Parameters:
parts - The parts.
Returns:
The total length
Throws:
IOException - If an I/O error occurs while writing the parts.

getLengthOfParts

public static long getLengthOfParts(Part[] parts,
                                    byte[] partBoundary)
                             throws IOException
Gets the length of the multipart message including the given parts.

Parameters:
parts - The parts.
partBoundary - The ASCII bytes to use as the part boundary.
Returns:
The total length
Throws:
IOException - If an I/O error occurs while writing the parts.
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/PartBase.html100644 0 0 70641 10661532627 30661 0ustar 0 0 PartBase (HttpClient 3.1 API)

org.apache.commons.httpclient.methods.multipart
Class PartBase

java.lang.Object
  extended by org.apache.commons.httpclient.methods.multipart.Part
      extended by org.apache.commons.httpclient.methods.multipart.PartBase
Direct Known Subclasses:
FilePart, StringPart

public abstract class PartBase
extends Part

Provides setters and getters for the basic Part properties.

Author:
Michael Becke

Field Summary
 
Fields inherited from class org.apache.commons.httpclient.methods.multipart.Part
BOUNDARY, BOUNDARY_BYTES, CHARSET, CHARSET_BYTES, CONTENT_DISPOSITION, CONTENT_DISPOSITION_BYTES, CONTENT_TRANSFER_ENCODING, CONTENT_TRANSFER_ENCODING_BYTES, CONTENT_TYPE, CONTENT_TYPE_BYTES, CRLF, CRLF_BYTES, EXTRA, EXTRA_BYTES, QUOTE, QUOTE_BYTES
 
Constructor Summary
PartBase(String name, String contentType, String charSet, String transferEncoding)
          Constructor.
 
Method Summary
 String getCharSet()
          Return the character encoding of this part.
 String getContentType()
          Returns the content type of this part.
 String getName()
          Returns the name.
 String getTransferEncoding()
          Returns the transfer encoding of this part.
 void setCharSet(String charSet)
          Sets the character encoding.
 void setContentType(String contentType)
          Sets the content type.
 void setName(String name)
          Sets the part name.
 void setTransferEncoding(String transferEncoding)
          Sets the transfer encoding.
 
Methods inherited from class org.apache.commons.httpclient.methods.multipart.Part
getBoundary, getLengthOfParts, getLengthOfParts, getPartBoundary, isRepeatable, length, lengthOfData, send, sendContentTypeHeader, sendData, sendDispositionHeader, sendEnd, sendEndOfHeader, sendParts, sendParts, sendStart, sendTransferEncodingHeader, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

PartBase

public PartBase(String name,
                String contentType,
                String charSet,
                String transferEncoding)
Constructor.

Parameters:
name - The name of the part
contentType - The content type, or null
charSet - The character encoding, or null
transferEncoding - The transfer encoding, or null
Method Detail

getName

public String getName()
Returns the name.

Specified by:
getName in class Part
Returns:
The name.
See Also:
Part.getName()

getContentType

public String getContentType()
Returns the content type of this part.

Specified by:
getContentType in class Part
Returns:
String The name.

getCharSet

public String getCharSet()
Return the character encoding of this part.

Specified by:
getCharSet in class Part
Returns:
String The name.

getTransferEncoding

public String getTransferEncoding()
Returns the transfer encoding of this part.

Specified by:
getTransferEncoding in class Part
Returns:
String The name.

setCharSet

public void setCharSet(String charSet)
Sets the character encoding.

Parameters:
charSet - the character encoding, or null to exclude the character encoding header

setContentType

public void setContentType(String contentType)
Sets the content type.

Parameters:
contentType - the content type, or null to exclude the content type header

setName

public void setName(String name)
Sets the part name.

Parameters:
name -

setTransferEncoding

public void setTransferEncoding(String transferEncoding)
Sets the transfer encoding.

Parameters:
transferEncoding - the transfer encoding, or null to exclude the transfer encoding header


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/PartSource.html100644 0 0 27065 10661532627 31251 0ustar 0 0 PartSource (HttpClient 3.1 API)

org.apache.commons.httpclient.methods.multipart
Interface PartSource

All Known Implementing Classes:
ByteArrayPartSource, FilePartSource

public interface PartSource

An interface for providing access to data when posting MultiPart messages.

Since:
2.0
Author:
Michael Becke
See Also:
FilePart

Method Summary
 InputStream createInputStream()
          Gets a new InputStream for reading this source.
 String getFileName()
          Gets the name of the file this source represents.
 long getLength()
          Gets the number of bytes contained in this source.
 

Method Detail

getLength

long getLength()
Gets the number of bytes contained in this source.

Returns:
a value >= 0

getFileName

String getFileName()
Gets the name of the file this source represents.

Returns:
the fileName used for posting a MultiPart file part

createInputStream

InputStream createInputStream()
                              throws IOException
Gets a new InputStream for reading this source. This method can be called more than once and should therefore return a new stream every time.

Returns:
a new InputStream
Throws:
IOException - if an error occurs when creating the InputStream


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/StringPart.html100644 0 0 73066 10661532627 31261 0ustar 0 0 StringPart (HttpClient 3.1 API)

org.apache.commons.httpclient.methods.multipart
Class StringPart

java.lang.Object
  extended by org.apache.commons.httpclient.methods.multipart.Part
      extended by org.apache.commons.httpclient.methods.multipart.PartBase
          extended by org.apache.commons.httpclient.methods.multipart.StringPart

public class StringPart
extends PartBase

Simple string parameter for a multipart post

Since:
2.0
Author:
Matthew Albright, Jeff Dever, Mike Bowler, Oleg Kalnichevski

Field Summary
static String DEFAULT_CHARSET
          Default charset of string parameters
static String DEFAULT_CONTENT_TYPE
          Default content encoding of string parameters.
static String DEFAULT_TRANSFER_ENCODING
          Default transfer encoding of string parameters
 
Fields inherited from class org.apache.commons.httpclient.methods.multipart.Part
BOUNDARY, BOUNDARY_BYTES, CHARSET, CHARSET_BYTES, CONTENT_DISPOSITION, CONTENT_DISPOSITION_BYTES, CONTENT_TRANSFER_ENCODING, CONTENT_TRANSFER_ENCODING_BYTES, CONTENT_TYPE, CONTENT_TYPE_BYTES, CRLF, CRLF_BYTES, EXTRA, EXTRA_BYTES, QUOTE, QUOTE_BYTES
 
Constructor Summary
StringPart(String name, String value)
          Constructor.
StringPart(String name, String value, String charset)
          Constructor.
 
Method Summary
protected  long lengthOfData()
          Return the length of the data.
protected  void sendData(OutputStream out)
          Writes the data to the given OutputStream.
 void setCharSet(String charSet)
          Sets the character encoding.
 
Methods inherited from class org.apache.commons.httpclient.methods.multipart.PartBase
getCharSet, getContentType, getName, getTransferEncoding, setContentType, setName, setTransferEncoding
 
Methods inherited from class org.apache.commons.httpclient.methods.multipart.Part
getBoundary, getLengthOfParts, getLengthOfParts, getPartBoundary, isRepeatable, length, send, sendContentTypeHeader, sendDispositionHeader, sendEnd, sendEndOfHeader, sendParts, sendParts, sendStart, sendTransferEncodingHeader, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

DEFAULT_CONTENT_TYPE

public static final String DEFAULT_CONTENT_TYPE
Default content encoding of string parameters.

See Also:
Constant Field Values

DEFAULT_CHARSET

public static final String DEFAULT_CHARSET
Default charset of string parameters

See Also:
Constant Field Values

DEFAULT_TRANSFER_ENCODING

public static final String DEFAULT_TRANSFER_ENCODING
Default transfer encoding of string parameters

See Also:
Constant Field Values
Constructor Detail

StringPart

public StringPart(String name,
                  String value,
                  String charset)
Constructor.

Parameters:
name - The name of the part
value - the string to post
charset - the charset to be used to encode the string, if null the default is used

StringPart

public StringPart(String name,
                  String value)
Constructor.

Parameters:
name - The name of the part
value - the string to post
Method Detail

sendData

protected void sendData(OutputStream out)
                 throws IOException
Writes the data to the given OutputStream.

Specified by:
sendData in class Part
Parameters:
out - the OutputStream to write to
Throws:
IOException - if there is a write error

lengthOfData

protected long lengthOfData()
                     throws IOException
Return the length of the data.

Specified by:
lengthOfData in class Part
Returns:
The length of the data.
Throws:
IOException - If an IO problem occurs
See Also:
Part.lengthOfData()

setCharSet

public void setCharSet(String charSet)
Description copied from class: PartBase
Sets the character encoding.

Overrides:
setCharSet in class PartBase
Parameters:
charSet - the character encoding, or null to exclude the character encoding header


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 167 10661532634 10265 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/ByteArrayPartSource.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/ByteAr100644 0 0 14345 10661532627 31301 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource

No usage of org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 154 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/FilePart.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/FilePa100644 0 0 14167 10661532627 31255 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.multipart.FilePart (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.multipart.FilePart

No usage of org.apache.commons.httpclient.methods.multipart.FilePart



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 162 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/FilePartSource.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/FilePa100644 0 0 14263 10661532627 31252 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.multipart.FilePartSource (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.multipart.FilePartSource

No usage of org.apache.commons.httpclient.methods.multipart.FilePartSource



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 172 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/MultipartRequestEntity.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/Multip100644 0 0 14403 10661532627 31360 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity

No usage of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/Part.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/Part.h100644 0 0 45037 10661532627 31251 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.multipart.Part (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.multipart.Part

Packages that use Part
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
org.apache.commons.httpclient.methods.multipart Provides Multipart support classes for the MultipartPostMethod
 

Uses of Part in org.apache.commons.httpclient.methods
 

Methods in org.apache.commons.httpclient.methods that return Part
 Part[] MultipartPostMethod.getParts()
          Deprecated. Returns all parts.
 

Methods in org.apache.commons.httpclient.methods with parameters of type Part
 void MultipartPostMethod.addPart(Part part)
          Deprecated. Adds a part.
 

Uses of Part in org.apache.commons.httpclient.methods.multipart
 

Subclasses of Part in org.apache.commons.httpclient.methods.multipart
 class FilePart
          This class implements a part of a Multipart post object that consists of a file.
 class PartBase
          Provides setters and getters for the basic Part properties.
 class StringPart
          Simple string parameter for a multipart post
 

Fields in org.apache.commons.httpclient.methods.multipart declared as Part
protected  Part[] MultipartRequestEntity.parts
          The MIME parts as set by the constructor
 

Methods in org.apache.commons.httpclient.methods.multipart with parameters of type Part
static long Part.getLengthOfParts(Part[] parts)
          Return the total sum of all parts and that of the last boundary
static long Part.getLengthOfParts(Part[] parts, byte[] partBoundary)
          Gets the length of the multipart message including the given parts.
static void Part.sendParts(OutputStream out, Part[] parts)
          Write all parts and the last boundary to the specified output stream.
static void Part.sendParts(OutputStream out, Part[] parts, byte[] partBoundary)
          Write all parts and the last boundary to the specified output stream.
 

Constructors in org.apache.commons.httpclient.methods.multipart with parameters of type Part
MultipartRequestEntity(Part[] parts, HttpMethodParams params)
          Creates a new multipart entity containing the given parts.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 154 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/PartBase.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/PartBa100644 0 0 21626 10661532627 31264 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.multipart.PartBase (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.multipart.PartBase

Packages that use PartBase
org.apache.commons.httpclient.methods.multipart Provides Multipart support classes for the MultipartPostMethod
 

Uses of PartBase in org.apache.commons.httpclient.methods.multipart
 

Subclasses of PartBase in org.apache.commons.httpclient.methods.multipart
 class FilePart
          This class implements a part of a Multipart post object that consists of a file.
 class StringPart
          Simple string parameter for a multipart post
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 156 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/PartSource.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/PartSo100644 0 0 30474 10661532627 31324 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.methods.multipart.PartSource (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.methods.multipart.PartSource

Packages that use PartSource
org.apache.commons.httpclient.methods.multipart Provides Multipart support classes for the MultipartPostMethod
 

Uses of PartSource in org.apache.commons.httpclient.methods.multipart
 

Classes in org.apache.commons.httpclient.methods.multipart that implement PartSource
 class ByteArrayPartSource
          A PartSource that reads from a byte array.
 class FilePartSource
          A PartSource that reads from a File.
 

Methods in org.apache.commons.httpclient.methods.multipart that return PartSource
protected  PartSource FilePart.getSource()
          Returns the source of the file part.
 

Constructors in org.apache.commons.httpclient.methods.multipart with parameters of type PartSource
FilePart(String name, PartSource partSource)
          FilePart Constructor.
FilePart(String name, PartSource partSource, String contentType, String charset)
          FilePart Constructor.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 156 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/StringPart.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/class-use/String100644 0 0 14213 10661532627 31353 0ustar 0 0 Uses of Class org.apache.commons.httpclient.methods.multipart.StringPart (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.methods.multipart.StringPart

No usage of org.apache.commons.httpclient.methods.multipart.StringPart



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/package-frame.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/package-frame.ht100644 0 0 4343 10661532627 31266 0ustar 0 0 org.apache.commons.httpclient.methods.multipart (HttpClient 3.1 API) org.apache.commons.httpclient.methods.multipart
Interfaces 
PartSource
Classes 
ByteArrayPartSource
FilePart
FilePartSource
MultipartRequestEntity
Part
PartBase
StringPart
././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/package-summary.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/package-summary.100644 0 0 23454 10661532627 31361 0ustar 0 0 org.apache.commons.httpclient.methods.multipart (HttpClient 3.1 API)

Package org.apache.commons.httpclient.methods.multipart

Provides Multipart support classes for the MultipartPostMethod.

See:
          Description

Interface Summary
PartSource An interface for providing access to data when posting MultiPart messages.
 

Class Summary
ByteArrayPartSource A PartSource that reads from a byte array.
FilePart This class implements a part of a Multipart post object that consists of a file.
FilePartSource A PartSource that reads from a File.
MultipartRequestEntity Implements a request entity suitable for an HTTP multipart POST method.
Part Abstract class for one Part of a multipart post object.
PartBase Provides setters and getters for the basic Part properties.
StringPart Simple string parameter for a multipart post
 

Package org.apache.commons.httpclient.methods.multipart Description

Provides Multipart support classes for the MultipartPostMethod.

Since:
2.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/package-tree.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/package-tree.htm100644 0 0 21647 10661532627 31336 0ustar 0 0 org.apache.commons.httpclient.methods.multipart Class Hierarchy (HttpClient 3.1 API)

Hierarchy For Package org.apache.commons.httpclient.methods.multipart

Package Hierarchies:
All Packages

Class Hierarchy

  • java.lang.Object
    • org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource (implements org.apache.commons.httpclient.methods.multipart.PartSource)
    • org.apache.commons.httpclient.methods.multipart.FilePartSource (implements org.apache.commons.httpclient.methods.multipart.PartSource)
    • org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity (implements org.apache.commons.httpclient.methods.RequestEntity)
    • org.apache.commons.httpclient.methods.multipart.Part
      • org.apache.commons.httpclient.methods.multipart.PartBase
        • org.apache.commons.httpclient.methods.multipart.FilePart
        • org.apache.commons.httpclient.methods.multipart.StringPart

Interface Hierarchy

  • org.apache.commons.httpclient.methods.multipart.PartSource


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/package-use.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/multipart/package-use.html100644 0 0 22453 10661532627 31343 0ustar 0 0 Uses of Package org.apache.commons.httpclient.methods.multipart (HttpClient 3.1 API)

Uses of Package
org.apache.commons.httpclient.methods.multipart

Packages that use org.apache.commons.httpclient.methods.multipart
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
org.apache.commons.httpclient.methods.multipart Provides Multipart support classes for the MultipartPostMethod
 

Classes in org.apache.commons.httpclient.methods.multipart used by org.apache.commons.httpclient.methods
Part
          Abstract class for one Part of a multipart post object.
 

Classes in org.apache.commons.httpclient.methods.multipart used by org.apache.commons.httpclient.methods.multipart
Part
          Abstract class for one Part of a multipart post object.
PartBase
          Provides setters and getters for the basic Part properties.
PartSource
          An interface for providing access to data when posting MultiPart messages.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/package-frame.html100644 0 0 6064 10661532627 27600 0ustar 0 0 org.apache.commons.httpclient.methods (HttpClient 3.1 API) org.apache.commons.httpclient.methods
Interfaces 
RequestEntity
Classes 
ByteArrayRequestEntity
DeleteMethod
EntityEnclosingMethod
ExpectContinueMethod
FileRequestEntity
GetMethod
HeadMethod
InputStreamRequestEntity
MultipartPostMethod
OptionsMethod
PostMethod
PutMethod
StringRequestEntity
TraceMethod
commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/package-summary.html100644 0 0 27430 10661532627 30223 0ustar 0 0 org.apache.commons.httpclient.methods (HttpClient 3.1 API)

Package org.apache.commons.httpclient.methods

Classes implementing HttpMethod for the base HTTP methods.

See:
          Description

Interface Summary
RequestEntity  
 

Class Summary
ByteArrayRequestEntity A RequestEntity that contains an array of bytes.
DeleteMethod Implements the HTTP DELETE method.
EntityEnclosingMethod This abstract class serves as a foundation for all HTTP methods that can enclose an entity within requests
ExpectContinueMethod This abstract class serves as a foundation for all HTTP methods that support 'Expect: 100-continue' handshake.
FileRequestEntity A RequestEntity that represents a File.
GetMethod Implements the HTTP GET method.
HeadMethod Implements the HTTP HEAD method.
InputStreamRequestEntity A RequestEntity that contains an InputStream.
MultipartPostMethod Deprecated. Use MultipartRequestEntity in conjunction with PostMethod instead.
OptionsMethod Implements the HTTP OPTIONS method.
PostMethod Implements the HTTP POST method.
PutMethod Implements the HTTP PUT method.
StringRequestEntity A RequestEntity that contains a String.
TraceMethod Implements the HTTP TRACE method.
 

Package org.apache.commons.httpclient.methods Description

Classes implementing HttpMethod for the base HTTP methods.

Since:
1.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/package-tree.html100644 0 0 25247 10661532627 27471 0ustar 0 0 org.apache.commons.httpclient.methods Class Hierarchy (HttpClient 3.1 API)

Hierarchy For Package org.apache.commons.httpclient.methods

Package Hierarchies:
All Packages

Class Hierarchy

Interface Hierarchy



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/methods/package-use.html100644 0 0 22174 10661532627 27322 0ustar 0 0 Uses of Package org.apache.commons.httpclient.methods (HttpClient 3.1 API)

Uses of Package
org.apache.commons.httpclient.methods

Packages that use org.apache.commons.httpclient.methods
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
org.apache.commons.httpclient.methods.multipart Provides Multipart support classes for the MultipartPostMethod
 

Classes in org.apache.commons.httpclient.methods used by org.apache.commons.httpclient.methods
EntityEnclosingMethod
          This abstract class serves as a foundation for all HTTP methods that can enclose an entity within requests
ExpectContinueMethod
           This abstract class serves as a foundation for all HTTP methods that support 'Expect: 100-continue' handshake.
RequestEntity
           
 

Classes in org.apache.commons.httpclient.methods used by org.apache.commons.httpclient.methods.multipart
RequestEntity
           
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/package-frame.html100644 0 0 17450 10661532627 26156 0ustar 0 0 org.apache.commons.httpclient (HttpClient 3.1 API) org.apache.commons.httpclient
Interfaces 
Credentials
HttpConnectionManager
HttpMethod
HttpMethodRetryHandler
MethodRetryHandler
Classes 
ChunkedInputStream
ChunkedOutputStream
ConnectMethod
ContentLengthInputStream
Cookie
DefaultHttpMethodRetryHandler
DefaultMethodRetryHandler
Header
HeaderElement
HeaderGroup
HostConfiguration
HttpClient
HttpConnection
HttpConstants
HttpHost
HttpMethodBase
HttpParser
HttpState
HttpStatus
HttpsURL
HttpURL
HttpVersion
MultiThreadedHttpConnectionManager
NameValuePair
NTCredentials
ProxyClient
ProxyClient.ConnectResponse
ProxyHost
SimpleHttpConnectionManager
StatusLine
URI
URI.LocaleToCharsetMap
UsernamePasswordCredentials
Exceptions 
CircularRedirectException
ConnectionPoolTimeoutException
ConnectTimeoutException
HttpContentTooLargeException
HttpException
HttpRecoverableException
InvalidRedirectLocationException
NoHttpResponseException
ProtocolException
RedirectException
URI.DefaultCharsetChanged
URIException
Errors 
HttpClientError
commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/package-summary.html100644 0 0 74164 10661532627 26566 0ustar 0 0 org.apache.commons.httpclient (HttpClient 3.1 API)

Package org.apache.commons.httpclient

Classes and interfaces supporting the client side of the HTTP protocol.

See:
          Description

Interface Summary
Credentials Authentication credentials.
HttpConnectionManager An interface for classes that manage HttpConnections.
HttpMethod HttpMethod interface represents a request to be sent via a HTTP connection and a corresponding response.
HttpMethodRetryHandler A handler for determining if an HttpMethod should be retried after a recoverable exception during execution.
MethodRetryHandler Deprecated. use HttpMethodRetryHandler
 

Class Summary
ChunkedInputStream Transparently coalesces chunks of a HTTP stream that uses Transfer-Encoding chunked.
ChunkedOutputStream Implements HTTP chunking support.
ConnectMethod Establishes a tunneled HTTP connection via the CONNECT method.
ContentLengthInputStream Cuts the wrapped InputStream off after a specified number of bytes.
Cookie HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.
DefaultHttpMethodRetryHandler The default HttpMethodRetryHandler used by HttpMethods.
DefaultMethodRetryHandler Deprecated. use DefaultHttpMethodRetryHandler
Header An HTTP header.
HeaderElement One element of an HTTP header's value.
HeaderGroup A class for combining a set of headers.
HostConfiguration Holds all of the variables needed to describe an HTTP connection to a host.
HttpClient An HTTP "user-agent", containing an HTTP state and one or more HTTP connections, to which HTTP methods can be applied.
HttpConnection An abstraction of an HTTP InputStream and OutputStream pair, together with the relevant attributes.
HttpConstants Deprecated. use EncodingUtil class
HttpHost Holds all of the variables needed to describe an HTTP connection to a host.
HttpMethodBase An abstract base implementation of HttpMethod.
HttpParser A utility class for parsing http header values according to RFC-2616 Section 4 and 19.3.
HttpState A container for HTTP attributes that may persist from request to request, such as cookies and authentication credentials.
HttpStatus Constants enumerating the HTTP status codes.
HttpsURL The HTTPS URL.
HttpURL The HTTP URL.
HttpVersion HTTP version, as specified in RFC 2616.
MultiThreadedHttpConnectionManager Manages a set of HttpConnections for various HostConfigurations.
NameValuePair A simple class encapsulating a name/value pair.
NTCredentials Credentials for use with the NTLM authentication scheme which requires additional information.
ProxyClient A client that provides sockets for communicating through HTTP proxies via the HTTP CONNECT method.
ProxyClient.ConnectResponse Contains the method used to execute the connect along with the created socket.
ProxyHost Holds all of the variables needed to describe an HTTP connection to a proxy.
SimpleHttpConnectionManager A connection manager that provides access to a single HttpConnection.
StatusLine Represents a Status-Line as returned from a HTTP server.
URI The interface for the URI(Uniform Resource Identifiers) version of RFC 2396.
URI.LocaleToCharsetMap A mapping to determine the (somewhat arbitrarily) preferred charset for a given locale.
UsernamePasswordCredentials Username and password Credentials.
 

Exception Summary
CircularRedirectException Signals a circular redirect
ConnectionPoolTimeoutException A timeout while connecting waiting for an available connection from an HttpConnectionManager.
ConnectTimeoutException A timeout while connecting to an HTTP server or waiting for an available connection from an HttpConnectionManager.
HttpContentTooLargeException Signals that the response content was larger than anticipated.
HttpException Signals that an HTTP or HttpClient exception has occurred.
HttpRecoverableException Deprecated. no longer used
InvalidRedirectLocationException Signals violation of HTTP specification caused by an invalid redirect location
NoHttpResponseException Signals that the target server failed to respond with a valid HTTP response.
ProtocolException Signals that an HTTP protocol violation has occurred.
RedirectException Signals violation of HTTP specification caused by an invalid redirect
URI.DefaultCharsetChanged The charset-changed normal operation to represent to be required to alert to user the fact the default charset is changed.
URIException The URI parsing and escape encoding exception.
 

Error Summary
HttpClientError Signals that an error has occurred.
 

Package org.apache.commons.httpclient Description

Classes and interfaces supporting the client side of the HTTP protocol.

The HttpClient component supports the client-side of RFC 1945 (HTTP/1.0) and RFC 2616 (HTTP/1.1), several related specifications (RFC 2109 (Cookies), RFC 2617 (HTTP Authentication), etc.), and provides a framework by which new request types (methods) or HTTP extensions can can be easily created or supported.

The basis for the abstraction is provided by three types:

    HttpConnection
    represents a network connection to some HTTP host.
    HttpMethod
    represents a request to be made over some HttpConnection and contains the server's response.
    HttpState
    contains the HTTP attributes that may persist from request to request, such as cookies and authentication credentials.

and several simple bean-style classes:

HttpClient provides a simple "user-agent" implementation that will suffice for many applications, but whose use is not required.

HttpClient also provides several utilities that may be useful when extending the framework:

    HttpMethodBase
    an abstract base implementation of HttpMethod, which may be extended to create new method types or to support additional protocol HTTP features.
    HttpStatus
    an enumeration of HttpStatus codes.
    ChunkedOutputStream
    an OutputStream wrapper supporting the "chunked" transfer encoding.
    ChunkedInputStream
    an InputStream wrapper supporting the "chunked" transfer encoding.
    URIUtil
    provides utilities for encoding and decoding URI's in the %HH format.

HttpClient Configuration with Java Properties

Java properties can be set at run time with the -Dname=value command line arguments to the application that uses HttpClient. These properties can also be set programaticly by calling System.getProperties().setProperty(name, value). This is the list of properties that HttpClient recognizes:
Name Type Effect
httpclient.useragent String Sets the User-Agent string to be sent on every HTTP request.
httpclient.authentication.preemptive boolean Sends authorization credentials without requiring explicit requests from the web server



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/package-tree.html100644 0 0 50435 10661532627 26023 0ustar 0 0 org.apache.commons.httpclient Class Hierarchy (HttpClient 3.1 API)

Hierarchy For Package org.apache.commons.httpclient

Package Hierarchies:
All Packages

Class Hierarchy

Interface Hierarchy



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/package-use.html100644 0 0 104510 10661532627 25672 0ustar 0 0 Uses of Package org.apache.commons.httpclient (HttpClient 3.1 API)

Uses of Package
org.apache.commons.httpclient

Packages that use org.apache.commons.httpclient
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods. 
org.apache.commons.httpclient.params HttpClient preferences framework. 
org.apache.commons.httpclient.protocol Provides protocol specific socket factory handling. 
org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient. 
 

Classes in org.apache.commons.httpclient used by org.apache.commons.httpclient
ConnectionPoolTimeoutException
          A timeout while connecting waiting for an available connection from an HttpConnectionManager.
ConnectMethod
          Establishes a tunneled HTTP connection via the CONNECT method.
ConnectTimeoutException
          A timeout while connecting to an HTTP server or waiting for an available connection from an HttpConnectionManager.
Cookie
           HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.
Credentials
          Authentication credentials.
Header
          An HTTP header.
HeaderElement
          One element of an HTTP header's value.
HeaderGroup
          A class for combining a set of headers.
HostConfiguration
          Holds all of the variables needed to describe an HTTP connection to a host.
HttpConnection
          An abstraction of an HTTP InputStream and OutputStream pair, together with the relevant attributes.
HttpConnectionManager
          An interface for classes that manage HttpConnections.
HttpException
          Signals that an HTTP or HttpClient exception has occurred.
HttpHost
          Holds all of the variables needed to describe an HTTP connection to a host.
HttpMethod
           HttpMethod interface represents a request to be sent via a HTTP connection and a corresponding response.
HttpMethodBase
          An abstract base implementation of HttpMethod.
HttpMethodRetryHandler
          A handler for determining if an HttpMethod should be retried after a recoverable exception during execution.
HttpRecoverableException
          Deprecated. no longer used
HttpState
           A container for HTTP attributes that may persist from request to request, such as cookies and authentication credentials.
HttpsURL
          The HTTPS URL.
HttpURL
          The HTTP URL.
HttpVersion
          HTTP version, as specified in RFC 2616.
MethodRetryHandler
          Deprecated. use HttpMethodRetryHandler
NameValuePair
          A simple class encapsulating a name/value pair.
ProtocolException
          Signals that an HTTP protocol violation has occurred.
ProxyClient.ConnectResponse
          Contains the method used to execute the connect along with the created socket.
ProxyHost
          Holds all of the variables needed to describe an HTTP connection to a proxy.
RedirectException
          Signals violation of HTTP specification caused by an invalid redirect
StatusLine
          Represents a Status-Line as returned from a HTTP server.
URI
          The interface for the URI(Uniform Resource Identifiers) version of RFC 2396.
URI.DefaultCharsetChanged
          The charset-changed normal operation to represent to be required to alert to user the fact the default charset is changed.
URIException
          The URI parsing and escape encoding exception.
UsernamePasswordCredentials
          Username and password Credentials.
 

Classes in org.apache.commons.httpclient used by org.apache.commons.httpclient.auth
Credentials
          Authentication credentials.
Header
          An HTTP header.
HttpConnection
          An abstraction of an HTTP InputStream and OutputStream pair, together with the relevant attributes.
HttpException
          Signals that an HTTP or HttpClient exception has occurred.
HttpMethod
           HttpMethod interface represents a request to be sent via a HTTP connection and a corresponding response.
HttpState
           A container for HTTP attributes that may persist from request to request, such as cookies and authentication credentials.
NTCredentials
          Credentials for use with the NTLM authentication scheme which requires additional information.
ProtocolException
          Signals that an HTTP protocol violation has occurred.
UsernamePasswordCredentials
          Username and password Credentials.
 

Classes in org.apache.commons.httpclient used by org.apache.commons.httpclient.cookie
Cookie
           HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.
Header
          An HTTP header.
HttpException
          Signals that an HTTP or HttpClient exception has occurred.
NameValuePair
          A simple class encapsulating a name/value pair.
ProtocolException
          Signals that an HTTP protocol violation has occurred.
 

Classes in org.apache.commons.httpclient used by org.apache.commons.httpclient.methods
HttpConnection
          An abstraction of an HTTP InputStream and OutputStream pair, together with the relevant attributes.
HttpException
          Signals that an HTTP or HttpClient exception has occurred.
HttpMethod
           HttpMethod interface represents a request to be sent via a HTTP connection and a corresponding response.
HttpMethodBase
          An abstract base implementation of HttpMethod.
HttpState
           A container for HTTP attributes that may persist from request to request, such as cookies and authentication credentials.
NameValuePair
          A simple class encapsulating a name/value pair.
 

Classes in org.apache.commons.httpclient used by org.apache.commons.httpclient.params
HostConfiguration
          Holds all of the variables needed to describe an HTTP connection to a host.
HttpVersion
          HTTP version, as specified in RFC 2616.
 

Classes in org.apache.commons.httpclient used by org.apache.commons.httpclient.protocol
ConnectTimeoutException
          A timeout while connecting to an HTTP server or waiting for an available connection from an HttpConnectionManager.
 

Classes in org.apache.commons.httpclient used by org.apache.commons.httpclient.util
HttpConnection
          An abstraction of an HTTP InputStream and OutputStream pair, together with the relevant attributes.
HttpConnectionManager
          An interface for classes that manage HttpConnections.
HttpMethod
           HttpMethod interface represents a request to be sent via a HTTP connection and a corresponding response.
NameValuePair
          A simple class encapsulating a name/value pair.
URI
          The interface for the URI(Uniform Resource Identifiers) version of RFC 2396.
URIException
          The URI parsing and escape encoding exception.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/DefaultHttpParams.html100644 0 0 154620 10661532627 30367 0ustar 0 0 DefaultHttpParams (HttpClient 3.1 API)

org.apache.commons.httpclient.params
Class DefaultHttpParams

java.lang.Object
  extended by org.apache.commons.httpclient.params.DefaultHttpParams
All Implemented Interfaces:
Serializable, Cloneable, HttpParams
Direct Known Subclasses:
HostParams, HttpConnectionParams, HttpMethodParams

public class DefaultHttpParams
extends Object
implements HttpParams, Serializable, Cloneable

This class represents a collection of HTTP protocol parameters. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.

Since:
3.0
Version:
$Revision: 510589 $
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Constructor Summary
DefaultHttpParams()
          Creates a new collection of parameters with the collection returned by getDefaultParams() as a parent.
DefaultHttpParams(HttpParams defaults)
          Creates a new collection of parameters with the given parent.
 
Method Summary
 void clear()
          Removes all parameters from this collection.
 Object clone()
          Clones this collection of parameters.
 boolean getBooleanParameter(String name, boolean defaultValue)
          Returns a Boolean parameter value with the given name.
static HttpParams getDefaultParams()
          Gets the default HttpParams to be used.
 HttpParams getDefaults()
          Returns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself
 double getDoubleParameter(String name, double defaultValue)
          Returns a Double parameter value with the given name.
 int getIntParameter(String name, int defaultValue)
          Returns an Integer parameter value with the given name.
 long getLongParameter(String name, long defaultValue)
          Returns a Long parameter value with the given name.
 Object getParameter(String name)
          Returns a parameter value with the given name.
 boolean isParameterFalse(String name)
          Returns true if the parameter is either not set or is false, false otherwise.
 boolean isParameterSet(String name)
          Returns true if the parameter is set at any level, false otherwise.
 boolean isParameterSetLocally(String name)
          Returns true if the parameter is set locally, false otherwise.
 boolean isParameterTrue(String name)
          Returns true if the parameter is set and is true, false otherwise.
 void setBooleanParameter(String name, boolean value)
          Assigns a Boolean to the parameter with the given name
 void setDefaults(HttpParams params)
          Assigns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself
 void setDoubleParameter(String name, double value)
          Assigns a Double to the parameter with the given name
static void setHttpParamsFactory(HttpParamsFactory httpParamsFactory)
          Sets the factory that will provide the default HttpParams.
 void setIntParameter(String name, int value)
          Assigns an Integer to the parameter with the given name
 void setLongParameter(String name, long value)
          Assigns a Long to the parameter with the given name
 void setParameter(String name, Object value)
          Assigns the value to the parameter with the given name
 void setParameters(String[] names, Object value)
          Assigns the value to all the parameter with the given names
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

DefaultHttpParams

public DefaultHttpParams(HttpParams defaults)
Creates a new collection of parameters with the given parent. The collection will defer to its parent for a default value if a particular parameter is not explicitly set in the collection itself.

Parameters:
defaults - the parent collection to defer to, if a parameter is not explictly set in the collection itself.

DefaultHttpParams

public DefaultHttpParams()
Creates a new collection of parameters with the collection returned by getDefaultParams() as a parent. The collection will defer to its parent for a default value if a particular parameter is not explicitly set in the collection itself.

See Also:
getDefaultParams()
Method Detail

getDefaultParams

public static HttpParams getDefaultParams()
Gets the default HttpParams to be used.

Returns:
the value returned from HttpParamsFactory#getDefaultParams()
See Also:
HttpParamsFactory.getDefaultParams()

setHttpParamsFactory

public static void setHttpParamsFactory(HttpParamsFactory httpParamsFactory)
Sets the factory that will provide the default HttpParams.

Parameters:
httpParamsFactory - an instance of HttpParamsFactory
See Also:
getDefaultParams()

getDefaults

public HttpParams getDefaults()
Description copied from interface: HttpParams
Returns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself

Specified by:
getDefaults in interface HttpParams
Returns:
the parent collection to defer to, if a particular parameter is not explictly set in the collection itself.
See Also:
HttpParams.setDefaults(HttpParams)

setDefaults

public void setDefaults(HttpParams params)
Description copied from interface: HttpParams
Assigns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself

Specified by:
setDefaults in interface HttpParams
Parameters:
params - the parent collection to defer to, if a particular parameter is not explictly set in the collection itself.
See Also:
HttpParams.getDefaults()

getParameter

public Object getParameter(String name)
Description copied from interface: HttpParams
Returns a parameter value with the given name. If the parameter is not explicitly defined in this collection, its value will be drawn from a higer level collection at which this parameter is defined. If the parameter is not explicitly set anywhere up the hierarchy, null value is returned.

Specified by:
getParameter in interface HttpParams
Parameters:
name - the parent name.
Returns:
an object that represents the value of the parameter.
See Also:
HttpParams.setParameter(String, Object)

setParameter

public void setParameter(String name,
                         Object value)
Description copied from interface: HttpParams
Assigns the value to the parameter with the given name

Specified by:
setParameter in interface HttpParams
Parameters:
name - parameter name
value - parameter value

setParameters

public void setParameters(String[] names,
                          Object value)
Assigns the value to all the parameter with the given names

Parameters:
names - array of parameter name
value - parameter value

getLongParameter

public long getLongParameter(String name,
                             long defaultValue)
Description copied from interface: HttpParams
Returns a Long parameter value with the given name. If the parameter is not explicitly defined in this collection, its value will be drawn from a higer level collection at which this parameter is defined. If the parameter is not explicitly set anywhere up the hierarchy, the default value is returned.

Specified by:
getLongParameter in interface HttpParams
Parameters:
name - the parent name.
defaultValue - the default value.
Returns:
a Long that represents the value of the parameter.
See Also:
HttpParams.setLongParameter(String, long)

setLongParameter

public void setLongParameter(String name,
                             long value)
Description copied from interface: HttpParams
Assigns a Long to the parameter with the given name

Specified by:
setLongParameter in interface HttpParams
Parameters:
name - parameter name
value - parameter value

getIntParameter

public int getIntParameter(String name,
                           int defaultValue)
Description copied from interface: HttpParams
Returns an Integer parameter value with the given name. If the parameter is not explicitly defined in this collection, its value will be drawn from a higer level collection at which this parameter is defined. If the parameter is not explicitly set anywhere up the hierarchy, the default value is returned.

Specified by:
getIntParameter in interface HttpParams
Parameters:
name - the parent name.
defaultValue - the default value.
Returns:
a Integer that represents the value of the parameter.
See Also:
HttpParams.setIntParameter(String, int)

setIntParameter

public void setIntParameter(String name,
                            int value)
Description copied from interface: HttpParams
Assigns an Integer to the parameter with the given name

Specified by:
setIntParameter in interface HttpParams
Parameters:
name - parameter name
value - parameter value

getDoubleParameter

public double getDoubleParameter(String name,
                                 double defaultValue)
Description copied from interface: HttpParams
Returns a Double parameter value with the given name. If the parameter is not explicitly defined in this collection, its value will be drawn from a higer level collection at which this parameter is defined. If the parameter is not explicitly set anywhere up the hierarchy, the default value is returned.

Specified by:
getDoubleParameter in interface HttpParams
Parameters:
name - the parent name.
defaultValue - the default value.
Returns:
a Double that represents the value of the parameter.
See Also:
HttpParams.setDoubleParameter(String, double)

setDoubleParameter

public void setDoubleParameter(String name,
                               double value)
Description copied from interface: HttpParams
Assigns a Double to the parameter with the given name

Specified by:
setDoubleParameter in interface HttpParams
Parameters:
name - parameter name
value - parameter value

getBooleanParameter

public boolean getBooleanParameter(String name,
                                   boolean defaultValue)
Description copied from interface: HttpParams
Returns a Boolean parameter value with the given name. If the parameter is not explicitly defined in this collection, its value will be drawn from a higer level collection at which this parameter is defined. If the parameter is not explicitly set anywhere up the hierarchy, the default value is returned.

Specified by:
getBooleanParameter in interface HttpParams
Parameters:
name - the parent name.
defaultValue - the default value.
Returns:
a Boolean that represents the value of the parameter.
See Also:
HttpParams.setBooleanParameter(String, boolean)

setBooleanParameter

public void setBooleanParameter(String name,
                                boolean value)
Description copied from interface: HttpParams
Assigns a Boolean to the parameter with the given name

Specified by:
setBooleanParameter in interface HttpParams
Parameters:
name - parameter name
value - parameter value

isParameterSet

public boolean isParameterSet(String name)
Description copied from interface: HttpParams
Returns true if the parameter is set at any level, false otherwise.

Specified by:
isParameterSet in interface HttpParams
Parameters:
name - parameter name
Returns:
true if the parameter is set at any level, false otherwise.

isParameterSetLocally

public boolean isParameterSetLocally(String name)
Description copied from interface: HttpParams
Returns true if the parameter is set locally, false otherwise.

Specified by:
isParameterSetLocally in interface HttpParams
Parameters:
name - parameter name
Returns:
true if the parameter is set locally, false otherwise.

isParameterTrue

public boolean isParameterTrue(String name)
Description copied from interface: HttpParams
Returns true if the parameter is set and is true, false otherwise.

Specified by:
isParameterTrue in interface HttpParams
Parameters:
name - parameter name
Returns:
true if the parameter is set and is true, false otherwise.

isParameterFalse

public boolean isParameterFalse(String name)
Description copied from interface: HttpParams
Returns true if the parameter is either not set or is false, false otherwise.

Specified by:
isParameterFalse in interface HttpParams
Parameters:
name - parameter name
Returns:
true if the parameter is either not set or is false, false otherwise.

clear

public void clear()
Removes all parameters from this collection.


clone

public Object clone()
             throws CloneNotSupportedException
Clones this collection of parameters. Please note that paramter values themselves are not cloned.

Overrides:
clone in class Object
Throws:
CloneNotSupportedException
See Also:
Serializable, Object.clone()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.ht100644 0 0 34244 10661532627 31345 0ustar 0 0 DefaultHttpParamsFactory (HttpClient 3.1 API)

org.apache.commons.httpclient.params
Class DefaultHttpParamsFactory

java.lang.Object
  extended by org.apache.commons.httpclient.params.DefaultHttpParamsFactory
All Implemented Interfaces:
HttpParamsFactory

public class DefaultHttpParamsFactory
extends Object
implements HttpParamsFactory

Since:
3.0

Constructor Summary
DefaultHttpParamsFactory()
           
 
Method Summary
protected  HttpParams createParams()
           
 HttpParams getDefaultParams()
          Gets the default parameters.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

DefaultHttpParamsFactory

public DefaultHttpParamsFactory()
Method Detail

getDefaultParams

public HttpParams getDefaultParams()
Description copied from interface: HttpParamsFactory
Gets the default parameters. This method may be called more than once and is not required to always return the same value.

Specified by:
getDefaultParams in interface HttpParamsFactory
Returns:
an instance of HttpParams

createParams

protected HttpParams createParams()


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/HostParams.html100644 0 0 54117 10661532627 27040 0ustar 0 0 HostParams (HttpClient 3.1 API)

org.apache.commons.httpclient.params
Class HostParams

java.lang.Object
  extended by org.apache.commons.httpclient.params.DefaultHttpParams
      extended by org.apache.commons.httpclient.params.HostParams
All Implemented Interfaces:
Serializable, Cloneable, HttpParams

public class HostParams
extends DefaultHttpParams

This class represents a collection of HTTP protocol parameters applicable to instances of HostConfiguration. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.

Since:
3.0
Version:
$Revision: 480424 $
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Field Summary
static String DEFAULT_HEADERS
          Defines the request headers to be sent per default with each request.
 
Constructor Summary
HostParams()
          Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent.
HostParams(HttpParams defaults)
          Creates a new collection of parameters with the given parent.
 
Method Summary
 String getVirtualHost()
          Returns the virtual host name.
 void setVirtualHost(String hostname)
          Sets the virtual host name.
 
Methods inherited from class org.apache.commons.httpclient.params.DefaultHttpParams
clear, clone, getBooleanParameter, getDefaultParams, getDefaults, getDoubleParameter, getIntParameter, getLongParameter, getParameter, isParameterFalse, isParameterSet, isParameterSetLocally, isParameterTrue, setBooleanParameter, setDefaults, setDoubleParameter, setHttpParamsFactory, setIntParameter, setLongParameter, setParameter, setParameters
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DEFAULT_HEADERS

public static final String DEFAULT_HEADERS
Defines the request headers to be sent per default with each request.

This parameter expects a value of type Collection. The collection is expected to contain Headers.

See Also:
Constant Field Values
Constructor Detail

HostParams

public HostParams()
Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent. The collection will defer to its parent for a default value if a particular parameter is not explicitly set in the collection itself.

See Also:
DefaultHttpParams.getDefaultParams()

HostParams

public HostParams(HttpParams defaults)
Creates a new collection of parameters with the given parent. The collection will defer to its parent for a default value if a particular parameter is not explicitly set in the collection itself.

Parameters:
defaults - the parent collection to defer to, if a parameter is not explictly set in the collection itself.
See Also:
DefaultHttpParams.getDefaultParams()
Method Detail

setVirtualHost

public void setVirtualHost(String hostname)
Sets the virtual host name.

Parameters:
hostname - The host name

getVirtualHost

public String getVirtualHost()
Returns the virtual host name.

Returns:
The virtual host name


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/HttpClientParams.html100644 0 0 131372 10661532627 30220 0ustar 0 0 HttpClientParams (HttpClient 3.1 API)

org.apache.commons.httpclient.params
Class HttpClientParams

java.lang.Object
  extended by org.apache.commons.httpclient.params.DefaultHttpParams
      extended by org.apache.commons.httpclient.params.HttpMethodParams
          extended by org.apache.commons.httpclient.params.HttpClientParams
All Implemented Interfaces:
Serializable, Cloneable, HttpParams

public class HttpClientParams
extends HttpMethodParams

This class represents a collection of HTTP protocol parameters applicable to instances of HttpClient. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.

Since:
3.0
Version:
$Revision: 480424 $
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Field Summary
static String ALLOW_CIRCULAR_REDIRECTS
          Defines whether circular redirects (redirects to the same location) should be allowed.
static String CONNECTION_MANAGER_CLASS
          Defines the default HTTP connection manager class.
static String CONNECTION_MANAGER_TIMEOUT
          Sets the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.
static String MAX_REDIRECTS
          Defines the maximum number of redirects to be followed.
static String PREEMPTIVE_AUTHENTICATION
          Defines whether authentication should be attempted preemptively.
static String REJECT_RELATIVE_REDIRECT
          Defines whether relative redirects should be rejected.
 
Fields inherited from class org.apache.commons.httpclient.params.HttpMethodParams
BUFFER_WARN_TRIGGER_LIMIT, COOKIE_POLICY, CREDENTIAL_CHARSET, DATE_PATTERNS, HEAD_BODY_CHECK_TIMEOUT, HTTP_CONTENT_CHARSET, HTTP_ELEMENT_CHARSET, HTTP_URI_CHARSET, MULTIPART_BOUNDARY, PROTOCOL_VERSION, REJECT_HEAD_BODY, RETRY_HANDLER, SINGLE_COOKIE_HEADER, SO_TIMEOUT, STATUS_LINE_GARBAGE_LIMIT, STRICT_TRANSFER_ENCODING, UNAMBIGUOUS_STATUS_LINE, USE_EXPECT_CONTINUE, USER_AGENT, VIRTUAL_HOST, WARN_EXTRA_INPUT
 
Constructor Summary
HttpClientParams()
          Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent.
HttpClientParams(HttpParams defaults)
          Creates a new collection of parameters with the given parent.
 
Method Summary
 Class getConnectionManagerClass()
          Returns the default HTTP connection manager class.
 long getConnectionManagerTimeout()
          Returns the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.
 boolean isAuthenticationPreemptive()
          Returns true if authentication should be attempted preemptively, false otherwise.
 void makeLenient()
          Makes the HTTP methods attempt to mimic the exact behaviour of commonly used HTTP agents, which many HTTP servers expect, even though such behaviour may violate the HTTP protocol specification (RFC 2616 and other relevant RFCs).
 void makeStrict()
          Makes the HTTP methods strictly follow the HTTP protocol specification (RFC 2616 and other relevant RFCs).
 void setAuthenticationPreemptive(boolean value)
          Sets whether authentication should be attempted preemptively.
 void setConnectionManagerClass(Class clazz)
          Sets HTTP connection manager class to be used der default.
 void setConnectionManagerTimeout(long timeout)
          Sets the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.
 
Methods inherited from class org.apache.commons.httpclient.params.HttpMethodParams
getContentCharset, getCookiePolicy, getCredentialCharset, getHttpElementCharset, getSoTimeout, getUriCharset, getVersion, getVirtualHost, setContentCharset, setCookiePolicy, setCredentialCharset, setHttpElementCharset, setSoTimeout, setUriCharset, setVersion, setVirtualHost
 
Methods inherited from class org.apache.commons.httpclient.params.DefaultHttpParams
clear, clone, getBooleanParameter, getDefaultParams, getDefaults, getDoubleParameter, getIntParameter, getLongParameter, getParameter, isParameterFalse, isParameterSet, isParameterSetLocally, isParameterTrue, setBooleanParameter, setDefaults, setDoubleParameter, setHttpParamsFactory, setIntParameter, setLongParameter, setParameter, setParameters
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

CONNECTION_MANAGER_TIMEOUT

public static final String CONNECTION_MANAGER_TIMEOUT
Sets the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.

This parameter expects a value of type Long.

See Also:
Constant Field Values

CONNECTION_MANAGER_CLASS

public static final String CONNECTION_MANAGER_CLASS
Defines the default HTTP connection manager class.

This parameter expects a value of type Class.

See Also:
Constant Field Values

PREEMPTIVE_AUTHENTICATION

public static final String PREEMPTIVE_AUTHENTICATION
Defines whether authentication should be attempted preemptively.

This parameter expects a value of type Boolean.

See Also:
Constant Field Values

REJECT_RELATIVE_REDIRECT

public static final String REJECT_RELATIVE_REDIRECT
Defines whether relative redirects should be rejected.

This parameter expects a value of type Boolean.

See Also:
Constant Field Values

MAX_REDIRECTS

public static final String MAX_REDIRECTS
Defines the maximum number of redirects to be followed. The limit on number of redirects is intended to prevent infinite loops.

This parameter expects a value of type Integer.

See Also:
Constant Field Values

ALLOW_CIRCULAR_REDIRECTS

public static final String ALLOW_CIRCULAR_REDIRECTS
Defines whether circular redirects (redirects to the same location) should be allowed. The HTTP spec is not sufficiently clear whether circular redirects are permitted, therefore optionally they can be enabled

This parameter expects a value of type Boolean.

See Also:
Constant Field Values
Constructor Detail

HttpClientParams

public HttpClientParams()
Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent. The collection will defer to its parent for a default value if a particular parameter is not explicitly set in the collection itself.

See Also:
DefaultHttpParams.getDefaultParams()

HttpClientParams

public HttpClientParams(HttpParams defaults)
Creates a new collection of parameters with the given parent. The collection will defer to its parent for a default value if a particular parameter is not explicitly set in the collection itself.

Parameters:
defaults - the parent collection to defer to, if a parameter is not explictly set in the collection itself.
See Also:
DefaultHttpParams.getDefaultParams()
Method Detail

getConnectionManagerTimeout

public long getConnectionManagerTimeout()
Returns the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.

Returns:
timeout in milliseconds.

setConnectionManagerTimeout

public void setConnectionManagerTimeout(long timeout)
Sets the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.

Parameters:
timeout - the timeout in milliseconds

getConnectionManagerClass

public Class getConnectionManagerClass()
Returns the default HTTP connection manager class.

Returns:
HTTP connection manager factory class.

setConnectionManagerClass

public void setConnectionManagerClass(Class clazz)
Sets HTTP connection manager class to be used der default.

Parameters:
clazz - HTTP connection manager factory class.

isAuthenticationPreemptive

public boolean isAuthenticationPreemptive()
Returns true if authentication should be attempted preemptively, false otherwise.

Returns:
true if authentication should be attempted preemptively, false otherwise.

setAuthenticationPreemptive

public void setAuthenticationPreemptive(boolean value)
Sets whether authentication should be attempted preemptively.

Parameters:
value - true if authentication should be attempted preemptively, false otherwise.

makeStrict

public void makeStrict()
Description copied from class: HttpMethodParams
Makes the HTTP methods strictly follow the HTTP protocol specification (RFC 2616 and other relevant RFCs). It must be noted that popular HTTP agents have different degree of HTTP protocol compliance and some HTTP serves are programmed to expect the behaviour that does not strictly adhere to the HTTP specification.

Overrides:
makeStrict in class HttpMethodParams

makeLenient

public void makeLenient()
Description copied from class: HttpMethodParams
Makes the HTTP methods attempt to mimic the exact behaviour of commonly used HTTP agents, which many HTTP servers expect, even though such behaviour may violate the HTTP protocol specification (RFC 2616 and other relevant RFCs).

Overrides:
makeLenient in class HttpMethodParams


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/HttpConnectionManagerParams.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/HttpConnectionManagerParams100644 0 0 77363 10661532627 31422 0ustar 0 0 HttpConnectionManagerParams (HttpClient 3.1 API)

org.apache.commons.httpclient.params
Class HttpConnectionManagerParams

java.lang.Object
  extended by org.apache.commons.httpclient.params.DefaultHttpParams
      extended by org.apache.commons.httpclient.params.HttpConnectionParams
          extended by org.apache.commons.httpclient.params.HttpConnectionManagerParams
All Implemented Interfaces:
Serializable, Cloneable, HttpParams

public class HttpConnectionManagerParams
extends HttpConnectionParams

This class represents a collection of HTTP protocol parameters applicable to HTTP connection managers. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.

Since:
3.0
Version:
$Revision: 480424 $
Author:
Oleg Kalnichevski, Michael Becke
See Also:
Serialized Form

Field Summary
static String MAX_HOST_CONNECTIONS
          Defines the maximum number of connections allowed per host configuration.
static String MAX_TOTAL_CONNECTIONS
          Defines the maximum number of connections allowed overall.
 
Fields inherited from class org.apache.commons.httpclient.params.HttpConnectionParams
CONNECTION_TIMEOUT, SO_LINGER, SO_RCVBUF, SO_SNDBUF, SO_TIMEOUT, STALE_CONNECTION_CHECK, TCP_NODELAY
 
Constructor Summary
HttpConnectionManagerParams()
           
 
Method Summary
 int getDefaultMaxConnectionsPerHost()
          Gets the default maximum number of connections allowed for a given host config.
 int getMaxConnectionsPerHost(HostConfiguration hostConfiguration)
          Gets the maximum number of connections to be used for a particular host config.
 int getMaxTotalConnections()
          Gets the maximum number of connections allowed.
 void setDefaultMaxConnectionsPerHost(int maxHostConnections)
          Sets the default maximum number of connections allowed for a given host config.
 void setMaxConnectionsPerHost(HostConfiguration hostConfiguration, int maxHostConnections)
          Sets the maximum number of connections to be used for the given host config.
 void setMaxTotalConnections(int maxTotalConnections)
          Sets the maximum number of connections allowed.
 
Methods inherited from class org.apache.commons.httpclient.params.HttpConnectionParams
getConnectionTimeout, getLinger, getReceiveBufferSize, getSendBufferSize, getSoTimeout, getTcpNoDelay, isStaleCheckingEnabled, setConnectionTimeout, setLinger, setReceiveBufferSize, setSendBufferSize, setSoTimeout, setStaleCheckingEnabled, setTcpNoDelay
 
Methods inherited from class org.apache.commons.httpclient.params.DefaultHttpParams
clear, clone, getBooleanParameter, getDefaultParams, getDefaults, getDoubleParameter, getIntParameter, getLongParameter, getParameter, isParameterFalse, isParameterSet, isParameterSetLocally, isParameterTrue, setBooleanParameter, setDefaults, setDoubleParameter, setHttpParamsFactory, setIntParameter, setLongParameter, setParameter, setParameters
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

MAX_HOST_CONNECTIONS

public static final String MAX_HOST_CONNECTIONS
Defines the maximum number of connections allowed per host configuration. These values only apply to the number of connections from a particular instance of HttpConnectionManager.

This parameter expects a value of type Map. The value should map instances of HostConfiguration to integers. The default value can be specified using HostConfiguration.ANY_HOST_CONFIGURATION.

See Also:
Constant Field Values

MAX_TOTAL_CONNECTIONS

public static final String MAX_TOTAL_CONNECTIONS
Defines the maximum number of connections allowed overall. This value only applies to the number of connections from a particular instance of HttpConnectionManager.

This parameter expects a value of type Integer.

See Also:
Constant Field Values
Constructor Detail

HttpConnectionManagerParams

public HttpConnectionManagerParams()
Method Detail

setDefaultMaxConnectionsPerHost

public void setDefaultMaxConnectionsPerHost(int maxHostConnections)
Sets the default maximum number of connections allowed for a given host config.

Parameters:
maxHostConnections - The default maximum.
See Also:
MAX_HOST_CONNECTIONS

setMaxConnectionsPerHost

public void setMaxConnectionsPerHost(HostConfiguration hostConfiguration,
                                     int maxHostConnections)
Sets the maximum number of connections to be used for the given host config.

Parameters:
hostConfiguration - The host config to set the maximum for. Use HostConfiguration.ANY_HOST_CONFIGURATION to configure the default value per host.
maxHostConnections - The maximum number of connections, > 0
See Also:
MAX_HOST_CONNECTIONS

getDefaultMaxConnectionsPerHost

public int getDefaultMaxConnectionsPerHost()
Gets the default maximum number of connections allowed for a given host config.

Returns:
The default maximum.
See Also:
MAX_HOST_CONNECTIONS

getMaxConnectionsPerHost

public int getMaxConnectionsPerHost(HostConfiguration hostConfiguration)
Gets the maximum number of connections to be used for a particular host config. If the value has not been specified for the given host the default value will be returned.

Parameters:
hostConfiguration - The host config.
Returns:
The maximum number of connections to be used for the given host config.
See Also:
MAX_HOST_CONNECTIONS

setMaxTotalConnections

public void setMaxTotalConnections(int maxTotalConnections)
Sets the maximum number of connections allowed.

Parameters:
maxTotalConnections - The maximum number of connections allowed.
See Also:
MAX_TOTAL_CONNECTIONS

getMaxTotalConnections

public int getMaxTotalConnections()
Gets the maximum number of connections allowed.

Returns:
The maximum number of connections allowed.
See Also:
MAX_TOTAL_CONNECTIONS


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/HttpConnectionParams.html100644 0 0 124015 10661532627 31075 0ustar 0 0 HttpConnectionParams (HttpClient 3.1 API)

org.apache.commons.httpclient.params
Class HttpConnectionParams

java.lang.Object
  extended by org.apache.commons.httpclient.params.DefaultHttpParams
      extended by org.apache.commons.httpclient.params.HttpConnectionParams
All Implemented Interfaces:
Serializable, Cloneable, HttpParams
Direct Known Subclasses:
HttpConnectionManagerParams

public class HttpConnectionParams
extends DefaultHttpParams

This class represents a collection of HTTP protocol parameters applicable to HTTP connections. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.

Since:
3.0
Version:
$Revision: 480424 $
Author:
Oleg Kalnichevski
See Also:
Serialized Form

Field Summary
static String CONNECTION_TIMEOUT
          Determines the timeout until a connection is etablished.
static String SO_LINGER
          Sets SO_LINGER with the specified linger time in seconds.
static String SO_RCVBUF
          Determines a hint the size of the underlying buffers used by the platform for incoming network I/O.
static String SO_SNDBUF
          Determines a hint the size of the underlying buffers used by the platform for outgoing network I/O.
static String SO_TIMEOUT
          Defines the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
static String STALE_CONNECTION_CHECK
          Determines whether stale connection check is to be used.
static String TCP_NODELAY
          Determines whether Nagle's algorithm is to be used.
 
Constructor Summary
HttpConnectionParams()
          Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent.
 
Method Summary
 int getConnectionTimeout()
          Returns the timeout until a connection is etablished.
 int getLinger()
          Returns linger-on-close timeout.
 int getReceiveBufferSize()
          Returns a hint the size of the underlying buffers used by the platform for incoming network I/O.
 int getSendBufferSize()
          Returns a hint the size of the underlying buffers used by the platform for outgoing network I/O.
 int getSoTimeout()
          Returns the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
 boolean getTcpNoDelay()
          Tests if Nagle's algorithm is to be used.
 boolean isStaleCheckingEnabled()
          Tests whether stale connection check is to be used.
 void setConnectionTimeout(int timeout)
          Sets the timeout until a connection is etablished.
 void setLinger(int value)
          Returns linger-on-close timeout.
 void setReceiveBufferSize(int size)
          Sets a hint the size of the underlying buffers used by the platform for incoming network I/O.
 void setSendBufferSize(int size)
          Sets a hint the size of the underlying buffers used by the platform for outgoing network I/O.
 void setSoTimeout(int timeout)
          Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
 void setStaleCheckingEnabled(boolean value)
          Defines whether stale connection check is to be used.
 void setTcpNoDelay(boolean value)
          Determines whether Nagle's algorithm is to be used.
 
Methods inherited from class org.apache.commons.httpclient.params.DefaultHttpParams
clear, clone, getBooleanParameter, getDefaultParams, getDefaults, getDoubleParameter, getIntParameter, getLongParameter, getParameter, isParameterFalse, isParameterSet, isParameterSetLocally, isParameterTrue, setBooleanParameter, setDefaults, setDoubleParameter, setHttpParamsFactory, setIntParameter, setLongParameter, setParameter, setParameters
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SO_TIMEOUT

public static final String SO_TIMEOUT
Defines the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the HTTP method parameters.

This parameter expects a value of type Integer.

See Also:
SocketOptions.SO_TIMEOUT, Constant Field Values

TCP_NODELAY

public static final String TCP_NODELAY
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 Boolean.

See Also:
SocketOptions.TCP_NODELAY, Constant Field Values

SO_SNDBUF

public static final String SO_SNDBUF
Determines a hint the size of the underlying buffers used by the platform for outgoing network I/O. This value is a suggestion to the kernel from the application about the size of buffers to use for the data to be sent over the socket.

This parameter expects a value of type Integer.

See Also:
SocketOptions.SO_SNDBUF, Constant Field Values

SO_RCVBUF

public static final String SO_RCVBUF
Determines a hint the size of the underlying buffers used by the platform for incoming network I/O. This value is a suggestion to the kernel from the application about the size of buffers to use for the data to be received over the socket.

This parameter expects a value of type Integer.

See Also:
SocketOptions.SO_RCVBUF, Constant Field Values

SO_LINGER

public static final String SO_LINGER
Sets SO_LINGER with the specified linger time in seconds. The maximum timeout value is platform specific. Value 0 implies that the option is disabled. Value -1 implies that the JRE default is used. The setting only affects socket close.

This parameter expects a value of type Integer.

See Also:
SocketOptions.SO_LINGER, Constant Field Values

CONNECTION_TIMEOUT

public static final String CONNECTION_TIMEOUT
Determines the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.

This parameter expects a value of type Integer.

See Also:
Constant Field Values

STALE_CONNECTION_CHECK

public static final String STALE_CONNECTION_CHECK
Determines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.

This parameter expects a value of type Boolean.

See Also:
Constant Field Values
Constructor Detail

HttpConnectionParams

public HttpConnectionParams()
Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent. The collection will defer to its parent for a default value if a particular parameter is not explicitly set in the collection itself.

See Also:
DefaultHttpParams.getDefaultParams()
Method Detail

getSoTimeout

public int getSoTimeout()
Returns the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the HTTP method parameters.

Returns:
timeout in milliseconds

setSoTimeout

public void setSoTimeout(int timeout)
Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the HTTP method parameters.

Parameters:
timeout - Timeout in milliseconds

setTcpNoDelay

public void setTcpNoDelay(boolean value)
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.

Parameters:
value - true if the Nagle's algorithm is to NOT be used (that is enable TCP_NODELAY), false otherwise.

getTcpNoDelay

public boolean getTcpNoDelay()
Tests if Nagle's algorithm is to be used.

Returns:
true if the Nagle's algorithm is to NOT be used (that is enable TCP_NODELAY), false otherwise.

getSendBufferSize

public int getSendBufferSize()
Returns a hint the size of the underlying buffers used by the platform for outgoing network I/O. This value is a suggestion to the kernel from the application about the size of buffers to use for the data to be sent over the socket.

Returns:
the hint size of the send buffer

setSendBufferSize

public void setSendBufferSize(int size)
Sets a hint the size of the underlying buffers used by the platform for outgoing network I/O. This value is a suggestion to the kernel from the application about the size of buffers to use for the data to be sent over the socket.

Parameters:
size - the hint size of the send buffer

getReceiveBufferSize

public int getReceiveBufferSize()
Returns a hint the size of the underlying buffers used by the platform for incoming network I/O. This value is a suggestion to the kernel from the application about the size of buffers to use for the data to be received over the socket.

Returns:
the hint size of the send buffer

setReceiveBufferSize

public void setReceiveBufferSize(int size)
Sets a hint the size of the underlying buffers used by the platform for incoming network I/O. This value is a suggestion to the kernel from the application about the size of buffers to use for the data to be received over the socket.

Parameters:
size - the hint size of the send buffer

getLinger

public int getLinger()
Returns linger-on-close timeout. Value 0 implies that the option is disabled. Value -1 implies that the JRE default is used.

Returns:
the linger-on-close timeout

setLinger

public void setLinger(int value)
Returns linger-on-close timeout. This option disables/enables immediate return from a close() of a TCP Socket. Enabling this option with a non-zero Integer timeout means that a close() will block pending the transmission and acknowledgement of all data written to the peer, at which point the socket is closed gracefully. Value 0 implies that the option is disabled. Value -1 implies that the JRE default is used.

Parameters:
value - the linger-on-close timeout

getConnectionTimeout

public int getConnectionTimeout()
Returns the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.

Returns:
timeout in milliseconds.

setConnectionTimeout

public void setConnectionTimeout(int timeout)
Sets the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.

Parameters:
timeout - Timeout in milliseconds.

isStaleCheckingEnabled

public boolean isStaleCheckingEnabled()
Tests whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.

Returns:
true if stale connection check is to be used, false otherwise.

setStaleCheckingEnabled

public void setStaleCheckingEnabled(boolean value)
Defines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.

Parameters:
value - true if stale connection check is to be used, false otherwise.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/HttpMethodParams.html100644 0 0 221214 10661532627 30215 0ustar 0 0 HttpMethodParams (HttpClient 3.1 API)

org.apache.commons.httpclient.params
Class HttpMethodParams

java.lang.Object
  extended by org.apache.commons.httpclient.params.DefaultHttpParams
      extended by org.apache.commons.httpclient.params.HttpMethodParams
All Implemented Interfaces:
Serializable, Cloneable, HttpParams
Direct Known Subclasses:
HttpClientParams

public class HttpMethodParams
extends DefaultHttpParams

This class represents a collection of HTTP protocol parameters applicable to HTTP methods. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.

Since:
3.0
Version:
$Revision: 483949 $
Author:
Oleg Kalnichevski, Christian Kohlschuetter
See Also:
Serialized Form

Field Summary
static String BUFFER_WARN_TRIGGER_LIMIT
          Sets the maximum buffered response size (in bytes) that triggers no warning.
static String COOKIE_POLICY
          Defines cookie policy to be used for cookie management.
static String CREDENTIAL_CHARSET
          Defines the charset to be used when encoding Credentials.
static String DATE_PATTERNS
          The key used to look up the date patterns used for parsing.
static String HEAD_BODY_CHECK_TIMEOUT
          Sets period of time in milliseconds to wait for a content body sent in response to HEAD method from a non-compliant server.
static String HTTP_CONTENT_CHARSET
          Defines the charset to be used for encoding content body.
static String HTTP_ELEMENT_CHARSET
          Defines the charset to be used for encoding HTTP protocol elements.
static String HTTP_URI_CHARSET
          Defines the charset to be used for parsing URIs.
static String MULTIPART_BOUNDARY
          Sets the value to use as the multipart boundary.
static String PROTOCOL_VERSION
          Defines the HTTP protocol version used by HTTP methods per default.
static String REJECT_HEAD_BODY
          Defines whether the content body sent in response to HeadMethod should be rejected.
static String RETRY_HANDLER
          Sets the method retry handler parameter.
static String SINGLE_COOKIE_HEADER
          Defines whether cookies should be put on a single response header.
static String SO_TIMEOUT
          Sets the socket timeout (SO_TIMEOUT) in milliseconds to be used when executing the method.
static String STATUS_LINE_GARBAGE_LIMIT
          Defines the maximum number of ignorable lines before we expect a HTTP response's status code.
static String STRICT_TRANSFER_ENCODING
          Defines whether responses with an invalid Transfer-Encoding header should be rejected.
static String UNAMBIGUOUS_STATUS_LINE
          Defines whether HTTP methods should reject ambiguous HTTP status line.
static String USE_EXPECT_CONTINUE
           Activates 'Expect: 100-Continue' handshake for the entity enclosing methods.
static String USER_AGENT
          Defines the content of the User-Agent header used by HTTP methods.
static String VIRTUAL_HOST
          Defines the virtual host name.
static String WARN_EXTRA_INPUT
          Defines HttpClient's behavior when a response provides more bytes than expected (specified with Content-Length, for example).
 
Constructor Summary
HttpMethodParams()
          Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent.
HttpMethodParams(HttpParams defaults)
          Creates a new collection of parameters with the given parent.
 
Method Summary
 String getContentCharset()
          Returns the default charset to be used for writing content body, when no charset explicitly specified.
 String getCookiePolicy()
          Returns cookie policy to be used by the HTTP methods this collection of parameters applies to.
 String getCredentialCharset()
          Returns the charset to be used for Credentials.
 String getHttpElementCharset()
          Returns the charset to be used for writing HTTP headers.
 int getSoTimeout()
          Returns the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
 String getUriCharset()
          Returns the charset to be used for parsing URIs.
 HttpVersion getVersion()
          Returns HTTP protocol version to be used by the HTTP methods that this collection of parameters applies to.
 String getVirtualHost()
          Returns the virtual host name.
 void makeLenient()
          Makes the HTTP methods attempt to mimic the exact behaviour of commonly used HTTP agents, which many HTTP servers expect, even though such behaviour may violate the HTTP protocol specification (RFC 2616 and other relevant RFCs).
 void makeStrict()
          Makes the HTTP methods strictly follow the HTTP protocol specification (RFC 2616 and other relevant RFCs).
 void setContentCharset(String charset)
          Sets the default charset to be used for writing content body, when no charset explicitly specified.
 void setCookiePolicy(String policy)
          Assigns the cookie policy to be used by the HTTP methods this collection of parameters applies to.
 void setCredentialCharset(String charset)
          Sets the charset to be used for writing HTTP headers.
 void setHttpElementCharset(String charset)
          Sets the charset to be used for writing HTTP headers.
 void setSoTimeout(int timeout)
          Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
 void setUriCharset(String charset)
          Sets the charset to be used for parsing URIs.
 void setVersion(HttpVersion version)
          Assigns the HTTP protocol version to be used by the HTTP methods that this collection of parameters applies to.
 void setVirtualHost(String hostname)
          Sets the virtual host name.
 
Methods inherited from class org.apache.commons.httpclient.params.DefaultHttpParams
clear, clone, getBooleanParameter, getDefaultParams, getDefaults, getDoubleParameter, getIntParameter, getLongParameter, getParameter, isParameterFalse, isParameterSet, isParameterSetLocally, isParameterTrue, setBooleanParameter, setDefaults, setDoubleParameter, setHttpParamsFactory, setIntParameter, setLongParameter, setParameter, setParameters
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

USER_AGENT

public static final String USER_AGENT
Defines the content of the User-Agent header used by HTTP methods.

This parameter expects a value of type String.

See Also:
Constant Field Values

PROTOCOL_VERSION

public static final String PROTOCOL_VERSION
Defines the HTTP protocol version used by HTTP methods per default.

This parameter expects a value of type HttpVersion.

See Also:
Constant Field Values

UNAMBIGUOUS_STATUS_LINE

public static final String UNAMBIGUOUS_STATUS_LINE
Defines whether HTTP methods should reject ambiguous HTTP status line.

This parameter expects a value of type Boolean.

See Also:
Constant Field Values

SINGLE_COOKIE_HEADER

public static final String SINGLE_COOKIE_HEADER
Defines whether cookies should be put on a single response header.

This parameter expects a value of type Boolean.

See Also:
Constant Field Values

STRICT_TRANSFER_ENCODING

public static final String STRICT_TRANSFER_ENCODING
Defines whether responses with an invalid Transfer-Encoding header should be rejected.

This parameter expects a value of type Boolean.

See Also:
Constant Field Values

REJECT_HEAD_BODY

public static final String REJECT_HEAD_BODY
Defines whether the content body sent in response to HeadMethod should be rejected.

This parameter expects a value of type Boolean.

See Also:
Constant Field Values

HEAD_BODY_CHECK_TIMEOUT

public static final String HEAD_BODY_CHECK_TIMEOUT
Sets period of time in milliseconds to wait for a content body sent in response to HEAD method from a non-compliant server. If the parameter is not set or set to -1 non-compliant response body check is disabled.

This parameter expects a value of type Integer.

See Also:
Constant Field Values

USE_EXPECT_CONTINUE

public static final String USE_EXPECT_CONTINUE

Activates 'Expect: 100-Continue' handshake for the entity enclosing methods. The purpose of the 'Expect: 100-Continue' handshake 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 noticable peformance 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 Boolean.

See Also:
Constant Field Values

CREDENTIAL_CHARSET

public static final String CREDENTIAL_CHARSET
Defines the charset to be used when encoding Credentials. If not defined then the HTTP_ELEMENT_CHARSET should be used.

This parameter expects a value of type String.

See Also:
Constant Field Values

HTTP_ELEMENT_CHARSET

public static final String HTTP_ELEMENT_CHARSET
Defines the charset to be used for encoding HTTP protocol elements.

This parameter expects a value of type String.

See Also:
Constant Field Values

HTTP_URI_CHARSET

public static final String HTTP_URI_CHARSET
Defines the charset to be used for parsing URIs.

This parameter expects a value of type String.

See Also:
Constant Field Values

HTTP_CONTENT_CHARSET

public static final String HTTP_CONTENT_CHARSET
Defines the charset to be used for encoding content body.

This parameter expects a value of type String.

See Also:
Constant Field Values

COOKIE_POLICY

public static final String COOKIE_POLICY
Defines cookie policy to be used for cookie management.

This parameter expects a value of type String.

See Also:
Constant Field Values

WARN_EXTRA_INPUT

public static final String WARN_EXTRA_INPUT
Defines HttpClient's behavior when a response provides more bytes than expected (specified with Content-Length, for example).

Such surplus data makes the HTTP connection unreliable for keep-alive requests, as malicious response data (faked headers etc.) can lead to undesired results on the next request using that connection.

If this parameter is set to true, any detection of extra input data will generate a warning in the log.

This parameter expects a value of type Boolean.

See Also:
Constant Field Values

STATUS_LINE_GARBAGE_LIMIT

public static final String STATUS_LINE_GARBAGE_LIMIT
Defines the maximum number of ignorable lines before we expect a HTTP response's status code.

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

Set this to 0 to disallow any garbage/empty lines before the status line.
To specify no limit, use Integer.MAX_VALUE (default in lenient mode).

This parameter expects a value of type Integer.

See Also:
Constant Field Values

SO_TIMEOUT

public static final String SO_TIMEOUT
Sets the socket timeout (SO_TIMEOUT) in milliseconds to be used when executing the method. A timeout value of zero is interpreted as an infinite timeout.

This parameter expects a value of type Integer.

See Also:
SocketOptions.SO_TIMEOUT, Constant Field Values

DATE_PATTERNS

public static final String DATE_PATTERNS
The key used to look up the date patterns used for parsing. The String patterns are stored in a Collection and must be compatible with SimpleDateFormat.

This parameter expects a value of type Collection.

See Also:
Constant Field Values

RETRY_HANDLER

public static final String RETRY_HANDLER
Sets the method retry handler parameter.

This parameter expects a value of type HttpMethodRetryHandler.

See Also:
Constant Field Values

BUFFER_WARN_TRIGGER_LIMIT

public static final String BUFFER_WARN_TRIGGER_LIMIT
Sets the maximum buffered response size (in bytes) that triggers no warning. Buffered responses exceeding this size will trigger a warning in the log.

This parameter expects a value if type Integer.

See Also:
Constant Field Values

VIRTUAL_HOST

public static final String VIRTUAL_HOST
Defines the virtual host name.

This parameter expects a value of type String.

See Also:
Constant Field Values

MULTIPART_BOUNDARY

public static final String MULTIPART_BOUNDARY
Sets the value to use as the multipart boundary.

This parameter expects a value if type String.

See Also:
MultipartRequestEntity, Constant Field Values
Constructor Detail

HttpMethodParams

public HttpMethodParams()
Creates a new collection of parameters with the collection returned by DefaultHttpParams.getDefaultParams() as a parent. The collection will defer to its parent for a default value if a particular parameter is not explicitly set in the collection itself.

See Also:
DefaultHttpParams.getDefaultParams()

HttpMethodParams

public HttpMethodParams(HttpParams defaults)
Creates a new collection of parameters with the given parent. The collection will defer to its parent for a default value if a particular parameter is not explicitly set in the collection itself.

Parameters:
defaults - the parent collection to defer to, if a parameter is not explictly set in the collection itself.
See Also:
DefaultHttpParams.getDefaultParams()
Method Detail

getHttpElementCharset

public String getHttpElementCharset()
Returns the charset to be used for writing HTTP headers.

Returns:
The charset

setHttpElementCharset

public void setHttpElementCharset(String charset)
Sets the charset to be used for writing HTTP headers.

Parameters:
charset - The charset

getContentCharset

public String getContentCharset()
Returns the default charset to be used for writing content body, when no charset explicitly specified.

Returns:
The charset

setUriCharset

public void setUriCharset(String charset)
Sets the charset to be used for parsing URIs.

Parameters:
charset - The charset

getUriCharset

public String getUriCharset()
Returns the charset to be used for parsing URIs.

Returns:
The charset

setContentCharset

public void setContentCharset(String charset)
Sets the default charset to be used for writing content body, when no charset explicitly specified.

Parameters:
charset - The charset

getCredentialCharset

public String getCredentialCharset()
Returns the charset to be used for Credentials. If not configured the HTTP element charset is used.

Returns:
The charset

setCredentialCharset

public void setCredentialCharset(String charset)
Sets the charset to be used for writing HTTP headers.

Parameters:
charset - The charset

getVersion

public HttpVersion getVersion()
Returns HTTP protocol version to be used by the HTTP methods that this collection of parameters applies to.

Returns:
HTTP protocol version

setVersion

public void setVersion(HttpVersion version)
Assigns the HTTP protocol version to be used by the HTTP methods that this collection of parameters applies to.

Parameters:
version - the HTTP protocol version

getCookiePolicy

public String getCookiePolicy()
Returns cookie policy to be used by the HTTP methods this collection of parameters applies to.

Returns:
cookie policy

setCookiePolicy

public void setCookiePolicy(String policy)
Assigns the cookie policy to be used by the HTTP methods this collection of parameters applies to.

Parameters:
policy - the cookie policy

getSoTimeout

public int getSoTimeout()
Returns the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout.

Returns:
timeout in milliseconds

setSoTimeout

public void setSoTimeout(int timeout)
Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout.

Parameters:
timeout - Timeout in milliseconds

setVirtualHost

public void setVirtualHost(String hostname)
Sets the virtual host name.

Parameters:
hostname - The host name

getVirtualHost

public String getVirtualHost()
Returns the virtual host name.

Returns:
The virtual host name

makeStrict

public void makeStrict()
Makes the HTTP methods strictly follow the HTTP protocol specification (RFC 2616 and other relevant RFCs). It must be noted that popular HTTP agents have different degree of HTTP protocol compliance and some HTTP serves are programmed to expect the behaviour that does not strictly adhere to the HTTP specification.


makeLenient

public void makeLenient()
Makes the HTTP methods attempt to mimic the exact behaviour of commonly used HTTP agents, which many HTTP servers expect, even though such behaviour may violate the HTTP protocol specification (RFC 2616 and other relevant RFCs).



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/HttpParams.html100644 0 0 102076 10661532627 27060 0ustar 0 0 HttpParams (HttpClient 3.1 API)

org.apache.commons.httpclient.params
Interface HttpParams

All Known Implementing Classes:
DefaultHttpParams, HostParams, HttpClientParams, HttpConnectionManagerParams, HttpConnectionParams, HttpMethodParams

public interface HttpParams

This interface represents a collection of HTTP protocol parameters. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.

Since:
3.0
Version:
$Revision: 480424 $
Author:
Oleg Kalnichevski

Method Summary
 boolean getBooleanParameter(String name, boolean defaultValue)
          Returns a Boolean parameter value with the given name.
 HttpParams getDefaults()
          Returns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself
 double getDoubleParameter(String name, double defaultValue)
          Returns a Double parameter value with the given name.
 int getIntParameter(String name, int defaultValue)
          Returns an Integer parameter value with the given name.
 long getLongParameter(String name, long defaultValue)
          Returns a Long parameter value with the given name.
 Object getParameter(String name)
          Returns a parameter value with the given name.
 boolean isParameterFalse(String name)
          Returns true if the parameter is either not set or is false, false otherwise.
 boolean isParameterSet(String name)
          Returns true if the parameter is set at any level, false otherwise.
 boolean isParameterSetLocally(String name)
          Returns true if the parameter is set locally, false otherwise.
 boolean isParameterTrue(String name)
          Returns true if the parameter is set and is true, false otherwise.
 void setBooleanParameter(String name, boolean value)
          Assigns a Boolean to the parameter with the given name
 void setDefaults(HttpParams params)
          Assigns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself
 void setDoubleParameter(String name, double value)
          Assigns a Double to the parameter with the given name
 void setIntParameter(String name, int value)
          Assigns an Integer to the parameter with the given name
 void setLongParameter(String name, long value)
          Assigns a Long to the parameter with the given name
 void setParameter(String name, Object value)
          Assigns the value to the parameter with the given name
 

Method Detail

getDefaults

HttpParams getDefaults()
Returns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself

Returns:
the parent collection to defer to, if a particular parameter is not explictly set in the collection itself.
See Also:
setDefaults(HttpParams)

setDefaults

void setDefaults(HttpParams params)
Assigns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself

Parameters:
params - the parent collection to defer to, if a particular parameter is not explictly set in the collection itself.
See Also:
getDefaults()

getParameter

Object getParameter(String name)
Returns a parameter value with the given name. If the parameter is not explicitly defined in this collection, its value will be drawn from a higer level collection at which this parameter is defined. If the parameter is not explicitly set anywhere up the hierarchy, null value is returned.

Parameters:
name - the parent name.
Returns:
an object that represents the value of the parameter.
See Also:
setParameter(String, Object)

setParameter

void setParameter(String name,
                  Object value)
Assigns the value to the parameter with the given name

Parameters:
name - parameter name
value - parameter value

getLongParameter

long getLongParameter(String name,
                      long defaultValue)
Returns a Long parameter value with the given name. If the parameter is not explicitly defined in this collection, its value will be drawn from a higer level collection at which this parameter is defined. If the parameter is not explicitly set anywhere up the hierarchy, the default value is returned.

Parameters:
name - the parent name.
defaultValue - the default value.
Returns:
a Long that represents the value of the parameter.
See Also:
setLongParameter(String, long)

setLongParameter

void setLongParameter(String name,
                      long value)
Assigns a Long to the parameter with the given name

Parameters:
name - parameter name
value - parameter value

getIntParameter

int getIntParameter(String name,
                    int defaultValue)
Returns an Integer parameter value with the given name. If the parameter is not explicitly defined in this collection, its value will be drawn from a higer level collection at which this parameter is defined. If the parameter is not explicitly set anywhere up the hierarchy, the default value is returned.

Parameters:
name - the parent name.
defaultValue - the default value.
Returns:
a Integer that represents the value of the parameter.
See Also:
setIntParameter(String, int)

setIntParameter

void setIntParameter(String name,
                     int value)
Assigns an Integer to the parameter with the given name

Parameters:
name - parameter name
value - parameter value

getDoubleParameter

double getDoubleParameter(String name,
                          double defaultValue)
Returns a Double parameter value with the given name. If the parameter is not explicitly defined in this collection, its value will be drawn from a higer level collection at which this parameter is defined. If the parameter is not explicitly set anywhere up the hierarchy, the default value is returned.

Parameters:
name - the parent name.
defaultValue - the default value.
Returns:
a Double that represents the value of the parameter.
See Also:
setDoubleParameter(String, double)

setDoubleParameter

void setDoubleParameter(String name,
                        double value)
Assigns a Double to the parameter with the given name

Parameters:
name - parameter name
value - parameter value

getBooleanParameter

boolean getBooleanParameter(String name,
                            boolean defaultValue)
Returns a Boolean parameter value with the given name. If the parameter is not explicitly defined in this collection, its value will be drawn from a higer level collection at which this parameter is defined. If the parameter is not explicitly set anywhere up the hierarchy, the default value is returned.

Parameters:
name - the parent name.
defaultValue - the default value.
Returns:
a Boolean that represents the value of the parameter.
See Also:
setBooleanParameter(String, boolean)

setBooleanParameter

void setBooleanParameter(String name,
                         boolean value)
Assigns a Boolean to the parameter with the given name

Parameters:
name - parameter name
value - parameter value

isParameterSet

boolean isParameterSet(String name)
Returns true if the parameter is set at any level, false otherwise.

Parameters:
name - parameter name
Returns:
true if the parameter is set at any level, false otherwise.

isParameterSetLocally

boolean isParameterSetLocally(String name)
Returns true if the parameter is set locally, false otherwise.

Parameters:
name - parameter name
Returns:
true if the parameter is set locally, false otherwise.

isParameterTrue

boolean isParameterTrue(String name)
Returns true if the parameter is set and is true, false otherwise.

Parameters:
name - parameter name
Returns:
true if the parameter is set and is true, false otherwise.

isParameterFalse

boolean isParameterFalse(String name)
Returns true if the parameter is either not set or is false, false otherwise.

Parameters:
name - parameter name
Returns:
true if the parameter is either not set or is false, false otherwise.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/HttpParamsFactory.html100644 0 0 22147 10661532627 30370 0ustar 0 0 HttpParamsFactory (HttpClient 3.1 API)

org.apache.commons.httpclient.params
Interface HttpParamsFactory

All Known Implementing Classes:
DefaultHttpParamsFactory

public interface HttpParamsFactory

A factory for getting the default set of parameters to use when creating an instance of HttpParams.

Since:
3.0
See Also:
DefaultHttpParams.setHttpParamsFactory(HttpParamsFactory)

Method Summary
 HttpParams getDefaultParams()
          Gets the default parameters.
 

Method Detail

getDefaultParams

HttpParams getDefaultParams()
Gets the default parameters. This method may be called more than once and is not required to always return the same value.

Returns:
an instance of HttpParams


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/DefaultHttpParams.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/DefaultHttpParams100644 0 0 25446 10661532627 31306 0ustar 0 0 Uses of Class org.apache.commons.httpclient.params.DefaultHttpParams (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.params.DefaultHttpParams

Packages that use DefaultHttpParams
org.apache.commons.httpclient.params HttpClient preferences framework. 
 

Uses of DefaultHttpParams in org.apache.commons.httpclient.params
 

Subclasses of DefaultHttpParams in org.apache.commons.httpclient.params
 class HostParams
          This class represents a collection of HTTP protocol parameters applicable to instances of HostConfiguration.
 class HttpClientParams
          This class represents a collection of HTTP protocol parameters applicable to instances of HttpClient.
 class HttpConnectionManagerParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP connection managers.
 class HttpConnectionParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP connections.
 class HttpMethodParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP methods.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 161 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/DefaultHttpParamsFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/DefaultHttpParams100644 0 0 14166 10661532627 31303 0ustar 0 0 Uses of Class org.apache.commons.httpclient.params.DefaultHttpParamsFactory (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.params.DefaultHttpParamsFactory

No usage of org.apache.commons.httpclient.params.DefaultHttpParamsFactory



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HostParams.html100644 0 0 22732 10661532627 30735 0ustar 0 0 Uses of Class org.apache.commons.httpclient.params.HostParams (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.params.HostParams

Packages that use HostParams
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of HostParams in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return HostParams
 HostParams HostConfiguration.getParams()
          Returns HTTP protocol parameters associated with this host.
 

Methods in org.apache.commons.httpclient with parameters of type HostParams
 void HostConfiguration.setParams(HostParams params)
          Assigns HTTP protocol parameters specific to this host.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HttpClientParams.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HttpClientParams.100644 0 0 34107 10661532627 31210 0ustar 0 0 Uses of Class org.apache.commons.httpclient.params.HttpClientParams (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.params.HttpClientParams

Packages that use HttpClientParams
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of HttpClientParams in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return HttpClientParams
 HttpClientParams ProxyClient.getParams()
          Returns HTTP protocol parameters associated with this ProxyClient.
 HttpClientParams HttpClient.getParams()
          Returns HTTP protocol parameters associated with this HttpClient.
 

Methods in org.apache.commons.httpclient with parameters of type HttpClientParams
 void ProxyClient.setParams(HttpClientParams params)
          Assigns HTTP protocol parameters for this ProxyClient.
 void HttpClient.setParams(HttpClientParams params)
          Assigns HTTP protocol parameters for this HttpClient.
 

Constructors in org.apache.commons.httpclient with parameters of type HttpClientParams
HttpClient(HttpClientParams params)
          Creates an instance of HttpClient using the given parameter set.
HttpClient(HttpClientParams params, HttpConnectionManager httpConnectionManager)
          Creates an instance of HttpClient with a user specified parameter set and HTTP connection manager.
ProxyClient(HttpClientParams params)
          Creates an instance of ProxyClient using the given parameter set.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 164 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HttpConnectionManagerParams.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HttpConnectionMan100644 0 0 32256 10661532627 31306 0ustar 0 0 Uses of Class org.apache.commons.httpclient.params.HttpConnectionManagerParams (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.params.HttpConnectionManagerParams

Packages that use HttpConnectionManagerParams
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
 

Uses of HttpConnectionManagerParams in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return HttpConnectionManagerParams
 HttpConnectionManagerParams SimpleHttpConnectionManager.getParams()
          Returns parameters associated with this connection manager.
 HttpConnectionManagerParams MultiThreadedHttpConnectionManager.getParams()
          Returns parameters associated with this connection manager.
 HttpConnectionManagerParams HttpConnectionManager.getParams()
          Returns parameters associated with this connection manager.
 

Methods in org.apache.commons.httpclient with parameters of type HttpConnectionManagerParams
 void SimpleHttpConnectionManager.setParams(HttpConnectionManagerParams params)
          Assigns parameters for this connection manager.
 void MultiThreadedHttpConnectionManager.setParams(HttpConnectionManagerParams params)
          Assigns parameters for this connection manager.
 void HttpConnectionManager.setParams(HttpConnectionManagerParams params)
          Assigns parameters for this connection manager.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HttpConnectionParams.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HttpConnectionPar100644 0 0 41121 10661532627 31304 0ustar 0 0 Uses of Class org.apache.commons.httpclient.params.HttpConnectionParams (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.params.HttpConnectionParams

Packages that use HttpConnectionParams
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.params HttpClient preferences framework. 
org.apache.commons.httpclient.protocol Provides protocol specific socket factory handling. 
 

Uses of HttpConnectionParams in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return HttpConnectionParams
 HttpConnectionParams HttpConnection.getParams()
          Returns HTTP protocol parameters associated with this method.
 

Methods in org.apache.commons.httpclient with parameters of type HttpConnectionParams
 void HttpConnection.setParams(HttpConnectionParams params)
          Assigns HTTP protocol parameters for this method.
 

Uses of HttpConnectionParams in org.apache.commons.httpclient.params
 

Subclasses of HttpConnectionParams in org.apache.commons.httpclient.params
 class HttpConnectionManagerParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP connection managers.
 

Uses of HttpConnectionParams in org.apache.commons.httpclient.protocol
 

Methods in org.apache.commons.httpclient.protocol with parameters of type HttpConnectionParams
 Socket SSLProtocolSocketFactory.createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params)
          Attempts to get a new socket connection to the given host within the given time limit.
 Socket DefaultProtocolSocketFactory.createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params)
          Attempts to get a new socket connection to the given host within the given time limit.
 Socket ProtocolSocketFactory.createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params)
          Gets a new socket connection to the given host.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HttpMethodParams.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HttpMethodParams.100644 0 0 36464 10661532627 31222 0ustar 0 0 Uses of Class org.apache.commons.httpclient.params.HttpMethodParams (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.params.HttpMethodParams

Packages that use HttpMethodParams
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.methods.multipart Provides Multipart support classes for the MultipartPostMethod
org.apache.commons.httpclient.params HttpClient preferences framework. 
 

Uses of HttpMethodParams in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return HttpMethodParams
 HttpMethodParams HttpMethodBase.getParams()
          Returns HTTP protocol parameters associated with this method.
 HttpMethodParams HttpMethod.getParams()
          Returns HTTP protocol parameters associated with this method.
 

Methods in org.apache.commons.httpclient with parameters of type HttpMethodParams
 void HttpMethodBase.setParams(HttpMethodParams params)
          Assigns HTTP protocol parameters for this method.
 void HttpMethod.setParams(HttpMethodParams params)
          Assigns HTTP protocol parameters for this method.
 

Uses of HttpMethodParams in org.apache.commons.httpclient.methods.multipart
 

Constructors in org.apache.commons.httpclient.methods.multipart with parameters of type HttpMethodParams
MultipartRequestEntity(Part[] parts, HttpMethodParams params)
          Creates a new multipart entity containing the given parts.
 

Uses of HttpMethodParams in org.apache.commons.httpclient.params
 

Subclasses of HttpMethodParams in org.apache.commons.httpclient.params
 class HttpClientParams
          This class represents a collection of HTTP protocol parameters applicable to instances of HttpClient.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HttpParams.html100644 0 0 53151 10661532627 30736 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.params.HttpParams (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.params.HttpParams

Packages that use HttpParams
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
org.apache.commons.httpclient.params HttpClient preferences framework. 
 

Uses of HttpParams in org.apache.commons.httpclient.auth
 

Constructors in org.apache.commons.httpclient.auth with parameters of type HttpParams
AuthChallengeProcessor(HttpParams params)
          Creates an authentication challenge processor with the given HTTP parameters
 

Uses of HttpParams in org.apache.commons.httpclient.params
 

Classes in org.apache.commons.httpclient.params that implement HttpParams
 class DefaultHttpParams
          This class represents a collection of HTTP protocol parameters.
 class HostParams
          This class represents a collection of HTTP protocol parameters applicable to instances of HostConfiguration.
 class HttpClientParams
          This class represents a collection of HTTP protocol parameters applicable to instances of HttpClient.
 class HttpConnectionManagerParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP connection managers.
 class HttpConnectionParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP connections.
 class HttpMethodParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP methods.
 

Methods in org.apache.commons.httpclient.params that return HttpParams
protected  HttpParams DefaultHttpParamsFactory.createParams()
           
 HttpParams DefaultHttpParamsFactory.getDefaultParams()
           
 HttpParams HttpParamsFactory.getDefaultParams()
          Gets the default parameters.
static HttpParams DefaultHttpParams.getDefaultParams()
          Gets the default HttpParams to be used.
 HttpParams HttpParams.getDefaults()
          Returns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself
 HttpParams DefaultHttpParams.getDefaults()
           
 

Methods in org.apache.commons.httpclient.params with parameters of type HttpParams
 void HttpParams.setDefaults(HttpParams params)
          Assigns the parent collection that this collection will defer to for a default value if a particular parameter is not explicitly set in the collection itself
 void DefaultHttpParams.setDefaults(HttpParams params)
           
 

Constructors in org.apache.commons.httpclient.params with parameters of type HttpParams
DefaultHttpParams(HttpParams defaults)
          Creates a new collection of parameters with the given parent.
HostParams(HttpParams defaults)
          Creates a new collection of parameters with the given parent.
HttpClientParams(HttpParams defaults)
          Creates a new collection of parameters with the given parent.
HttpMethodParams(HttpParams defaults)
          Creates a new collection of parameters with the given parent.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HttpParamsFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/class-use/HttpParamsFactory100644 0 0 22422 10661532627 31320 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.params.HttpParamsFactory (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.params.HttpParamsFactory

Packages that use HttpParamsFactory
org.apache.commons.httpclient.params HttpClient preferences framework. 
 

Uses of HttpParamsFactory in org.apache.commons.httpclient.params
 

Classes in org.apache.commons.httpclient.params that implement HttpParamsFactory
 class DefaultHttpParamsFactory
           
 

Methods in org.apache.commons.httpclient.params with parameters of type HttpParamsFactory
static void DefaultHttpParams.setHttpParamsFactory(HttpParamsFactory httpParamsFactory)
          Sets the factory that will provide the default HttpParams.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/package-frame.html100644 0 0 4504 10661532627 27415 0ustar 0 0 org.apache.commons.httpclient.params (HttpClient 3.1 API) org.apache.commons.httpclient.params
Interfaces 
HttpParams
HttpParamsFactory
Classes 
DefaultHttpParams
DefaultHttpParamsFactory
HostParams
HttpClientParams
HttpConnectionManagerParams
HttpConnectionParams
HttpMethodParams
commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/package-summary.html100644 0 0 24660 10661532627 30045 0ustar 0 0 org.apache.commons.httpclient.params (HttpClient 3.1 API)

Package org.apache.commons.httpclient.params

HttpClient preferences framework.

See:
          Description

Interface Summary
HttpParams This interface represents a collection of HTTP protocol parameters.
HttpParamsFactory A factory for getting the default set of parameters to use when creating an instance of HttpParams.
 

Class Summary
DefaultHttpParams This class represents a collection of HTTP protocol parameters.
DefaultHttpParamsFactory  
HostParams This class represents a collection of HTTP protocol parameters applicable to instances of HostConfiguration.
HttpClientParams This class represents a collection of HTTP protocol parameters applicable to instances of HttpClient.
HttpConnectionManagerParams This class represents a collection of HTTP protocol parameters applicable to HTTP connection managers.
HttpConnectionParams This class represents a collection of HTTP protocol parameters applicable to HTTP connections.
HttpMethodParams This class represents a collection of HTTP protocol parameters applicable to HTTP methods.
 

Package org.apache.commons.httpclient.params Description

HttpClient preferences framework.

Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/package-tree.html100644 0 0 21573 10661532627 27307 0ustar 0 0 org.apache.commons.httpclient.params Class Hierarchy (HttpClient 3.1 API)

Hierarchy For Package org.apache.commons.httpclient.params

Package Hierarchies:
All Packages

Class Hierarchy

Interface Hierarchy



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/params/package-use.html100644 0 0 37661 10661532627 27151 0ustar 0 0 Uses of Package org.apache.commons.httpclient.params (HttpClient 3.1 API)

Uses of Package
org.apache.commons.httpclient.params

Packages that use org.apache.commons.httpclient.params
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. 
org.apache.commons.httpclient.methods.multipart Provides Multipart support classes for the MultipartPostMethod
org.apache.commons.httpclient.params HttpClient preferences framework. 
org.apache.commons.httpclient.protocol Provides protocol specific socket factory handling. 
 

Classes in org.apache.commons.httpclient.params used by org.apache.commons.httpclient
HostParams
          This class represents a collection of HTTP protocol parameters applicable to instances of HostConfiguration.
HttpClientParams
          This class represents a collection of HTTP protocol parameters applicable to instances of HttpClient.
HttpConnectionManagerParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP connection managers.
HttpConnectionParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP connections.
HttpMethodParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP methods.
 

Classes in org.apache.commons.httpclient.params used by org.apache.commons.httpclient.auth
HttpParams
          This interface represents a collection of HTTP protocol parameters.
 

Classes in org.apache.commons.httpclient.params used by org.apache.commons.httpclient.methods.multipart
HttpMethodParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP methods.
 

Classes in org.apache.commons.httpclient.params used by org.apache.commons.httpclient.params
DefaultHttpParams
          This class represents a collection of HTTP protocol parameters.
HttpConnectionParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP connections.
HttpMethodParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP methods.
HttpParams
          This interface represents a collection of HTTP protocol parameters.
HttpParamsFactory
          A factory for getting the default set of parameters to use when creating an instance of HttpParams.
 

Classes in org.apache.commons.httpclient.params used by org.apache.commons.httpclient.protocol
HttpConnectionParams
          This class represents a collection of HTTP protocol parameters applicable to HTTP connections.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 171 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactory.SocketTask.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/ControllerThreadSocketFac100644 0 0 37677 10661532627 31444 0ustar 0 0 ControllerThreadSocketFactory.SocketTask (HttpClient 3.1 API)

org.apache.commons.httpclient.protocol
Class ControllerThreadSocketFactory.SocketTask

java.lang.Object
  extended by org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory.SocketTask
All Implemented Interfaces:
Runnable
Enclosing class:
ControllerThreadSocketFactory

public abstract static class ControllerThreadSocketFactory.SocketTask
extends Object
implements Runnable

Helper class for wrapping socket based tasks.


Constructor Summary
ControllerThreadSocketFactory.SocketTask()
           
 
Method Summary
abstract  void doit()
          Perform the logic.
protected  Socket getSocket()
          Return the socket.
 void run()
          Execute the logic in this object and keep track of any exceptions.
protected  void setSocket(Socket newSocket)
          Set the socket.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ControllerThreadSocketFactory.SocketTask

public ControllerThreadSocketFactory.SocketTask()
Method Detail

setSocket

protected void setSocket(Socket newSocket)
Set the socket.

Parameters:
newSocket - The new socket.

getSocket

protected Socket getSocket()
Return the socket.

Returns:
Socket The socket.

doit

public abstract void doit()
                   throws IOException
Perform the logic.

Throws:
IOException - If an IO problem occurs

run

public void run()
Execute the logic in this object and keep track of any exceptions.

Specified by:
run in interface Runnable


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 156 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/ControllerThreadSocketFac100644 0 0 44500 10661532627 31423 0ustar 0 0 ControllerThreadSocketFactory (HttpClient 3.1 API)

org.apache.commons.httpclient.protocol
Class ControllerThreadSocketFactory

java.lang.Object
  extended by org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory

public final class ControllerThreadSocketFactory
extends Object

This helper class is intedned to help work around the limitation of older Java versions (older than 1.4) that prevents from specifying a connection timeout when creating a socket. This factory executes a controller thread overssing the process of socket initialisation. If the socket constructor cannot be created within the specified time limit, the controller terminates and throws an ConnectTimeoutException

Since:
3.0
Author:
Ortwin Glueck, Oleg Kalnichevski

Nested Class Summary
static class ControllerThreadSocketFactory.SocketTask
          Helper class for wrapping socket based tasks.
 
Method Summary
static Socket createSocket(ControllerThreadSocketFactory.SocketTask task, int timeout)
           
static Socket createSocket(ProtocolSocketFactory socketfactory, String host, int port, InetAddress localAddress, int localPort, int timeout)
          This method spawns a controller thread overseeing the process of socket initialisation.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

createSocket

public static Socket createSocket(ProtocolSocketFactory socketfactory,
                                  String host,
                                  int port,
                                  InetAddress localAddress,
                                  int localPort,
                                  int timeout)
                           throws IOException,
                                  UnknownHostException,
                                  ConnectTimeoutException
This method spawns a controller thread overseeing the process of socket initialisation. If the socket constructor cannot be created within the specified time limit, the controller terminates and throws an ConnectTimeoutException

Parameters:
host - the host name/IP
port - the port on the host
localAddress - the local host name/IP to bind the socket to
localPort - the port on the local machine
timeout - the timeout value to be used in milliseconds. If the socket cannot be completed within the given time limit, it will be abandoned
Returns:
a connected Socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined
ConnectTimeoutException - if socket cannot be connected within the given time limit

createSocket

public static Socket createSocket(ControllerThreadSocketFactory.SocketTask task,
                                  int timeout)
                           throws IOException,
                                  UnknownHostException,
                                  ConnectTimeoutException
Throws:
IOException
UnknownHostException
ConnectTimeoutException


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFact100644 0 0 63522 10661532627 31447 0ustar 0 0 DefaultProtocolSocketFactory (HttpClient 3.1 API)

org.apache.commons.httpclient.protocol
Class DefaultProtocolSocketFactory

java.lang.Object
  extended by org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory
All Implemented Interfaces:
ProtocolSocketFactory

public class DefaultProtocolSocketFactory
extends Object
implements ProtocolSocketFactory

The default class for creating protocol sockets. This class just uses the socket constructors.

Since:
2.0
Author:
Michael Becke

Constructor Summary
DefaultProtocolSocketFactory()
          Constructor for DefaultProtocolSocketFactory.
 
Method Summary
 Socket createSocket(String host, int port)
          Gets a new socket connection to the given host.
 Socket createSocket(String host, int port, InetAddress localAddress, int localPort)
          Gets a new socket connection to the given host.
 Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params)
          Attempts to get a new socket connection to the given host within the given time limit.
 boolean equals(Object obj)
          All instances of DefaultProtocolSocketFactory are the same.
 int hashCode()
          All instances of DefaultProtocolSocketFactory have the same hash code.
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

DefaultProtocolSocketFactory

public DefaultProtocolSocketFactory()
Constructor for DefaultProtocolSocketFactory.

Method Detail

createSocket

public Socket createSocket(String host,
                           int port,
                           InetAddress localAddress,
                           int localPort)
                    throws IOException,
                           UnknownHostException
Description copied from interface: ProtocolSocketFactory
Gets a new socket connection to the given host.

Specified by:
createSocket in interface ProtocolSocketFactory
Parameters:
host - the host name/IP
port - the port on the host
localAddress - the local host name/IP to bind the socket to
localPort - the port on the local machine
Returns:
Socket a new socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined
See Also:
createSocket(java.lang.String,int,java.net.InetAddress,int)

createSocket

public Socket createSocket(String host,
                           int port,
                           InetAddress localAddress,
                           int localPort,
                           HttpConnectionParams params)
                    throws IOException,
                           UnknownHostException,
                           ConnectTimeoutException
Attempts to get a new socket connection to the given host within the given time limit.

This method employs several techniques to circumvent the limitations of older JREs that do not support connect timeout. When running in JRE 1.4 or above reflection is used to call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older JREs a controller thread is executed. The controller thread attempts to create a new socket within the given limit of time. If socket constructor does not return until the timeout expires, the controller terminates and throws an ConnectTimeoutException

Specified by:
createSocket in interface ProtocolSocketFactory
Parameters:
host - the host name/IP
port - the port on the host
localAddress - the local host name/IP to bind the socket to
localPort - the port on the local machine
params - Http connection parameters
Returns:
Socket a new socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined
ConnectTimeoutException - if socket cannot be connected within the given time limit
Since:
3.0

createSocket

public Socket createSocket(String host,
                           int port)
                    throws IOException,
                           UnknownHostException
Description copied from interface: ProtocolSocketFactory
Gets a new socket connection to the given host.

Specified by:
createSocket in interface ProtocolSocketFactory
Parameters:
host - the host name/IP
port - the port on the host
Returns:
Socket a new socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined
See Also:
ProtocolSocketFactory.createSocket(java.lang.String,int)

equals

public boolean equals(Object obj)
All instances of DefaultProtocolSocketFactory are the same.

Overrides:
equals in class Object

hashCode

public int hashCode()
All instances of DefaultProtocolSocketFactory have the same hash code.

Overrides:
hashCode in class Object


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/Protocol.html100644 0 0 64273 10661532627 27142 0ustar 0 0 Protocol (HttpClient 3.1 API)

org.apache.commons.httpclient.protocol
Class Protocol

java.lang.Object
  extended by org.apache.commons.httpclient.protocol.Protocol

public class Protocol
extends Object

A class to encapsulate the specifics of a protocol. This class class also provides the ability to customize the set and characteristics of the protocols used.

One use case for modifying the default set of protocols would be to set a custom SSL socket factory. This would look something like the following:

 
 Protocol myHTTPS = new Protocol( "https", new MySSLSocketFactory(), 443 );
 
 Protocol.registerProtocol( "https", myHTTPS );
 

Since:
2.0
Author:
Michael Becke, Jeff Dever, Mike Bowler

Constructor Summary
Protocol(String scheme, ProtocolSocketFactory factory, int defaultPort)
          Constructs a new Protocol.
Protocol(String scheme, SecureProtocolSocketFactory factory, int defaultPort)
          Deprecated. Use the constructor that uses ProtocolSocketFactory, this version of the constructor is only kept for backwards API compatibility.
 
Method Summary
 boolean equals(Object obj)
          Return true if the specified object equals this object.
 int getDefaultPort()
          Returns the defaultPort.
static Protocol getProtocol(String id)
          Gets the protocol with the given ID.
 String getScheme()
          Returns the scheme.
 ProtocolSocketFactory getSocketFactory()
          Returns the socketFactory.
 int hashCode()
          Return a hash code for this object
 boolean isSecure()
          Returns true if this protocol is secure
static void registerProtocol(String id, Protocol protocol)
          Registers a new protocol with the given identifier.
 int resolvePort(int port)
          Resolves the correct port for this protocol.
 String toString()
          Return a string representation of this object.
static void unregisterProtocol(String id)
          Unregisters the protocol with the given ID.
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Protocol

public Protocol(String scheme,
                ProtocolSocketFactory factory,
                int defaultPort)
Constructs a new Protocol. Whether the created protocol is secure depends on the class of factory.

Parameters:
scheme - the scheme (e.g. http, https)
factory - the factory for creating sockets for communication using this protocol
defaultPort - the port this protocol defaults to

Protocol

public Protocol(String scheme,
                SecureProtocolSocketFactory factory,
                int defaultPort)
Deprecated. Use the constructor that uses ProtocolSocketFactory, this version of the constructor is only kept for backwards API compatibility.

Constructs a new Protocol. Whether the created protocol is secure depends on the class of factory.

Parameters:
scheme - the scheme (e.g. http, https)
factory - the factory for creating sockets for communication using this protocol
defaultPort - the port this protocol defaults to
Method Detail

registerProtocol

public static void registerProtocol(String id,
                                    Protocol protocol)
Registers a new protocol with the given identifier. If a protocol with the given ID already exists it will be overridden. This ID is the same one used to retrieve the protocol from getProtocol(String).

Parameters:
id - the identifier for this protocol
protocol - the protocol to register
See Also:
getProtocol(String)

unregisterProtocol

public static void unregisterProtocol(String id)
Unregisters the protocol with the given ID.

Parameters:
id - the ID of the protocol to remove

getProtocol

public static Protocol getProtocol(String id)
                            throws IllegalStateException
Gets the protocol with the given ID.

Parameters:
id - the protocol ID
Returns:
Protocol a protocol
Throws:
IllegalStateException - if a protocol with the ID cannot be found

getDefaultPort

public int getDefaultPort()
Returns the defaultPort.

Returns:
int

getSocketFactory

public ProtocolSocketFactory getSocketFactory()
Returns the socketFactory. If secure the factory is a SecureProtocolSocketFactory.

Returns:
SocketFactory

getScheme

public String getScheme()
Returns the scheme.

Returns:
The scheme

isSecure

public boolean isSecure()
Returns true if this protocol is secure

Returns:
true if this protocol is secure

resolvePort

public int resolvePort(int port)
Resolves the correct port for this protocol. Returns the given port if valid or the default port otherwise.

Parameters:
port - the port to be resolved
Returns:
the given port or the defaultPort

toString

public String toString()
Return a string representation of this object.

Overrides:
toString in class Object
Returns:
a string representation of this object.

equals

public boolean equals(Object obj)
Return true if the specified object equals this object.

Overrides:
equals in class Object
Parameters:
obj - The object to compare against.
Returns:
true if the objects are equal.

hashCode

public int hashCode()
Return a hash code for this object

Overrides:
hashCode in class Object
Returns:
The hash code.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/ProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/ProtocolSocketFactory.htm100644 0 0 44001 10661532627 31452 0ustar 0 0 ProtocolSocketFactory (HttpClient 3.1 API)

org.apache.commons.httpclient.protocol
Interface ProtocolSocketFactory

All Known Subinterfaces:
SecureProtocolSocketFactory
All Known Implementing Classes:
DefaultProtocolSocketFactory, SSLProtocolSocketFactory

public interface ProtocolSocketFactory

A factory for creating Sockets.

Both Object.equals() and Object.hashCode() should be overridden appropriately. Protocol socket factories are used to uniquely identify Protocols and HostConfigurations, and equals() and hashCode() are required for the correct operation of some connection managers.

Since:
2.0
Author:
Michael Becke, Mike Bowler
See Also:
Protocol

Method Summary
 Socket createSocket(String host, int port)
          Gets a new socket connection to the given host.
 Socket createSocket(String host, int port, InetAddress localAddress, int localPort)
          Gets a new socket connection to the given host.
 Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params)
          Gets a new socket connection to the given host.
 

Method Detail

createSocket

Socket createSocket(String host,
                    int port,
                    InetAddress localAddress,
                    int localPort)
                    throws IOException,
                           UnknownHostException
Gets a new socket connection to the given host.

Parameters:
host - the host name/IP
port - the port on the host
localAddress - the local host name/IP to bind the socket to
localPort - the port on the local machine
Returns:
Socket a new socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined

createSocket

Socket createSocket(String host,
                    int port,
                    InetAddress localAddress,
                    int localPort,
                    HttpConnectionParams params)
                    throws IOException,
                           UnknownHostException,
                           ConnectTimeoutException
Gets a new socket connection to the given host.

Parameters:
host - the host name/IP
port - the port on the host
localAddress - the local host name/IP to bind the socket to
localPort - the port on the local machine
params - Http connection parameters
Returns:
Socket a new socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined
ConnectTimeoutException - if socket cannot be connected within the given time limit
Since:
3.0

createSocket

Socket createSocket(String host,
                    int port)
                    throws IOException,
                           UnknownHostException
Gets a new socket connection to the given host.

Parameters:
host - the host name/IP
port - the port on the host
Returns:
Socket a new socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/ReflectionSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/ReflectionSocketFactory.h100644 0 0 34665 10661532627 31421 0ustar 0 0 ReflectionSocketFactory (HttpClient 3.1 API)

org.apache.commons.httpclient.protocol
Class ReflectionSocketFactory

java.lang.Object
  extended by org.apache.commons.httpclient.protocol.ReflectionSocketFactory

public final class ReflectionSocketFactory
extends Object

This helper class uses refelction in order to execute Socket methods available in Java 1.4 and above

Since:
3.0
Author:
Oleg Kalnichevski

Method Summary
static Socket createSocket(String socketfactoryName, String host, int port, InetAddress localAddress, int localPort, int timeout)
          This method attempts to execute Socket method available since Java 1.4 using reflection.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

createSocket

public static Socket createSocket(String socketfactoryName,
                                  String host,
                                  int port,
                                  InetAddress localAddress,
                                  int localPort,
                                  int timeout)
                           throws IOException,
                                  UnknownHostException,
                                  ConnectTimeoutException
This method attempts to execute Socket method available since Java 1.4 using reflection. If the methods are not available or could not be executed null is returned

Parameters:
socketfactoryName - name of the socket factory class
host - the host name/IP
port - the port on the host
localAddress - the local host name/IP to bind the socket to
localPort - the port on the local machine
timeout - the timeout value to be used in milliseconds. If the socket cannot be completed within the given time limit, it will be abandoned
Returns:
a connected Socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined
ConnectTimeoutException - if socket cannot be connected within the given time limit


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.100644 0 0 72475 10661532627 31343 0ustar 0 0 SSLProtocolSocketFactory (HttpClient 3.1 API)

org.apache.commons.httpclient.protocol
Class SSLProtocolSocketFactory

java.lang.Object
  extended by org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory
All Implemented Interfaces:
ProtocolSocketFactory, SecureProtocolSocketFactory

public class SSLProtocolSocketFactory
extends Object
implements SecureProtocolSocketFactory

A SecureProtocolSocketFactory that uses JSSE to create sockets.

Since:
2.0
Author:
Michael Becke, Mike Bowler

Constructor Summary
SSLProtocolSocketFactory()
          Constructor for SSLProtocolSocketFactory.
 
Method Summary
 Socket createSocket(Socket socket, String host, int port, boolean autoClose)
          Returns a socket connected to the given host that is layered over an existing socket.
 Socket createSocket(String host, int port)
          Gets a new socket connection to the given host.
 Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
          Gets a new socket connection to the given host.
 Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params)
          Attempts to get a new socket connection to the given host within the given time limit.
 boolean equals(Object obj)
          All instances of SSLProtocolSocketFactory are the same.
 int hashCode()
          All instances of SSLProtocolSocketFactory have the same hash code.
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

SSLProtocolSocketFactory

public SSLProtocolSocketFactory()
Constructor for SSLProtocolSocketFactory.

Method Detail

createSocket

public Socket createSocket(String host,
                           int port,
                           InetAddress clientHost,
                           int clientPort)
                    throws IOException,
                           UnknownHostException
Description copied from interface: ProtocolSocketFactory
Gets a new socket connection to the given host.

Specified by:
createSocket in interface ProtocolSocketFactory
Parameters:
host - the host name/IP
port - the port on the host
clientHost - the local host name/IP to bind the socket to
clientPort - the port on the local machine
Returns:
Socket a new socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined
See Also:
ProtocolSocketFactory.createSocket(java.lang.String,int,java.net.InetAddress,int)

createSocket

public Socket createSocket(String host,
                           int port,
                           InetAddress localAddress,
                           int localPort,
                           HttpConnectionParams params)
                    throws IOException,
                           UnknownHostException,
                           ConnectTimeoutException
Attempts to get a new socket connection to the given host within the given time limit.

This method employs several techniques to circumvent the limitations of older JREs that do not support connect timeout. When running in JRE 1.4 or above reflection is used to call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older JREs a controller thread is executed. The controller thread attempts to create a new socket within the given limit of time. If socket constructor does not return until the timeout expires, the controller terminates and throws an ConnectTimeoutException

Specified by:
createSocket in interface ProtocolSocketFactory
Parameters:
host - the host name/IP
port - the port on the host
localAddress - the local host name/IP to bind the socket to
localPort - the port on the local machine
params - Http connection parameters
Returns:
Socket a new socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined
ConnectTimeoutException - if socket cannot be connected within the given time limit
Since:
3.0

createSocket

public Socket createSocket(String host,
                           int port)
                    throws IOException,
                           UnknownHostException
Description copied from interface: ProtocolSocketFactory
Gets a new socket connection to the given host.

Specified by:
createSocket in interface ProtocolSocketFactory
Parameters:
host - the host name/IP
port - the port on the host
Returns:
Socket a new socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined
See Also:
ProtocolSocketFactory.createSocket(java.lang.String,int)

createSocket

public Socket createSocket(Socket socket,
                           String host,
                           int port,
                           boolean autoClose)
                    throws IOException,
                           UnknownHostException
Description copied from interface: SecureProtocolSocketFactory
Returns a socket connected to the given host that is layered over an existing socket. Used primarily for creating secure sockets through proxies.

Specified by:
createSocket in interface SecureProtocolSocketFactory
Parameters:
socket - the existing socket
host - the host name/IP
port - the port on the host
autoClose - a flag for closing the underling socket when the created socket is closed
Returns:
Socket a new socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined
See Also:
SecureProtocolSocketFactory.createSocket(java.net.Socket,java.lang.String,int,boolean)

equals

public boolean equals(Object obj)
All instances of SSLProtocolSocketFactory are the same.

Overrides:
equals in class Object

hashCode

public int hashCode()
All instances of SSLProtocolSocketFactory have the same hash code.

Overrides:
hashCode in class Object


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 154 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/SecureProtocolSocketFacto100644 0 0 31630 10661532627 31463 0ustar 0 0 SecureProtocolSocketFactory (HttpClient 3.1 API)

org.apache.commons.httpclient.protocol
Interface SecureProtocolSocketFactory

All Superinterfaces:
ProtocolSocketFactory
All Known Implementing Classes:
SSLProtocolSocketFactory

public interface SecureProtocolSocketFactory
extends ProtocolSocketFactory

A ProtocolSocketFactory that is secure.

Since:
2.0
Author:
Michael Becke, Mike Bowler
See Also:
ProtocolSocketFactory

Method Summary
 Socket createSocket(Socket socket, String host, int port, boolean autoClose)
          Returns a socket connected to the given host that is layered over an existing socket.
 
Methods inherited from interface org.apache.commons.httpclient.protocol.ProtocolSocketFactory
createSocket, createSocket, createSocket
 

Method Detail

createSocket

Socket createSocket(Socket socket,
                    String host,
                    int port,
                    boolean autoClose)
                    throws IOException,
                           UnknownHostException
Returns a socket connected to the given host that is layered over an existing socket. Used primarily for creating secure sockets through proxies.

Parameters:
socket - the existing socket
host - the host name/IP
port - the port on the host
autoClose - a flag for closing the underling socket when the created socket is closed
Returns:
Socket a new socket
Throws:
IOException - if an I/O error occurs while creating the socket
UnknownHostException - if the IP address of the host cannot be determined


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 203 10661532634 10254 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/ControllerThreadSocketFactory.SocketTask.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/ControllerThrea100644 0 0 21604 10661532627 31373 0ustar 0 0 Uses of Class org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory.SocketTask (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory.SocketTask

Packages that use ControllerThreadSocketFactory.SocketTask
org.apache.commons.httpclient.protocol Provides protocol specific socket factory handling. 
 

Uses of ControllerThreadSocketFactory.SocketTask in org.apache.commons.httpclient.protocol
 

Methods in org.apache.commons.httpclient.protocol with parameters of type ControllerThreadSocketFactory.SocketTask
static Socket ControllerThreadSocketFactory.createSocket(ControllerThreadSocketFactory.SocketTask task, int timeout)
           
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 170 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/ControllerThreadSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/ControllerThrea100644 0 0 14274 10661532627 31400 0ustar 0 0 Uses of Class org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory

No usage of org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 167 10661532634 10265 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/DefaultProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/DefaultProtocol100644 0 0 14262 10661532627 31374 0ustar 0 0 Uses of Class org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory

No usage of org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/Protocol.html100644 0 0 50204 10661532627 31026 0ustar 0 0 Uses of Class org.apache.commons.httpclient.protocol.Protocol (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.protocol.Protocol

Packages that use Protocol
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.protocol Provides protocol specific socket factory handling. 
 

Uses of Protocol in org.apache.commons.httpclient
 

Methods in org.apache.commons.httpclient that return Protocol
 Protocol HttpHost.getProtocol()
          Returns the protocol.
 Protocol HttpConnection.getProtocol()
          Returns the protocol used to establish the connection.
 Protocol HostConfiguration.getProtocol()
          Returns the protocol.
 

Methods in org.apache.commons.httpclient with parameters of type Protocol
 void HostConfiguration.setHost(String host, int port, Protocol protocol)
          Sets the given host, port and protocol.
 void HostConfiguration.setHost(String host, String virtualHost, int port, Protocol protocol)
          Deprecated. #setHost(String, int, Protocol)
 void HttpConnection.setProtocol(Protocol protocol)
          Sets the protocol used to establish the connection
 

Constructors in org.apache.commons.httpclient with parameters of type Protocol
HttpConnection(String host, int port, Protocol protocol)
          Creates a new HTTP connection for the given host and port using the given protocol.
HttpConnection(String proxyHost, int proxyPort, String host, int port, Protocol protocol)
          Creates a new HTTP connection for the given host with the virtual alias and port via the given proxy host and port using the given protocol.
HttpConnection(String proxyHost, int proxyPort, String host, String virtualHost, int port, Protocol protocol)
          Deprecated. use #HttpConnection(String, int, String, int, Protocol)
HttpConnection(String host, String virtualHost, int port, Protocol protocol)
          Creates a new HTTP connection for the given host with the virtual alias and port using given protocol.
HttpHost(String hostname, int port, Protocol protocol)
          Constructor for HttpHost.
 

Uses of Protocol in org.apache.commons.httpclient.protocol
 

Methods in org.apache.commons.httpclient.protocol that return Protocol
static Protocol Protocol.getProtocol(String id)
          Gets the protocol with the given ID.
 

Methods in org.apache.commons.httpclient.protocol with parameters of type Protocol
static void Protocol.registerProtocol(String id, Protocol protocol)
          Registers a new protocol with the given identifier.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 160 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/ProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/ProtocolSocketF100644 0 0 33546 10661532627 31354 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.protocol.ProtocolSocketFactory (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.protocol.ProtocolSocketFactory

Packages that use ProtocolSocketFactory
org.apache.commons.httpclient.protocol Provides protocol specific socket factory handling. 
 

Uses of ProtocolSocketFactory in org.apache.commons.httpclient.protocol
 

Subinterfaces of ProtocolSocketFactory in org.apache.commons.httpclient.protocol
 interface SecureProtocolSocketFactory
          A ProtocolSocketFactory that is secure.
 

Classes in org.apache.commons.httpclient.protocol that implement ProtocolSocketFactory
 class DefaultProtocolSocketFactory
          The default class for creating protocol sockets.
 class SSLProtocolSocketFactory
          A SecureProtocolSocketFactory that uses JSSE to create sockets.
 

Methods in org.apache.commons.httpclient.protocol that return ProtocolSocketFactory
 ProtocolSocketFactory Protocol.getSocketFactory()
          Returns the socketFactory.
 

Methods in org.apache.commons.httpclient.protocol with parameters of type ProtocolSocketFactory
static Socket ControllerThreadSocketFactory.createSocket(ProtocolSocketFactory socketfactory, String host, int port, InetAddress localAddress, int localPort, int timeout)
          This method spawns a controller thread overseeing the process of socket initialisation.
 

Constructors in org.apache.commons.httpclient.protocol with parameters of type ProtocolSocketFactory
Protocol(String scheme, ProtocolSocketFactory factory, int defaultPort)
          Constructs a new Protocol.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 162 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/ReflectionSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/ReflectionSocke100644 0 0 14200 10661532627 31335 0ustar 0 0 Uses of Class org.apache.commons.httpclient.protocol.ReflectionSocketFactory (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.protocol.ReflectionSocketFactory

No usage of org.apache.commons.httpclient.protocol.ReflectionSocketFactory



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 163 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/SSLProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/SSLProtocolSock100644 0 0 14212 10661532627 31264 0ustar 0 0 Uses of Class org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory

No usage of org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 166 10661532634 10264 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/SecureProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/class-use/SecureProtocolS100644 0 0 23360 10661532627 31360 0ustar 0 0 Uses of Interface org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory (HttpClient 3.1 API)

Uses of Interface
org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory

Packages that use SecureProtocolSocketFactory
org.apache.commons.httpclient.protocol Provides protocol specific socket factory handling. 
 

Uses of SecureProtocolSocketFactory in org.apache.commons.httpclient.protocol
 

Classes in org.apache.commons.httpclient.protocol that implement SecureProtocolSocketFactory
 class SSLProtocolSocketFactory
          A SecureProtocolSocketFactory that uses JSSE to create sockets.
 

Constructors in org.apache.commons.httpclient.protocol with parameters of type SecureProtocolSocketFactory
Protocol(String scheme, SecureProtocolSocketFactory factory, int defaultPort)
          Deprecated. Use the constructor that uses ProtocolSocketFactory, this version of the constructor is only kept for backwards API compatibility.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/package-frame.html100644 0 0 4516 10661532627 27776 0ustar 0 0 org.apache.commons.httpclient.protocol (HttpClient 3.1 API) org.apache.commons.httpclient.protocol
Interfaces 
ProtocolSocketFactory
SecureProtocolSocketFactory
Classes 
ControllerThreadSocketFactory
ControllerThreadSocketFactory.SocketTask
DefaultProtocolSocketFactory
Protocol
ReflectionSocketFactory
SSLProtocolSocketFactory
commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/package-summary.html100644 0 0 22737 10661532627 30426 0ustar 0 0 org.apache.commons.httpclient.protocol (HttpClient 3.1 API)

Package org.apache.commons.httpclient.protocol

Provides protocol specific socket factory handling.

See:
          Description

Interface Summary
ProtocolSocketFactory A factory for creating Sockets.
SecureProtocolSocketFactory A ProtocolSocketFactory that is secure.
 

Class Summary
ControllerThreadSocketFactory This helper class is intedned to help work around the limitation of older Java versions (older than 1.4) that prevents from specifying a connection timeout when creating a socket.
ControllerThreadSocketFactory.SocketTask Helper class for wrapping socket based tasks.
DefaultProtocolSocketFactory The default class for creating protocol sockets.
Protocol A class to encapsulate the specifics of a protocol.
ReflectionSocketFactory This helper class uses refelction in order to execute Socket methods available in Java 1.4 and above
SSLProtocolSocketFactory A SecureProtocolSocketFactory that uses JSSE to create sockets.
 

Package org.apache.commons.httpclient.protocol Description

Provides protocol specific socket factory handling.

Since:
2.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/package-tree.html100644 0 0 21320 10661532627 27653 0ustar 0 0 org.apache.commons.httpclient.protocol Class Hierarchy (HttpClient 3.1 API)

Hierarchy For Package org.apache.commons.httpclient.protocol

Package Hierarchies:
All Packages

Class Hierarchy

Interface Hierarchy



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/protocol/package-use.html100644 0 0 22075 10661532627 27520 0ustar 0 0 Uses of Package org.apache.commons.httpclient.protocol (HttpClient 3.1 API)

Uses of Package
org.apache.commons.httpclient.protocol

Packages that use org.apache.commons.httpclient.protocol
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol. 
org.apache.commons.httpclient.protocol Provides protocol specific socket factory handling. 
 

Classes in org.apache.commons.httpclient.protocol used by org.apache.commons.httpclient
Protocol
          A class to encapsulate the specifics of a protocol.
 

Classes in org.apache.commons.httpclient.protocol used by org.apache.commons.httpclient.protocol
ControllerThreadSocketFactory.SocketTask
          Helper class for wrapping socket based tasks.
Protocol
          A class to encapsulate the specifics of a protocol.
ProtocolSocketFactory
          A factory for creating Sockets.
SecureProtocolSocketFactory
          A ProtocolSocketFactory that is secure.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/DateParseException.html100644 0 0 34743 10661532627 30203 0ustar 0 0 DateParseException (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class DateParseException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.apache.commons.httpclient.util.DateParseException
All Implemented Interfaces:
Serializable

public class DateParseException
extends Exception

An exception to indicate an error parsing a date string.

Author:
Michael Becke
See Also:
DateUtil, Serialized Form

Constructor Summary
DateParseException()
           
DateParseException(String message)
           
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

DateParseException

public DateParseException()

DateParseException

public DateParseException(String message)
Parameters:
message - the exception message


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/DateParser.html100644 0 0 44426 10661532627 26505 0ustar 0 0 DateParser (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class DateParser

java.lang.Object
  extended by org.apache.commons.httpclient.util.DateParser

Deprecated. Use DateUtil

public class DateParser
extends Object

A utility class for parsing HTTP dates as used in cookies and other headers. This class handles dates as defined by RFC 2616 section 3.3.1 as well as some other common non-standard formats.

Author:
Christopher Brown, Michael Becke

Field Summary
static String PATTERN_ASCTIME
          Deprecated. Date format pattern used to parse HTTP date headers in ANSI C asctime() format.
static String PATTERN_RFC1036
          Deprecated. Date format pattern used to parse HTTP date headers in RFC 1036 format.
static String PATTERN_RFC1123
          Deprecated. Date format pattern used to parse HTTP date headers in RFC 1123 format.
 
Method Summary
static Date parseDate(String dateValue)
          Deprecated. Parses a date value.
static Date parseDate(String dateValue, Collection dateFormats)
          Deprecated. Parses the date value using the given date formats.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

PATTERN_RFC1123

public static final String PATTERN_RFC1123
Deprecated. 
Date format pattern used to parse HTTP date headers in RFC 1123 format.

See Also:
Constant Field Values

PATTERN_RFC1036

public static final String PATTERN_RFC1036
Deprecated. 
Date format pattern used to parse HTTP date headers in RFC 1036 format.

See Also:
Constant Field Values

PATTERN_ASCTIME

public static final String PATTERN_ASCTIME
Deprecated. 
Date format pattern used to parse HTTP date headers in ANSI C asctime() format.

See Also:
Constant Field Values
Method Detail

parseDate

public static Date parseDate(String dateValue)
                      throws DateParseException
Deprecated. 
Parses a date value. The formats used for parsing the date value are retrieved from the default http params.

Parameters:
dateValue - the date value to parse
Returns:
the parsed date
Throws:
DateParseException - if the value could not be parsed using any of the supported date formats

parseDate

public static Date parseDate(String dateValue,
                             Collection dateFormats)
                      throws DateParseException
Deprecated. 
Parses the date value using the given date formats.

Parameters:
dateValue - the date value to parse
dateFormats - the date formats to use
Returns:
the parsed date
Throws:
DateParseException - if none of the dataFormats could parse the dateValue


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/DateUtil.html100644 0 0 60144 10661532627 26161 0ustar 0 0 DateUtil (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class DateUtil

java.lang.Object
  extended by org.apache.commons.httpclient.util.DateUtil

public class DateUtil
extends Object

A utility class for parsing and formatting HTTP dates as used in cookies and other headers. This class handles dates as defined by RFC 2616 section 3.3.1 as well as some other common non-standard formats.

Author:
Christopher Brown, Michael Becke

Field Summary
static String PATTERN_ASCTIME
          Date format pattern used to parse HTTP date headers in ANSI C asctime() format.
static String PATTERN_RFC1036
          Date format pattern used to parse HTTP date headers in RFC 1036 format.
static String PATTERN_RFC1123
          Date format pattern used to parse HTTP date headers in RFC 1123 format.
 
Method Summary
static String formatDate(Date date)
          Formats the given date according to the RFC 1123 pattern.
static String formatDate(Date date, String pattern)
          Formats the given date according to the specified pattern.
static Date parseDate(String dateValue)
          Parses a date value.
static Date parseDate(String dateValue, Collection dateFormats)
          Parses the date value using the given date formats.
static Date parseDate(String dateValue, Collection dateFormats, Date startDate)
          Parses the date value using the given date formats.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

PATTERN_RFC1123

public static final String PATTERN_RFC1123
Date format pattern used to parse HTTP date headers in RFC 1123 format.

See Also:
Constant Field Values

PATTERN_RFC1036

public static final String PATTERN_RFC1036
Date format pattern used to parse HTTP date headers in RFC 1036 format.

See Also:
Constant Field Values

PATTERN_ASCTIME

public static final String PATTERN_ASCTIME
Date format pattern used to parse HTTP date headers in ANSI C asctime() format.

See Also:
Constant Field Values
Method Detail

parseDate

public static Date parseDate(String dateValue)
                      throws DateParseException
Parses a date value. The formats used for parsing the date value are retrieved from the default http params.

Parameters:
dateValue - the date value to parse
Returns:
the parsed date
Throws:
DateParseException - if the value could not be parsed using any of the supported date formats

parseDate

public static Date parseDate(String dateValue,
                             Collection dateFormats)
                      throws DateParseException
Parses the date value using the given date formats.

Parameters:
dateValue - the date value to parse
dateFormats - the date formats to use
Returns:
the parsed date
Throws:
DateParseException - if none of the dataFormats could parse the dateValue

parseDate

public static Date parseDate(String dateValue,
                             Collection dateFormats,
                             Date startDate)
                      throws DateParseException
Parses the date value using the given date formats.

Parameters:
dateValue - the date value to parse
dateFormats - the date formats to use
startDate - During parsing, two digit years will be placed in the range startDate to startDate + 100 years. This value may be null. When null is given as a parameter, year 2000 will be used.
Returns:
the parsed date
Throws:
DateParseException - if none of the dataFormats could parse the dateValue

formatDate

public static String formatDate(Date date)
Formats the given date according to the RFC 1123 pattern.

Parameters:
date - The date to format.
Returns:
An RFC 1123 formatted date string.
See Also:
PATTERN_RFC1123

formatDate

public static String formatDate(Date date,
                                String pattern)
Formats the given date according to the specified pattern. The pattern must conform to that used by the simple date format class.

Parameters:
date - The date to format.
pattern - The pattern to use for formatting the date.
Returns:
A formatted date string.
Throws:
IllegalArgumentException - If the given date pattern is invalid.
See Also:
SimpleDateFormat


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/EncodingUtil.html100644 0 0 52077 10661532627 27040 0ustar 0 0 EncodingUtil (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class EncodingUtil

java.lang.Object
  extended by org.apache.commons.httpclient.util.EncodingUtil

public class EncodingUtil
extends Object

The home for utility methods that handle various encoding tasks.

Since:
2.0 final
Author:
Michael Becke, Oleg Kalnichevski

Method Summary
static String formUrlEncode(NameValuePair[] pairs, String charset)
          Form-urlencoding routine.
static byte[] getAsciiBytes(String data)
          Converts the specified string to byte array of ASCII characters.
static String getAsciiString(byte[] data)
          Converts the byte array of ASCII characters to a string.
static String getAsciiString(byte[] data, int offset, int length)
          Converts the byte array of ASCII characters to a string.
static byte[] getBytes(String data, String charset)
          Converts the specified string to a byte array.
static String getString(byte[] data, int offset, int length, String charset)
          Converts the byte array of HTTP content characters to a string.
static String getString(byte[] data, String charset)
          Converts the byte array of HTTP content characters to a string.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

formUrlEncode

public static String formUrlEncode(NameValuePair[] pairs,
                                   String charset)
Form-urlencoding routine. The default encoding for all forms is `application/x-www-form-urlencoded'. A form data set is represented in this media type as follows: The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped as per [URL]; that is, non-alphanumeric characters are replaced by `%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks, as in multi-line text field values, are represented as CR LF pairs, i.e. `%0D%0A'.

if the given charset is not supported, ISO-8859-1 is used instead.

Parameters:
pairs - the values to be encoded
charset - the character set of pairs to be encoded
Returns:
the urlencoded pairs
Since:
2.0 final

getString

public static String getString(byte[] data,
                               int offset,
                               int length,
                               String charset)
Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.

Parameters:
data - the byte array to be encoded
offset - the index of the first byte to encode
length - the number of bytes to encode
charset - the desired character encoding
Returns:
The result of the conversion.
Since:
3.0

getString

public static String getString(byte[] data,
                               String charset)
Converts the byte array of HTTP content characters to a string. If the specified charset is not supported, default system encoding is used.

Parameters:
data - the byte array to be encoded
charset - the desired character encoding
Returns:
The result of the conversion.
Since:
3.0

getBytes

public static byte[] getBytes(String data,
                              String charset)
Converts the specified string to a byte array. If the charset is not supported the default system charset is used.

Parameters:
data - the string to be encoded
charset - the desired character encoding
Returns:
The resulting byte array.
Since:
3.0

getAsciiBytes

public static byte[] getAsciiBytes(String data)
Converts the specified string to byte array of ASCII characters.

Parameters:
data - the string to be encoded
Returns:
The string as a byte array.
Since:
3.0

getAsciiString

public static String getAsciiString(byte[] data,
                                    int offset,
                                    int length)
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)

Parameters:
data - the byte array to be encoded
offset - the index of the first byte to encode
length - the number of bytes to encode
Returns:
The string representation of the byte array
Since:
3.0

getAsciiString

public static String getAsciiString(byte[] data)
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)

Parameters:
data - the byte array to be encoded
Returns:
The string representation of the byte array
Since:
3.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/ExceptionUtil.html100644 0 0 34446 10661532627 27250 0ustar 0 0 ExceptionUtil (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class ExceptionUtil

java.lang.Object
  extended by org.apache.commons.httpclient.util.ExceptionUtil

public class ExceptionUtil
extends Object

The home for utility methods that handle various exception-related tasks.

Since:
3.0
Author:
Oleg Kalnichevski, Laura Werner

Constructor Summary
ExceptionUtil()
           
 
Method Summary
static void initCause(Throwable throwable, Throwable cause)
          If we're running on JDK 1.4 or later, initialize the cause for the given throwable.
static boolean isSocketTimeoutException(InterruptedIOException e)
          If SocketTimeoutExceptionClass is defined, returns true only if the exception is an instance of SocketTimeoutExceptionClass.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ExceptionUtil

public ExceptionUtil()
Method Detail

initCause

public static void initCause(Throwable throwable,
                             Throwable cause)
If we're running on JDK 1.4 or later, initialize the cause for the given throwable.

Parameters:
throwable - The throwable.
cause - The cause of the throwable.

isSocketTimeoutException

public static boolean isSocketTimeoutException(InterruptedIOException e)
If SocketTimeoutExceptionClass is defined, returns true only if the exception is an instance of SocketTimeoutExceptionClass. If SocketTimeoutExceptionClass is undefined, always returns true.

Parameters:
e - an instance of InterruptedIOException class.
Returns:
true if the exception signals socket timeout, false otherwise.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/HttpURLConnection.html100644 0 0 231460 10661532627 30011 0ustar 0 0 HttpURLConnection (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class HttpURLConnection

java.lang.Object
  extended by java.net.URLConnection
      extended by java.net.HttpURLConnection
          extended by org.apache.commons.httpclient.util.HttpURLConnection

public class HttpURLConnection
extends HttpURLConnection

Provides a HttpURLConnection wrapper around HttpClient's HttpMethod. This allows existing code to easily switch to HttpClieht without breaking existing interfaces using the JDK HttpURLConnection. Note 1: The current implementations wraps only a connected HttpMethod, ie a method that has alreayd been used to connect to an HTTP server. Note 2: It is a best try effort as different version of the JDK have different behaviours for HttpURLConnection (And I'm not even including the numerous HttpURLConnection bugs!).

Since:
2.0
Version:
$Id: HttpURLConnection.java 480424 2006-11-29 05:56:49Z bayard $
Author:
Vincent Massol, Jeff Dever, Mike Bowler

Field Summary
 
Fields inherited from class java.net.HttpURLConnection
chunkLength, fixedContentLength, HTTP_ACCEPTED, HTTP_BAD_GATEWAY, HTTP_BAD_METHOD, HTTP_BAD_REQUEST, HTTP_CLIENT_TIMEOUT, HTTP_CONFLICT, HTTP_CREATED, HTTP_ENTITY_TOO_LARGE, HTTP_FORBIDDEN, HTTP_GATEWAY_TIMEOUT, HTTP_GONE, HTTP_INTERNAL_ERROR, HTTP_LENGTH_REQUIRED, HTTP_MOVED_PERM, HTTP_MOVED_TEMP, HTTP_MULT_CHOICE, HTTP_NO_CONTENT, HTTP_NOT_ACCEPTABLE, HTTP_NOT_AUTHORITATIVE, HTTP_NOT_FOUND, HTTP_NOT_IMPLEMENTED, HTTP_NOT_MODIFIED, HTTP_OK, HTTP_PARTIAL, HTTP_PAYMENT_REQUIRED, HTTP_PRECON_FAILED, HTTP_PROXY_AUTH, HTTP_REQ_TOO_LONG, HTTP_RESET, HTTP_SEE_OTHER, HTTP_SERVER_ERROR, HTTP_UNAUTHORIZED, HTTP_UNAVAILABLE, HTTP_UNSUPPORTED_TYPE, HTTP_USE_PROXY, HTTP_VERSION, instanceFollowRedirects, responseCode, responseMessage
 
Fields inherited from class java.net.URLConnection
allowUserInteraction, connected, doInput, doOutput, ifModifiedSince, useCaches
 
Constructor Summary
  HttpURLConnection(HttpMethod method, URL url)
          Creates an HttpURLConnection from a HttpMethod.
protected HttpURLConnection(URL url)
          Create an instance.
 
Method Summary
 void connect()
          Not available: the data must have already been retrieved.
 void disconnect()
          Not yet implemented.
 boolean getAllowUserInteraction()
          Not yet implemented.
 Object getContent()
          Not yet implemented.
 Object getContent(Class[] classes)
          Not yet implemented.
 boolean getDefaultUseCaches()
          Not available: the data must have already been retrieved.
 boolean getDoInput()
          Not yet implemented.
 boolean getDoOutput()
          Not yet implemented.
 InputStream getErrorStream()
          Not yet implemented.
 String getHeaderField(int position)
          Return the header field at the specified position
 String getHeaderField(String name)
          Return the header field
 String getHeaderFieldKey(int keyPosition)
          Return the header field key
 long getIfModifiedSince()
          Not yet implemented.
 InputStream getInputStream()
          Gets an input stream for the HttpMethod response body.
 boolean getInstanceFollowRedirects()
          Not yet implemented.
 OutputStream getOutputStream()
           
 Permission getPermission()
          Not yet implemented.
 String getRequestMethod()
          Return the request method.
 String getRequestProperty(String key)
          Not yet implemented.
 int getResponseCode()
          Return the response code.
 String getResponseMessage()
          Return the response message
 URL getURL()
          Return the URL
 boolean getUseCaches()
          Not yet implemented.
 void setAllowUserInteraction(boolean isAllowInteraction)
          Not available: the data must have already been retrieved.
 void setDefaultUseCaches(boolean isUsingCaches)
          Not available: the data must have already been retrieved.
 void setDoInput(boolean isInput)
          Not available: the data must have already been retrieved.
 void setDoOutput(boolean isOutput)
          Not available: the data must have already been retrieved.
 void setIfModifiedSince(long modificationDate)
          Not available: the data must have already been retrieved.
 void setInstanceFollowRedirects(boolean isFollowingRedirects)
          Not available: the data must have already been retrieved.
 void setRequestMethod(String method)
          Not available: the data must have already been retrieved.
 void setRequestProperty(String key, String value)
          Not available: the data must have already been retrieved.
 void setUseCaches(boolean isUsingCaches)
          Not available: the data must have already been retrieved.
 boolean usingProxy()
          Not yet implemented.
 
Methods inherited from class java.net.HttpURLConnection
getFollowRedirects, getHeaderFieldDate, setChunkedStreamingMode, setFixedLengthStreamingMode, setFollowRedirects
 
Methods inherited from class java.net.URLConnection
addRequestProperty, getConnectTimeout, getContentEncoding, getContentLength, getContentType, getDate, getDefaultAllowUserInteraction, getDefaultRequestProperty, getExpiration, getFileNameMap, getHeaderFieldInt, getHeaderFields, getLastModified, getReadTimeout, getRequestProperties, guessContentTypeFromName, guessContentTypeFromStream, setConnectTimeout, setContentHandlerFactory, setDefaultAllowUserInteraction, setDefaultRequestProperty, setFileNameMap, setReadTimeout, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

HttpURLConnection

public HttpURLConnection(HttpMethod method,
                         URL url)
Creates an HttpURLConnection from a HttpMethod.

Parameters:
method - the theMethod that was used to connect to the HTTP server and which contains the returned data.
url - the URL to which we are connected (includes query string)

HttpURLConnection

protected HttpURLConnection(URL url)
Create an instance.

Parameters:
url - The URL.
See Also:
HttpURLConnection.HttpURLConnection(URL)
Method Detail

getInputStream

public InputStream getInputStream()
                           throws IOException
Gets an input stream for the HttpMethod response body.

Overrides:
getInputStream in class URLConnection
Returns:
The input stream.
Throws:
IOException - If an IO problem occurs.
See Also:
URLConnection.getInputStream(), HttpMethod.getResponseBodyAsStream()

getErrorStream

public InputStream getErrorStream()
Not yet implemented. Return the error stream.

Overrides:
getErrorStream in class HttpURLConnection
See Also:
HttpURLConnection.getErrorStream()

disconnect

public void disconnect()
Not yet implemented.

Specified by:
disconnect in class HttpURLConnection
See Also:
HttpURLConnection.disconnect()

connect

public void connect()
             throws IOException
Not available: the data must have already been retrieved.

Specified by:
connect in class URLConnection
Throws:
IOException - If an IO problem occurs.
See Also:
URLConnection.connect()

usingProxy

public boolean usingProxy()
Not yet implemented.

Specified by:
usingProxy in class HttpURLConnection
Returns:
true if we are using a proxy.
See Also:
HttpURLConnection.usingProxy()

getRequestMethod

public String getRequestMethod()
Return the request method.

Overrides:
getRequestMethod in class HttpURLConnection
Returns:
The request method.
See Also:
HttpURLConnection.getRequestMethod(), HttpMethod.getName()

getResponseCode

public int getResponseCode()
                    throws IOException
Return the response code.

Overrides:
getResponseCode in class HttpURLConnection
Returns:
The response code.
Throws:
IOException - If an IO problem occurs.
See Also:
HttpURLConnection.getResponseCode(), HttpMethod.getStatusCode()

getResponseMessage

public String getResponseMessage()
                          throws IOException
Return the response message

Overrides:
getResponseMessage in class HttpURLConnection
Returns:
The response message
Throws:
IOException - If an IO problem occurs.
See Also:
HttpURLConnection.getResponseMessage(), HttpMethod.getStatusText()

getHeaderField

public String getHeaderField(String name)
Return the header field

Overrides:
getHeaderField in class URLConnection
Parameters:
name - the name of the header
Returns:
the header field.
See Also:
URLConnection.getHeaderField(String), HttpMethod.getResponseHeaders()

getHeaderFieldKey

public String getHeaderFieldKey(int keyPosition)
Return the header field key

Overrides:
getHeaderFieldKey in class HttpURLConnection
Parameters:
keyPosition - The key position
Returns:
The header field key.
See Also:
HttpURLConnection.getHeaderFieldKey(int), HttpMethod.getResponseHeaders()

getHeaderField

public String getHeaderField(int position)
Return the header field at the specified position

Overrides:
getHeaderField in class HttpURLConnection
Parameters:
position - The position
Returns:
The header field.
See Also:
HttpURLConnection.getHeaderField(int), HttpMethod.getResponseHeaders()

getURL

public URL getURL()
Return the URL

Overrides:
getURL in class URLConnection
Returns:
The URL.
See Also:
URLConnection.getURL()

setInstanceFollowRedirects

public void setInstanceFollowRedirects(boolean isFollowingRedirects)
Not available: the data must have already been retrieved.

Overrides:
setInstanceFollowRedirects in class HttpURLConnection

getInstanceFollowRedirects

public boolean getInstanceFollowRedirects()
Not yet implemented.

Overrides:
getInstanceFollowRedirects in class HttpURLConnection

setRequestMethod

public void setRequestMethod(String method)
                      throws ProtocolException
Not available: the data must have already been retrieved.

Overrides:
setRequestMethod in class HttpURLConnection
Throws:
ProtocolException
See Also:
HttpURLConnection.setRequestMethod(String)

getPermission

public Permission getPermission()
                         throws IOException
Not yet implemented.

Overrides:
getPermission in class HttpURLConnection
Throws:
IOException
See Also:
HttpURLConnection.getPermission()

getContent

public Object getContent()
                  throws IOException
Not yet implemented.

Overrides:
getContent in class URLConnection
Throws:
IOException
See Also:
URLConnection.getContent()

getContent

public Object getContent(Class[] classes)
                  throws IOException
Not yet implemented.

Overrides:
getContent in class URLConnection
Throws:
IOException

getOutputStream

public OutputStream getOutputStream()
                             throws IOException
Overrides:
getOutputStream in class URLConnection
Throws:
IOException
See Also:
URLConnection.getOutputStream()

setDoInput

public void setDoInput(boolean isInput)
Not available: the data must have already been retrieved.

Overrides:
setDoInput in class URLConnection
See Also:
URLConnection.setDoInput(boolean)

getDoInput

public boolean getDoInput()
Not yet implemented.

Overrides:
getDoInput in class URLConnection
See Also:
URLConnection.getDoInput()

setDoOutput

public void setDoOutput(boolean isOutput)
Not available: the data must have already been retrieved.

Overrides:
setDoOutput in class URLConnection
See Also:
URLConnection.setDoOutput(boolean)

getDoOutput

public boolean getDoOutput()
Not yet implemented.

Overrides:
getDoOutput in class URLConnection
See Also:
URLConnection.getDoOutput()

setAllowUserInteraction

public void setAllowUserInteraction(boolean isAllowInteraction)
Not available: the data must have already been retrieved.

Overrides:
setAllowUserInteraction in class URLConnection
See Also:
URLConnection.setAllowUserInteraction(boolean)

getAllowUserInteraction

public boolean getAllowUserInteraction()
Not yet implemented.

Overrides:
getAllowUserInteraction in class URLConnection
See Also:
URLConnection.getAllowUserInteraction()

setUseCaches

public void setUseCaches(boolean isUsingCaches)
Not available: the data must have already been retrieved.

Overrides:
setUseCaches in class URLConnection
See Also:
URLConnection.setUseCaches(boolean)

getUseCaches

public boolean getUseCaches()
Not yet implemented.

Overrides:
getUseCaches in class URLConnection
See Also:
URLConnection.getUseCaches()

setIfModifiedSince

public void setIfModifiedSince(long modificationDate)
Not available: the data must have already been retrieved.

Overrides:
setIfModifiedSince in class URLConnection
See Also:
URLConnection.setIfModifiedSince(long)

getIfModifiedSince

public long getIfModifiedSince()
Not yet implemented.

Overrides:
getIfModifiedSince in class URLConnection
See Also:
URLConnection.getIfModifiedSince()

getDefaultUseCaches

public boolean getDefaultUseCaches()
Not available: the data must have already been retrieved.

Overrides:
getDefaultUseCaches in class URLConnection
See Also:
URLConnection.getDefaultUseCaches()

setDefaultUseCaches

public void setDefaultUseCaches(boolean isUsingCaches)
Not available: the data must have already been retrieved.

Overrides:
setDefaultUseCaches in class URLConnection
See Also:
URLConnection.setDefaultUseCaches(boolean)

setRequestProperty

public void setRequestProperty(String key,
                               String value)
Not available: the data must have already been retrieved.

Overrides:
setRequestProperty in class URLConnection
See Also:
URLConnection.setRequestProperty(String,String)

getRequestProperty

public String getRequestProperty(String key)
Not yet implemented.

Overrides:
getRequestProperty in class URLConnection
See Also:
URLConnection.getRequestProperty(String)


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/IdleConnectionHandler.html100644 0 0 37374 10661532627 30652 0ustar 0 0 IdleConnectionHandler (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class IdleConnectionHandler

java.lang.Object
  extended by org.apache.commons.httpclient.util.IdleConnectionHandler

public class IdleConnectionHandler
extends Object

A helper class for connection managers to track idle connections.

This class is not synchronized.

Since:
3.0
See Also:
HttpConnectionManager.closeIdleConnections(long)

Constructor Summary
IdleConnectionHandler()
           
 
Method Summary
 void add(HttpConnection connection)
          Registers the given connection with this handler.
 void closeIdleConnections(long idleTime)
          Closes connections that have been idle for at least the given amount of time.
 void remove(HttpConnection connection)
          Removes the given connection from the list of connections to be closed when idle.
 void removeAll()
          Removes all connections referenced by this handler.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

IdleConnectionHandler

public IdleConnectionHandler()
Method Detail

add

public void add(HttpConnection connection)
Registers the given connection with this handler. The connection will be held until remove(HttpConnection) or closeIdleConnections(long) is called.

Parameters:
connection - the connection to add
See Also:
remove(HttpConnection)

remove

public void remove(HttpConnection connection)
Removes the given connection from the list of connections to be closed when idle.

Parameters:
connection -

removeAll

public void removeAll()
Removes all connections referenced by this handler.


closeIdleConnections

public void closeIdleConnections(long idleTime)
Closes connections that have been idle for at least the given amount of time.

Parameters:
idleTime - the minimum idle time, in milliseconds, for connections to be closed


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/IdleConnectionTimeoutThread.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/IdleConnectionTimeoutThread.h100644 0 0 72063 10661532627 31330 0ustar 0 0 IdleConnectionTimeoutThread (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class IdleConnectionTimeoutThread

java.lang.Object
  extended by java.lang.Thread
      extended by org.apache.commons.httpclient.util.IdleConnectionTimeoutThread
All Implemented Interfaces:
Runnable

public class IdleConnectionTimeoutThread
extends Thread

A utility class for periodically closing idle connections.

Since:
3.0
See Also:
HttpConnectionManager.closeIdleConnections(long)

Nested Class Summary
 
Nested classes/interfaces inherited from class java.lang.Thread
Thread.State, Thread.UncaughtExceptionHandler
 
Field Summary
 
Fields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
 
Constructor Summary
IdleConnectionTimeoutThread()
           
 
Method Summary
 void addConnectionManager(HttpConnectionManager connectionManager)
          Adds a connection manager to be handled by this class.
protected  void handleCloseIdleConnections(HttpConnectionManager connectionManager)
          Handles calling closeIdleConnections() and doing any other cleanup work on the given connection mangaer.
 void removeConnectionManager(HttpConnectionManager connectionManager)
          Removes the connection manager from this class.
 void run()
          Closes idle connections.
 void setConnectionTimeout(long connectionTimeout)
          Sets the timeout value to use when testing for idle connections.
 void setTimeoutInterval(long timeoutInterval)
          Sets the interval used by this class between closing idle connections.
 void shutdown()
          Stops the thread used to close idle connections.
 
Methods inherited from class java.lang.Thread
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, stop, suspend, toString, yield
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

IdleConnectionTimeoutThread

public IdleConnectionTimeoutThread()
Method Detail

addConnectionManager

public void addConnectionManager(HttpConnectionManager connectionManager)
Adds a connection manager to be handled by this class. HttpConnectionManager.closeIdleConnections(long) will be called on the connection manager every timeoutInterval milliseconds.

Parameters:
connectionManager - The connection manager to add

removeConnectionManager

public void removeConnectionManager(HttpConnectionManager connectionManager)
Removes the connection manager from this class. The idle connections from the connection manager will no longer be automatically closed by this class.

Parameters:
connectionManager - The connection manager to remove

handleCloseIdleConnections

protected void handleCloseIdleConnections(HttpConnectionManager connectionManager)
Handles calling closeIdleConnections() and doing any other cleanup work on the given connection mangaer.

Parameters:
connectionManager - The connection manager to close idle connections for

run

public void run()
Closes idle connections.

Specified by:
run in interface Runnable
Overrides:
run in class Thread

shutdown

public void shutdown()
Stops the thread used to close idle connections. This class cannot be used once shutdown.


setConnectionTimeout

public void setConnectionTimeout(long connectionTimeout)
Sets the timeout value to use when testing for idle connections.

Parameters:
connectionTimeout - The connection timeout in milliseconds
See Also:
HttpConnectionManager.closeIdleConnections(long)

setTimeoutInterval

public void setTimeoutInterval(long timeoutInterval)
Sets the interval used by this class between closing idle connections. Idle connections will be closed every timeoutInterval milliseconds.

Parameters:
timeoutInterval - The timeout interval in milliseconds


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/LangUtils.html100644 0 0 36455 10661532627 26360 0ustar 0 0 LangUtils (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class LangUtils

java.lang.Object
  extended by org.apache.commons.httpclient.util.LangUtils

public class LangUtils
extends Object

A set of utility methods to help produce consistent Object#equals(Object) and Object#hashCode methods.

Since:
3.0
Author:
Oleg Kalnichevski

Field Summary
static int HASH_OFFSET
           
static int HASH_SEED
           
 
Method Summary
static boolean equals(Object obj1, Object obj2)
           
static int hashCode(int seed, boolean b)
           
static int hashCode(int seed, int hashcode)
           
static int hashCode(int seed, Object obj)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

HASH_SEED

public static final int HASH_SEED
See Also:
Constant Field Values

HASH_OFFSET

public static final int HASH_OFFSET
See Also:
Constant Field Values
Method Detail

hashCode

public static int hashCode(int seed,
                           int hashcode)

hashCode

public static int hashCode(int seed,
                           Object obj)

hashCode

public static int hashCode(int seed,
                           boolean b)

equals

public static boolean equals(Object obj1,
                             Object obj2)


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/ParameterFormatter.html100644 0 0 47026 10661532627 30256 0ustar 0 0 ParameterFormatter (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class ParameterFormatter

java.lang.Object
  extended by org.apache.commons.httpclient.util.ParameterFormatter

public class ParameterFormatter
extends Object

This formatter produces a textual representation of attribute/value pairs. It comforms to the generic grammar and formatting rules outlined in the Section 2.1 and Section 3.6 of RFC 2616

2.1 Augmented BNF

Many HTTP/1.1 header field values consist of words separated by LWS or special characters. These special characters MUST be in a quoted string to be used within a parameter value (as defined in section 3.6).

 token          = 1*
 separators     = "(" | ")" | "<" | ">" | "@"
                | "," | ";" | ":" | "\" | <">
                | "/" | "[" | "]" | "?" | "="
                | "{" | "}" | SP | HT
 

A string of text is parsed as a single word if it is quoted using double-quote marks.

 quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
 qdtext         = >
 

The backslash character ("\") MAY be used as a single-character quoting mechanism only within quoted-string and comment constructs.

 quoted-pair    = "\" CHAR
 
3.6 Transfer Codings

Parameters are in the form of attribute/value pairs.

 parameter               = attribute "=" value
 attribute               = token
 value                   = token | quoted-string
 

Since:
3.0
Author:
Oleg Kalnichevski

Constructor Summary
ParameterFormatter()
          Default ParameterFormatter constructor
 
Method Summary
 String format(NameValuePair param)
          Produces textual representaion of the attribute/value pair using formatting rules defined in RFC 2616
 void format(StringBuffer buffer, NameValuePair param)
          Produces textual representaion of the attribute/value pair using formatting rules defined in RFC 2616
static void formatValue(StringBuffer buffer, String value, boolean alwaysUseQuotes)
          Formats the given parameter value using formatting rules defined in RFC 2616
 boolean isAlwaysUseQuotes()
          Determines whether all parameter values must be enclosed in quotation marks, even if they do not contain any special characters
 void setAlwaysUseQuotes(boolean alwaysUseQuotes)
          Defines whether all parameter values must be enclosed in quotation marks, even if they do not contain any special characters
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ParameterFormatter

public ParameterFormatter()
Default ParameterFormatter constructor

Method Detail

isAlwaysUseQuotes

public boolean isAlwaysUseQuotes()
Determines whether all parameter values must be enclosed in quotation marks, even if they do not contain any special characters

Returns:
true if all parameter values must be enclosed in quotation marks, false otherwise

setAlwaysUseQuotes

public void setAlwaysUseQuotes(boolean alwaysUseQuotes)
Defines whether all parameter values must be enclosed in quotation marks, even if they do not contain any special characters

Parameters:
alwaysUseQuotes -

formatValue

public static void formatValue(StringBuffer buffer,
                               String value,
                               boolean alwaysUseQuotes)
Formats the given parameter value using formatting rules defined in RFC 2616

Parameters:
buffer - output buffer
value - the parameter value to be formatted
alwaysUseQuotes - true if the parameter value must be enclosed in quotation marks, even if it does not contain any special characters, false only if the parameter value contains potentially unsafe special characters

format

public void format(StringBuffer buffer,
                   NameValuePair param)
Produces textual representaion of the attribute/value pair using formatting rules defined in RFC 2616

Parameters:
buffer - output buffer
param - the parameter to be formatted

format

public String format(NameValuePair param)
Produces textual representaion of the attribute/value pair using formatting rules defined in RFC 2616

Parameters:
param - the parameter to be formatted
Returns:
RFC 2616 conformant textual representaion of the attribute/value pair


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/ParameterParser.html100644 0 0 41226 10661532627 27543 0ustar 0 0 ParameterParser (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class ParameterParser

java.lang.Object
  extended by org.apache.commons.httpclient.util.ParameterParser

public class ParameterParser
extends Object

A simple parser intended to parse sequences of name/value pairs. Parameter values are exptected to be enclosed in quotes if they contain unsafe characters, such as '=' characters or separators. Parameter values are optional and can be omitted.

param1 = value; param2 = "anything goes; really"; param3

Since:
3.0
Author:
Oleg Kalnichevski

Constructor Summary
ParameterParser()
          Default ParameterParser constructor
 
Method Summary
 List parse(char[] chars, char separator)
          Extracts a list of NameValuePairs from the given array of characters.
 List parse(char[] chars, int offset, int length, char separator)
          Extracts a list of NameValuePairs from the given array of characters.
 List parse(String str, char separator)
          Extracts a list of NameValuePairs from the given string.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ParameterParser

public ParameterParser()
Default ParameterParser constructor

Method Detail

parse

public List parse(String str,
                  char separator)
Extracts a list of NameValuePairs from the given string.

Parameters:
str - the string that contains a sequence of name/value pairs
Returns:
a list of NameValuePairs

parse

public List parse(char[] chars,
                  char separator)
Extracts a list of NameValuePairs from the given array of characters.

Parameters:
chars - the array of characters that contains a sequence of name/value pairs
Returns:
a list of NameValuePairs

parse

public List parse(char[] chars,
                  int offset,
                  int length,
                  char separator)
Extracts a list of NameValuePairs from the given array of characters.

Parameters:
chars - the array of characters that contains a sequence of name/value pairs
offset - - the initial offset.
length - - the length.
Returns:
a list of NameValuePairs


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 157 10661532634 10264 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/TimeoutController.TimeoutException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/TimeoutController.TimeoutExce100644 0 0 34450 10661532627 31430 0ustar 0 0 TimeoutController.TimeoutException (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class TimeoutController.TimeoutException

java.lang.Object
  extended by java.lang.Throwable
      extended by java.lang.Exception
          extended by org.apache.commons.httpclient.util.TimeoutController.TimeoutException
All Implemented Interfaces:
Serializable
Enclosing class:
TimeoutController

public static class TimeoutController.TimeoutException
extends Exception

Signals that the task timed out.

See Also:
Serialized Form

Constructor Summary
TimeoutController.TimeoutException()
          Create an instance
 
Method Summary
 
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

TimeoutController.TimeoutException

public TimeoutController.TimeoutException()
Create an instance



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/TimeoutController.html100644 0 0 35305 10661532627 30141 0ustar 0 0 TimeoutController (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class TimeoutController

java.lang.Object
  extended by org.apache.commons.httpclient.util.TimeoutController

public final class TimeoutController
extends Object

Executes a task with a specified timeout.

Since:
2.0
Version:
$Revision: 480424 $
Author:
Ortwin Glueck, Mike Bowler

Nested Class Summary
static class TimeoutController.TimeoutException
          Signals that the task timed out.
 
Method Summary
static void execute(Runnable task, long timeout)
          Executes task in a new deamon Thread and waits for the timeout.
static void execute(Thread task, long timeout)
          Executes task.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

execute

public static void execute(Thread task,
                           long timeout)
                    throws TimeoutController.TimeoutException
Executes task. Waits for timeout milliseconds for the task to end and returns. If the task does not return in time, the thread is interrupted and an Exception is thrown. The caller should override the Thread.interrupt() method to something that quickly makes the thread die or use Thread.isInterrupted().

Parameters:
task - The thread to execute
timeout - The timeout in milliseconds. 0 means to wait forever.
Throws:
TimeoutController.TimeoutException - if the timeout passes and the thread does not return.

execute

public static void execute(Runnable task,
                           long timeout)
                    throws TimeoutController.TimeoutException
Executes task in a new deamon Thread and waits for the timeout.

Parameters:
task - The task to execute
timeout - The timeout in milliseconds. 0 means to wait forever.
Throws:
TimeoutController.TimeoutException - if the timeout passes and the thread does not return.


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/URIUtil.Coder.html100644 0 0 120424 10661532627 27014 0ustar 0 0 URIUtil.Coder (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class URIUtil.Coder

java.lang.Object
  extended by org.apache.commons.httpclient.URI
      extended by org.apache.commons.httpclient.util.URIUtil.Coder
All Implemented Interfaces:
Serializable, Cloneable, Comparable
Enclosing class:
URIUtil

Deprecated. use org.apache.commons.codec.net.URLCodec

protected static class URIUtil.Coder
extends URI

The basic and internal utility for URI escape and character encoding and decoding.

See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class org.apache.commons.httpclient.URI
URI.DefaultCharsetChanged, URI.LocaleToCharsetMap
 
Field Summary
 
Fields inherited from class org.apache.commons.httpclient.URI
_authority, _fragment, _host, _is_abs_path, _is_hier_part, _is_hostname, _is_IPv4address, _is_IPv6reference, _is_net_path, _is_opaque_part, _is_reg_name, _is_rel_path, _is_server, _opaque, _path, _port, _query, _scheme, _uri, _userinfo, abs_path, absoluteURI, allowed_abs_path, allowed_authority, allowed_fragment, allowed_host, allowed_IPv6reference, allowed_opaque_part, allowed_query, allowed_reg_name, allowed_rel_path, allowed_userinfo, allowed_within_authority, allowed_within_path, allowed_within_query, allowed_within_userinfo, alpha, alphanum, authority, control, defaultDocumentCharset, defaultDocumentCharsetByLocale, defaultDocumentCharsetByPlatform, defaultProtocolCharset, delims, digit, disallowed_opaque_part, disallowed_rel_path, domainlabel, escaped, fragment, hash, hex, hier_part, host, hostname, hostport, IPv4address, IPv6address, IPv6reference, mark, net_path, opaque_part, param, path, path_segments, pchar, percent, port, protocolCharset, query, reg_name, rel_path, rel_segment, relativeURI, reserved, rootPath, scheme, segment, server, space, toplabel, unreserved, unwise, URI_reference, uric, uric_no_slash, userinfo, within_userinfo
 
Constructor Summary
protected URIUtil.Coder()
          Deprecated.  
 
Method Summary
static String decode(char[] escapedComponent, String charset)
          Deprecated. use org.apache.commons.codec.net.URLCodec
static char[] encode(String unescapedComponent, BitSet allowed, String charset)
          Deprecated. use org.apache.commons.codec.net.URLCodec
static String replace(String original, char[] from, char[] to)
          Deprecated. Replace from a given character to given character in an array order for a given string.
static String replace(String original, char from, char to)
          Deprecated. Replace from a given character to given character for a given string.
static boolean verifyEscaped(char[] original)
          Deprecated. Verify whether a given string is escaped or not
 
Methods inherited from class org.apache.commons.httpclient.URI
clone, compareTo, decode, equals, equals, getAboveHierPath, getAuthority, getCurrentHierPath, getDefaultDocumentCharset, getDefaultDocumentCharsetByLocale, getDefaultDocumentCharsetByPlatform, getDefaultProtocolCharset, getEscapedAboveHierPath, getEscapedAuthority, getEscapedCurrentHierPath, getEscapedFragment, getEscapedName, getEscapedPath, getEscapedPathQuery, getEscapedQuery, getEscapedURI, getEscapedURIReference, getEscapedUserinfo, getFragment, getHost, getName, getPath, getPathQuery, getPort, getProtocolCharset, getQuery, getRawAboveHierPath, getRawAuthority, getRawCurrentHierPath, getRawCurrentHierPath, getRawFragment, getRawHost, getRawName, getRawPath, getRawPathQuery, getRawQuery, getRawScheme, getRawURI, getRawURIReference, getRawUserinfo, getScheme, getURI, getURIReference, getUserinfo, hasAuthority, hasFragment, hashCode, hasQuery, hasUserinfo, indexFirstOf, indexFirstOf, indexFirstOf, indexFirstOf, isAbsoluteURI, isAbsPath, isHierPart, isHostname, isIPv4address, isIPv6reference, isNetPath, isOpaquePart, isRegName, isRelativeURI, isRelPath, isServer, normalize, normalize, parseAuthority, parseUriReference, prevalidate, removeFragmentIdentifier, resolvePath, setDefaultDocumentCharset, setDefaultProtocolCharset, setEscapedAuthority, setEscapedFragment, setEscapedPath, setEscapedQuery, setFragment, setPath, setQuery, setRawAuthority, setRawFragment, setRawPath, setRawQuery, setURI, toString, validate, validate
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

URIUtil.Coder

protected URIUtil.Coder()
Deprecated. 
Method Detail

encode

public static char[] encode(String unescapedComponent,
                            BitSet allowed,
                            String charset)
                     throws URIException
Deprecated. use org.apache.commons.codec.net.URLCodec

Escape and encode a given string with allowed characters not to be escaped.

Parameters:
unescapedComponent - an unescaped component
allowed - allowed characters not to be escaped
charset - the charset to encode
Returns:
the escaped and encoded string
Throws:
URIException - if the charset is not supported

decode

public static String decode(char[] escapedComponent,
                            String charset)
                     throws URIException
Deprecated. use org.apache.commons.codec.net.URLCodec

Unescape and decode a given string.

Parameters:
escapedComponent - an being-unescaped component
charset - the charset to decode
Returns:
the escaped and encoded string
Throws:
URIException - if the charset is not supported

verifyEscaped

public static boolean verifyEscaped(char[] original)
Deprecated. 
Verify whether a given string is escaped or not

Parameters:
original - given characters
Returns:
true if the given character array is 7 bit ASCII-compatible.

replace

public static String replace(String original,
                             char[] from,
                             char[] to)
Deprecated. 
Replace from a given character to given character in an array order for a given string.

Parameters:
original - a given string
from - a replacing character array
to - a replaced character array
Returns:
the replaced string

replace

public static String replace(String original,
                             char from,
                             char to)
Deprecated. 
Replace from a given character to given character for a given string.

Parameters:
original - a given string
from - a replacing character array
to - a replaced character array
Returns:
the replaced string


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/URIUtil.html100644 0 0 170757 10661532627 25777 0ustar 0 0 URIUtil (HttpClient 3.1 API)

org.apache.commons.httpclient.util
Class URIUtil

java.lang.Object
  extended by org.apache.commons.httpclient.util.URIUtil

public class URIUtil
extends Object

The URI escape and character encoding and decoding utility. It's compatible with HttpURL rather than URI.

Version:
$Revision: 507321 $ $Date: 2002/03/14 15:14:01
Author:
Sung-Gu

Nested Class Summary
protected static class URIUtil.Coder
          Deprecated. use org.apache.commons.codec.net.URLCodec
 
Field Summary
protected static BitSet empty
           
 
Constructor Summary
URIUtil()
           
 
Method Summary
static String decode(String escaped)
          Unescape and decode a given string regarded as an escaped string with the default protocol charset.
static String decode(String escaped, String charset)
          Unescape and decode a given string regarded as an escaped string.
static String encode(String unescaped, BitSet allowed)
          Escape and encode a given string with allowed characters not to be escaped and the default protocol charset.
static String encode(String unescaped, BitSet allowed, String charset)
          Escape and encode a given string with allowed characters not to be escaped and a given charset.
static String encodeAll(String unescaped)
          Get the all escaped and encoded string with the default protocl charset.
static String encodeAll(String unescaped, String charset)
          Get the all escaped and encoded string with a given charset.
static String encodePath(String unescaped)
          Escape and encode a string regarded as the path component of an URI with the default protocol charset.
static String encodePath(String unescaped, String charset)
          Escape and encode a string regarded as the path component of an URI with a given charset.
static String encodePathQuery(String unescaped)
          Escape and encode a string regarded as the path and query components of an URI with the default protocol charset.
static String encodePathQuery(String unescaped, String charset)
          Escape and encode a string regarded as the path and query components of an URI with a given charset.
static String encodeQuery(String unescaped)
          Escape and encode a string regarded as the query component of an URI with the default protocol charset.
static String encodeQuery(String unescaped, String charset)
          Escape and encode a string regarded as the query component of an URI with a given charset.
static String encodeWithinAuthority(String unescaped)
          Escape and encode a string regarded as within the authority component of an URI with the default protocol charset.
static String encodeWithinAuthority(String unescaped, String charset)
          Escape and encode a string regarded as within the authority component of an URI with a given charset.
static String encodeWithinPath(String unescaped)
          Escape and encode a string regarded as within the path component of an URI with the default protocol charset.
static String encodeWithinPath(String unescaped, String charset)
          Escape and encode a string regarded as within the path component of an URI with a given charset.
static String encodeWithinQuery(String unescaped)
          Escape and encode a string regarded as within the query component of an URI with the default protocol charset.
static String encodeWithinQuery(String unescaped, String charset)
          Escape and encode a string regarded as within the query component of an URI with a given charset.
static String getFromPath(String uri)
          Get the path of an URI and its rest part.
static String getName(String uri)
          Get the basename of an URI.
static String getPath(String uri)
          Get the path of an URI.
static String getPathQuery(String uri)
          Get the path and query of an URI.
static String getQuery(String uri)
          Get the query of an URI.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

empty

protected static final BitSet empty
Constructor Detail

URIUtil

public URIUtil()
Method Detail

getName

public static String getName(String uri)
Get the basename of an URI. It's possibly an empty string.

Parameters:
uri - a string regarded an URI
Returns:
the basename string; an empty string if the path ends with slash

getQuery

public static String getQuery(String uri)
Get the query of an URI.

Parameters:
uri - a string regarded an URI
Returns:
the query string; null if empty or undefined

getPath

public static String getPath(String uri)
Get the path of an URI.

Parameters:
uri - a string regarded an URI
Returns:
the path string

getPathQuery

public static String getPathQuery(String uri)
Get the path and query of an URI.

Parameters:
uri - a string regarded an URI
Returns:
the path and query string

getFromPath

public static String getFromPath(String uri)
Get the path of an URI and its rest part.

Parameters:
uri - a string regarded an URI
Returns:
the string from the path part

encodeAll

public static String encodeAll(String unescaped)
                        throws URIException
Get the all escaped and encoded string with the default protocl charset. It's the same function to use encode(String unescaped, Bitset empty, URI.getDefaultProtocolCharset()).

Parameters:
unescaped - an unescaped string
Returns:
the escaped string
Throws:
URIException - if the default protocol charset is not supported
See Also:
URI.getDefaultProtocolCharset(), encode(java.lang.String, java.util.BitSet)

encodeAll

public static String encodeAll(String unescaped,
                               String charset)
                        throws URIException
Get the all escaped and encoded string with a given charset. It's the same function to use encode(String unescaped, Bitset empty, String charset).

Parameters:
unescaped - an unescaped string
charset - the charset
Returns:
the escaped string
Throws:
URIException - if the charset is not supported
See Also:
encode(java.lang.String, java.util.BitSet)

encodeWithinAuthority

public static String encodeWithinAuthority(String unescaped)
                                    throws URIException
Escape and encode a string regarded as within the authority component of an URI with the default protocol charset. Within the authority component, the characters ";", ":", "@", "?", and "/" are reserved.

Parameters:
unescaped - an unescaped string
Returns:
the escaped string
Throws:
URIException - if the default protocol charset is not supported
See Also:
URI.getDefaultProtocolCharset(), encode(java.lang.String, java.util.BitSet)

encodeWithinAuthority

public static String encodeWithinAuthority(String unescaped,
                                           String charset)
                                    throws URIException
Escape and encode a string regarded as within the authority component of an URI with a given charset. Within the authority component, the characters ";", ":", "@", "?", and "/" are reserved.

Parameters:
unescaped - an unescaped string
charset - the charset
Returns:
the escaped string
Throws:
URIException - if the charset is not supported
See Also:
encode(java.lang.String, java.util.BitSet)

encodePathQuery

public static String encodePathQuery(String unescaped)
                              throws URIException
Escape and encode a string regarded as the path and query components of an URI with the default protocol charset.

Parameters:
unescaped - an unescaped string
Returns:
the escaped string
Throws:
URIException - if the default protocol charset is not supported
See Also:
URI.getDefaultProtocolCharset(), encode(java.lang.String, java.util.BitSet)

encodePathQuery

public static String encodePathQuery(String unescaped,
                                     String charset)
                              throws URIException
Escape and encode a string regarded as the path and query components of an URI with a given charset.

Parameters:
unescaped - an unescaped string
charset - the charset
Returns:
the escaped string
Throws:
URIException - if the charset is not supported
See Also:
encode(java.lang.String, java.util.BitSet)

encodeWithinPath

public static String encodeWithinPath(String unescaped)
                               throws URIException
Escape and encode a string regarded as within the path component of an URI with the default protocol charset. The path may consist of a sequence of path segments separated by a single slash "/" character. Within a path segment, the characters "/", ";", "=", and "?" are reserved.

Parameters:
unescaped - an unescaped string
Returns:
the escaped string
Throws:
URIException - if the default protocol charset is not supported
See Also:
URI.getDefaultProtocolCharset(), encode(java.lang.String, java.util.BitSet)

encodeWithinPath

public static String encodeWithinPath(String unescaped,
                                      String charset)
                               throws URIException
Escape and encode a string regarded as within the path component of an URI with a given charset. The path may consist of a sequence of path segments separated by a single slash "/" character. Within a path segment, the characters "/", ";", "=", and "?" are reserved.

Parameters:
unescaped - an unescaped string
charset - the charset
Returns:
the escaped string
Throws:
URIException - if the charset is not supported
See Also:
encode(java.lang.String, java.util.BitSet)

encodePath

public static String encodePath(String unescaped)
                         throws URIException
Escape and encode a string regarded as the path component of an URI with the default protocol charset.

Parameters:
unescaped - an unescaped string
Returns:
the escaped string
Throws:
URIException - if the default protocol charset is not supported
See Also:
URI.getDefaultProtocolCharset(), encode(java.lang.String, java.util.BitSet)

encodePath

public static String encodePath(String unescaped,
                                String charset)
                         throws URIException
Escape and encode a string regarded as the path component of an URI with a given charset.

Parameters:
unescaped - an unescaped string
charset - the charset
Returns:
the escaped string
Throws:
URIException - if the charset is not supported
See Also:
encode(java.lang.String, java.util.BitSet)

encodeWithinQuery

public static String encodeWithinQuery(String unescaped)
                                throws URIException
Escape and encode a string regarded as within the query component of an URI with the default protocol charset. When a query comprise the name and value pairs, it is used in order to encode each name and value string. The reserved special characters within a query component are being included in encoding the query.

Parameters:
unescaped - an unescaped string
Returns:
the escaped string
Throws:
URIException - if the default protocol charset is not supported
See Also:
URI.getDefaultProtocolCharset(), encode(java.lang.String, java.util.BitSet)

encodeWithinQuery

public static String encodeWithinQuery(String unescaped,
                                       String charset)
                                throws URIException
Escape and encode a string regarded as within the query component of an URI with a given charset. When a query comprise the name and value pairs, it is used in order to encode each name and value string. The reserved special characters within a query component are being included in encoding the query.

Parameters:
unescaped - an unescaped string
charset - the charset
Returns:
the escaped string
Throws:
URIException - if the charset is not supported
See Also:
encode(java.lang.String, java.util.BitSet)

encodeQuery

public static String encodeQuery(String unescaped)
                          throws URIException
Escape and encode a string regarded as the query component of an URI with the default protocol charset. When a query string is not misunderstood the reserved special characters ("&", "=", "+", ",", and "$") within a query component, this method is recommended to use in encoding the whole query.

Parameters:
unescaped - an unescaped string
Returns:
the escaped string
Throws:
URIException - if the default protocol charset is not supported
See Also:
URI.getDefaultProtocolCharset(), encode(java.lang.String, java.util.BitSet)

encodeQuery

public static String encodeQuery(String unescaped,
                                 String charset)
                          throws URIException
Escape and encode a string regarded as the query component of an URI with a given charset. When a query string is not misunderstood the reserved special characters ("&", "=", "+", ",", and "$") within a query component, this method is recommended to use in encoding the whole query.

Parameters:
unescaped - an unescaped string
charset - the charset
Returns:
the escaped string
Throws:
URIException - if the charset is not supported
See Also:
encode(java.lang.String, java.util.BitSet)

encode

public static String encode(String unescaped,
                            BitSet allowed)
                     throws URIException
Escape and encode a given string with allowed characters not to be escaped and the default protocol charset.

Parameters:
unescaped - a string
allowed - allowed characters not to be escaped
Returns:
the escaped string
Throws:
URIException - if the default protocol charset is not supported
See Also:
URI.getDefaultProtocolCharset()

encode

public static String encode(String unescaped,
                            BitSet allowed,
                            String charset)
                     throws URIException
Escape and encode a given string with allowed characters not to be escaped and a given charset.

Parameters:
unescaped - a string
allowed - allowed characters not to be escaped
charset - the charset
Returns:
the escaped string
Throws:
URIException

decode

public static String decode(String escaped)
                     throws URIException
Unescape and decode a given string regarded as an escaped string with the default protocol charset.

Parameters:
escaped - a string
Returns:
the unescaped string
Throws:
URIException - if the string cannot be decoded (invalid)
See Also:
URI.getDefaultProtocolCharset()

decode

public static String decode(String escaped,
                            String charset)
                     throws URIException
Unescape and decode a given string regarded as an escaped string.

Parameters:
escaped - a string
charset - the charset
Returns:
the unescaped string
Throws:
URIException - if the charset is not supported
See Also:
URIUtil.Coder.decode(char[], java.lang.String)


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/DateParseException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/DateParseException.100644 0 0 27202 10661532627 31205 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.DateParseException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.DateParseException

Packages that use DateParseException
org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient. 
 

Uses of DateParseException in org.apache.commons.httpclient.util
 

Methods in org.apache.commons.httpclient.util that throw DateParseException
static Date DateUtil.parseDate(String dateValue)
          Parses a date value.
static Date DateParser.parseDate(String dateValue)
          Deprecated. Parses a date value.
static Date DateUtil.parseDate(String dateValue, Collection dateFormats)
          Parses the date value using the given date formats.
static Date DateParser.parseDate(String dateValue, Collection dateFormats)
          Deprecated. Parses the date value using the given date formats.
static Date DateUtil.parseDate(String dateValue, Collection dateFormats, Date startDate)
          Parses the date value using the given date formats.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/DateParser.html100644 0 0 13726 10661532627 30403 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.DateParser (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.DateParser

No usage of org.apache.commons.httpclient.util.DateParser



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/DateUtil.html100644 0 0 13702 10661532627 30056 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.DateUtil (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.DateUtil

No usage of org.apache.commons.httpclient.util.DateUtil



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/EncodingUtil.html100644 0 0 13752 10661532627 30734 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.EncodingUtil (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.EncodingUtil

No usage of org.apache.commons.httpclient.util.EncodingUtil



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/ExceptionUtil.html100644 0 0 13764 10661532627 31147 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.ExceptionUtil (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.ExceptionUtil

No usage of org.apache.commons.httpclient.util.ExceptionUtil



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/HttpURLConnection.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/HttpURLConnection.h100644 0 0 14034 10661532627 31147 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.HttpURLConnection (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.HttpURLConnection

No usage of org.apache.commons.httpclient.util.HttpURLConnection



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 154 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/IdleConnectionHandler.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/IdleConnectionHandl100644 0 0 14104 10661532627 31241 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.IdleConnectionHandler (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.IdleConnectionHandler

No usage of org.apache.commons.httpclient.util.IdleConnectionHandler



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 162 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/IdleConnectionTimeoutThread.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/IdleConnectionTimeo100644 0 0 14200 10661532627 31265 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.IdleConnectionTimeoutThread (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.IdleConnectionTimeoutThread

No usage of org.apache.commons.httpclient.util.IdleConnectionTimeoutThread



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/LangUtils.html100644 0 0 13714 10661532627 30250 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.LangUtils (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.LangUtils

No usage of org.apache.commons.httpclient.util.LangUtils



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/ParameterFormatter.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/ParameterFormatter.100644 0 0 14046 10661532627 31264 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.ParameterFormatter (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.ParameterFormatter

No usage of org.apache.commons.httpclient.util.ParameterFormatter



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/ParameterParser.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/ParameterParser.htm100644 0 0 14010 10661532627 31255 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.ParameterParser (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.ParameterParser

No usage of org.apache.commons.httpclient.util.ParameterParser



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 171 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/TimeoutController.TimeoutException.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/TimeoutController.T100644 0 0 22050 10661532627 31270 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.TimeoutController.TimeoutException (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.TimeoutController.TimeoutException

Packages that use TimeoutController.TimeoutException
org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient. 
 

Uses of TimeoutController.TimeoutException in org.apache.commons.httpclient.util
 

Methods in org.apache.commons.httpclient.util that throw TimeoutController.TimeoutException
static void TimeoutController.execute(Runnable task, long timeout)
          Executes task in a new deamon Thread and waits for the timeout.
static void TimeoutController.execute(Thread task, long timeout)
          Executes task.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/TimeoutController.htmlcommons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/TimeoutController.h100644 0 0 14034 10661532627 31317 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.TimeoutController (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.TimeoutController

No usage of org.apache.commons.httpclient.util.TimeoutController



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/URIUtil.Coder.html100644 0 0 13764 10661532627 30703 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.URIUtil.Coder (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.URIUtil.Coder

No usage of org.apache.commons.httpclient.util.URIUtil.Coder



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/class-use/URIUtil.html100644 0 0 13670 10661532627 27644 0ustar 0 0 Uses of Class org.apache.commons.httpclient.util.URIUtil (HttpClient 3.1 API)

Uses of Class
org.apache.commons.httpclient.util.URIUtil

No usage of org.apache.commons.httpclient.util.URIUtil



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/package-frame.html100644 0 0 6004 10661532627 27104 0ustar 0 0 org.apache.commons.httpclient.util (HttpClient 3.1 API) org.apache.commons.httpclient.util
Classes 
DateParser
DateUtil
EncodingUtil
ExceptionUtil
HttpURLConnection
IdleConnectionHandler
IdleConnectionTimeoutThread
LangUtils
ParameterFormatter
ParameterParser
TimeoutController
URIUtil
URIUtil.Coder
Exceptions 
DateParseException
TimeoutController.TimeoutException
commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/package-summary.html100644 0 0 26432 10661532627 27536 0ustar 0 0 org.apache.commons.httpclient.util (HttpClient 3.1 API)

Package org.apache.commons.httpclient.util

Provides some utility classes for use by HttpClient.

See:
          Description

Class Summary
DateParser Deprecated. Use DateUtil
DateUtil A utility class for parsing and formatting HTTP dates as used in cookies and other headers.
EncodingUtil The home for utility methods that handle various encoding tasks.
ExceptionUtil The home for utility methods that handle various exception-related tasks.
HttpURLConnection Provides a HttpURLConnection wrapper around HttpClient's HttpMethod.
IdleConnectionHandler A helper class for connection managers to track idle connections.
IdleConnectionTimeoutThread A utility class for periodically closing idle connections.
LangUtils A set of utility methods to help produce consistent Object#equals(Object) and Object#hashCode methods.
ParameterFormatter This formatter produces a textual representation of attribute/value pairs.
ParameterParser A simple parser intended to parse sequences of name/value pairs.
TimeoutController Executes a task with a specified timeout.
URIUtil The URI escape and character encoding and decoding utility.
URIUtil.Coder Deprecated. use org.apache.commons.codec.net.URLCodec
 

Exception Summary
DateParseException An exception to indicate an error parsing a date string.
TimeoutController.TimeoutException Signals that the task timed out.
 

Package org.apache.commons.httpclient.util Description

Provides some utility classes for use by HttpClient.

Since:
2.0


Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/package-tree.html100644 0 0 25540 10661532627 26777 0ustar 0 0 org.apache.commons.httpclient.util Class Hierarchy (HttpClient 3.1 API)

Hierarchy For Package org.apache.commons.httpclient.util

Package Hierarchies:
All Packages

Class Hierarchy



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/org/apache/commons/httpclient/util/package-use.html100644 0 0 16430 10661532627 26632 0ustar 0 0 Uses of Package org.apache.commons.httpclient.util (HttpClient 3.1 API)

Uses of Package
org.apache.commons.httpclient.util

Packages that use org.apache.commons.httpclient.util
org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient. 
 

Classes in org.apache.commons.httpclient.util used by org.apache.commons.httpclient.util
DateParseException
          An exception to indicate an error parsing a date string.
TimeoutController.TimeoutException
          Signals that the task timed out.
 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/overview-frame.html100644 0 0 4366 10661532627 20552 0ustar 0 0 Overview (HttpClient 3.1 API)
All Classes

Packages
org.apache.commons.httpclient
org.apache.commons.httpclient.auth
org.apache.commons.httpclient.cookie
org.apache.commons.httpclient.methods
org.apache.commons.httpclient.methods.multipart
org.apache.commons.httpclient.params
org.apache.commons.httpclient.protocol
org.apache.commons.httpclient.util

  commons-httpclient-3.1/docs/apidocs/overview-summary.html100644 0 0 17255 10661532627 21176 0ustar 0 0 Overview (HttpClient 3.1 API)


HttpClient 3.1 API

Packages
org.apache.commons.httpclient Classes and interfaces supporting the client side of the HTTP protocol.
org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests.
org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with Cookie.
org.apache.commons.httpclient.methods Classes implementing HttpMethod for the base HTTP methods.
org.apache.commons.httpclient.methods.multipart Provides Multipart support classes for the MultipartPostMethod.
org.apache.commons.httpclient.params HttpClient preferences framework.
org.apache.commons.httpclient.protocol Provides protocol specific socket factory handling.
org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient.

 



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/overview-tree.html100644 0 0 124327 10661532627 20457 0ustar 0 0 Class Hierarchy (HttpClient 3.1 API)

Hierarchy For All Packages

Package Hierarchies:
org.apache.commons.httpclient, org.apache.commons.httpclient.auth, org.apache.commons.httpclient.cookie, org.apache.commons.httpclient.methods, org.apache.commons.httpclient.methods.multipart, org.apache.commons.httpclient.params, org.apache.commons.httpclient.protocol, org.apache.commons.httpclient.util

Class Hierarchy

Interface Hierarchy



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/package-list100644 0 0 453 10661532627 17166 0ustar 0 0 org.apache.commons.httpclient org.apache.commons.httpclient.auth org.apache.commons.httpclient.cookie org.apache.commons.httpclient.methods org.apache.commons.httpclient.methods.multipart org.apache.commons.httpclient.params org.apache.commons.httpclient.protocol org.apache.commons.httpclient.util commons-httpclient-3.1/docs/apidocs/resources/inherit.gif100644 0 0 71 10661532627 21016 0ustar 0 0 GIF89a, DrjԐ;߀Q@N;commons-httpclient-3.1/docs/apidocs/serialized-form.html100644 0 0 124354 10661532627 20750 0ustar 0 0 Serialized Form (HttpClient 3.1 API)

Serialized Form


Package org.apache.commons.httpclient

Class org.apache.commons.httpclient.CircularRedirectException extends RedirectException implements Serializable

Class org.apache.commons.httpclient.ConnectionPoolTimeoutException extends ConnectTimeoutException implements Serializable

Class org.apache.commons.httpclient.ConnectTimeoutException extends InterruptedIOException implements Serializable

Class org.apache.commons.httpclient.Cookie extends NameValuePair implements Serializable

Serialized Fields

cookieComment

String cookieComment
Comment attribute.


cookieDomain

String cookieDomain
Domain attribute.


cookieExpiryDate

Date cookieExpiryDate
Expiration Date.


cookiePath

String cookiePath
Path attribute.


isSecure

boolean isSecure
My secure flag.


hasPathAttribute

boolean hasPathAttribute
Specifies if the set-cookie header included a Path attribute for this cookie


hasDomainAttribute

boolean hasDomainAttribute
Specifies if the set-cookie header included a Domain attribute for this cookie


cookieVersion

int cookieVersion
The version of the cookie specification I was created from.

Class org.apache.commons.httpclient.Header extends NameValuePair implements Serializable

Serialized Fields

isAutogenerated

boolean isAutogenerated
Autogenerated header flag.

Class org.apache.commons.httpclient.HeaderElement extends NameValuePair implements Serializable

Serialized Fields

parameters

NameValuePair[] parameters
My parameters, if any.

Class org.apache.commons.httpclient.HttpClientError extends Error implements Serializable

Class org.apache.commons.httpclient.HttpContentTooLargeException extends HttpException implements Serializable

Serialized Fields

maxlen

int maxlen

Class org.apache.commons.httpclient.HttpException extends IOException implements Serializable

Serialized Fields

reason

String reason
Deprecated. HttpClient no longer uses this field for itself. It is only provided for compatibility with existing clients.
A "reason" string provided for compatibility with older clients.


reasonCode

int reasonCode
Deprecated. HttpClient no longer uses this field for itself. It is only provided for compatibility with existing clients.
Reason code for compatibility with older clients.


cause

Throwable cause
The original Throwable representing the cause of this error

Class org.apache.commons.httpclient.HttpRecoverableException extends HttpException implements Serializable

Class org.apache.commons.httpclient.HttpsURL extends HttpURL implements Serializable

serialVersionUID: 887844277028676648L

Class org.apache.commons.httpclient.HttpURL extends URI implements Serializable

serialVersionUID: -7158031098595039459L

Class org.apache.commons.httpclient.InvalidRedirectLocationException extends RedirectException implements Serializable

Serialized Fields

location

String location

Class org.apache.commons.httpclient.NameValuePair extends Object implements Serializable

Serialized Fields

name

String name
Name.


value

String value
Value.

Class org.apache.commons.httpclient.NoHttpResponseException extends IOException implements Serializable

Class org.apache.commons.httpclient.ProtocolException extends HttpException implements Serializable

Class org.apache.commons.httpclient.RedirectException extends ProtocolException implements Serializable

Class org.apache.commons.httpclient.URI extends Object implements Serializable

serialVersionUID: 604752400577948726L

Serialization Methods

readObject

private void readObject(ObjectInputStream ois)
                 throws ClassNotFoundException,
                        IOException
Read a URI.

Throws:
ClassNotFoundException - If one of the classes specified in the input stream cannot be found.
IOException - If an IO problem occurs.

writeObject

private void writeObject(ObjectOutputStream oos)
                  throws IOException
Write the content of this URI.

Throws:
IOException - If an IO problem occurs.
Serialized Fields

hash

int hash
Cache the hash code for this URI.


_uri

char[] _uri
This Uniform Resource Identifier (URI). The URI is always in an "escaped" form, since escaping or unescaping a completed URI might change its semantics.


protocolCharset

String protocolCharset
The charset of the protocol used by this URI instance.


_scheme

char[] _scheme
The scheme.


_opaque

char[] _opaque
The opaque.


_authority

char[] _authority
The authority.


_userinfo

char[] _userinfo
The userinfo.


_host

char[] _host
The host.


_port

int _port
The port.


_path

char[] _path
The path.


_query

char[] _query
The query.


_fragment

char[] _fragment
The fragment.


_is_hier_part

boolean _is_hier_part

_is_opaque_part

boolean _is_opaque_part

_is_net_path

boolean _is_net_path

_is_abs_path

boolean _is_abs_path

_is_rel_path

boolean _is_rel_path

_is_reg_name

boolean _is_reg_name

_is_server

boolean _is_server

_is_hostname

boolean _is_hostname

_is_IPv4address

boolean _is_IPv4address

_is_IPv6reference

boolean _is_IPv6reference

Class org.apache.commons.httpclient.URI.DefaultCharsetChanged extends RuntimeException implements Serializable

Serialized Fields

reasonCode

int reasonCode
The reason code.


reason

String reason
The reason message.

Class org.apache.commons.httpclient.URIException extends HttpException implements Serializable

Serialized Fields

reasonCode

int reasonCode
The reason code.


reason

String reason
The reason message.


Package org.apache.commons.httpclient.auth

Class org.apache.commons.httpclient.auth.AuthChallengeException extends AuthenticationException implements Serializable

Class org.apache.commons.httpclient.auth.AuthenticationException extends ProtocolException implements Serializable

Class org.apache.commons.httpclient.auth.CredentialsNotAvailableException extends AuthenticationException implements Serializable

Class org.apache.commons.httpclient.auth.InvalidCredentialsException extends AuthenticationException implements Serializable

Class org.apache.commons.httpclient.auth.MalformedChallengeException extends ProtocolException implements Serializable


Package org.apache.commons.httpclient.cookie

Class org.apache.commons.httpclient.cookie.Cookie2 extends Cookie implements Serializable

Serialized Fields

cookieCommentURL

String cookieCommentURL
Comment URL attribute


cookiePorts

int[] cookiePorts
Port attribute.


discard

boolean discard
Discard attribute.


hasPortAttribute

boolean hasPortAttribute
Indicates if the set-cookie2 header included a Port attribute for this cookie


isPortAttributeBlank

boolean isPortAttributeBlank
Indicates if the set-cookie2 header's Port attribute did not have any value.


hasVersionAttribute

boolean hasVersionAttribute
Indicates if the set-cookie2 header included a Version attribute

Class org.apache.commons.httpclient.cookie.MalformedCookieException extends ProtocolException implements Serializable


Package org.apache.commons.httpclient.params

Class org.apache.commons.httpclient.params.DefaultHttpParams extends Object implements Serializable

Serialized Fields

defaults

HttpParams defaults
The set of default values to defer to


parameters

HashMap<K,V> parameters
Hash map of HTTP parameters that this collection contains

Class org.apache.commons.httpclient.params.HostParams extends DefaultHttpParams implements Serializable

Class org.apache.commons.httpclient.params.HttpClientParams extends HttpMethodParams implements Serializable

Class org.apache.commons.httpclient.params.HttpConnectionManagerParams extends HttpConnectionParams implements Serializable

Class org.apache.commons.httpclient.params.HttpConnectionParams extends DefaultHttpParams implements Serializable

Class org.apache.commons.httpclient.params.HttpMethodParams extends DefaultHttpParams implements Serializable


Package org.apache.commons.httpclient.util

Class org.apache.commons.httpclient.util.DateParseException extends Exception implements Serializable

Class org.apache.commons.httpclient.util.TimeoutController.TimeoutException extends Exception implements Serializable

Class org.apache.commons.httpclient.util.URIUtil.Coder extends URI implements Serializable



Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/apidocs/stylesheet.css100644 0 0 2772 10661532631 17623 0ustar 0 0 /* Javadoc style sheet */ /* Define colors, fonts and other style attributes here to override the defaults */ /* Page background color */ body { background-color: #FFFFFF } a:link, a:visited { color: blue; } a:active, a:hover, #leftcol a:active, #leftcol a:hover { color: #f30 !important; } a:link.selfref, a:visited.selfref { color: #555 !important; } .a td { background: #ddd; color: #000; } /* Table colors */ .TableHeadingColor { background: #036; color:#FFFFFF } /* Dark blue */ .TableSubHeadingColor { background: #bbb; color:#fff } /* Dark grey */ .TableRowColor { background: #efefef } /* White */ /* Font used in left-hand frame lists */ .FrameTitleFont { font-size: normal; font-family: normal; color:#000000 } .FrameHeadingFont { font-size: normal; font-family: normal; color:#000000 } .FrameItemFont { font-size: normal; font-family: normal; color:#000000 } /* Example of smaller, sans-serif font in frames */ /* .FrameItemFont { font-size: 10pt; font-family: Helvetica, Arial, sans-serif } */ /* Navigation bar fonts and colors */ .NavBarCell1 { background-color:#ddd;}/* Light mauve */ .NavBarCell1Rev { background-color:#888;}/* Dark Blue */ .NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;} .NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;} .NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} .NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} commons-httpclient-3.1/docs/authentication.html100644 0 0 46532 10661532631 17225 0ustar 0 0 HttpClient - HttpClient Authentication Guide

Introduction

HttpClient supports three different types of http authentication schemes: Basic, Digest and NTLM. These can be used to authenticate with http servers or proxies.

Server Authentication

HttpClient handles authenticating with servers almost transparently, the only thing a developer must do is actually provide the login credentials. These credentials are stored in the HttpState instance and can be set or retrieved using the setCredentials(AuthScope authscope, Credentials cred) and getCredentials(AuthScope authscope) methods.

The automatic authorization built in to HttpClient can be disabled with the method setDoAuthentication(boolean doAuthentication) in the HttpMethod class. The change only affects that method instance.

Preemptive Authentication

Preemptive authentication can be enabled within HttpClient. In this mode HttpClient will send the basic authentication response even before the server gives an unauthorized response in certain situations, thus reducing the overhead of making the connection. To enable this use the following:

client.getParams().setAuthenticationPreemptive(true);

Preemptive authentication mode also requires default Credentials to be set for the target or proxy host against which preemptive authentication is to be attempted. Failure to provide default credentials will render the preemptive authentication mode ineffective.

Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(new AuthScope("myhost", 80, AuthScope.ANY_REALM), defaultcreds);

The preemptive authentication in HttpClient conforms to rfc2617:

A client SHOULD assume that all paths at or deeper than the depth of the last symbolic element in the path field of the Request-URI also are within the protection space specified by the Basic realm value of the current challenge. A client MAY preemptively send the corresponding Authorization header with requests for resources in that space without receipt of another challenge from the server. Similarly, when a client sends a request to a proxy, it may reuse a userid and password in the Proxy-Authorization header field without receiving another challenge from the proxy server.

Security aspects of server authentication

Use default credentials with caution when developing applications that may need to communicate with untrusted web sites or web applications. When preemptive authentication is activated or credentials are not explicitly given for a specific authentication realm and host HttpClient will use default credentials to try to authenticate with the target site. If you want to avoid sending sensitive credentials to an untrusted site, narrow the credentials scope as much as possible: always specify the host and, when known, the realm the credentials are intended for.

Setting credentials with AuthScope.ANY authentication scope (null value for host and/or realm) is highly discouraged in production applications. Doing this will result in the credentials being sent for all authentication attempts (all requests in the case of preemptive authentication). Use of this setting should be limited to debugging only.

// To be avoided unless in debug mode
Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(AuthScope.ANY, defaultcreds);

Proxy Authentication

Proxy authentication in HttpClient is almost identical to server authentication with the exception that the credentials for each are stored independantly. So for proxy authentication you must use setProxyCredentials(AuthScope authscope, Credentials cred) and getProxyCredentials(AuthScope authscope).

Authentication Schemes

The following authentication schemes are supported by HttpClient.

Basic

Basic authentication is the original and most compatible authentication scheme for HTTP. Unfortunately, it is also the least secure as it sends the username and password unencrypted to the server. Basic authentication requires an instance of UsernamePasswordCredentials (which NTCredentials extends) to be available, either for the specific realm specified by the server or as the default credentials.

Digest

Digest authentication was added in the HTTP 1.1 protocol and while not being as widely supported as Basic authentication there is a great deal of support for it. Digest authentication is significantly more secure than basic authentication as it never transfers the actual password across the network, but instead uses it to encrypt a "nonce" value sent from the server.

Digest authentication requires an instance of UsernamePasswordCredentials (which NTCredentials extends) to be available either for the specific realm specified by the server or as the default credentials.

NTLM

NTLM is the most complex of the authentication protocols supported by HttpClient. It is a proprietary protocol designed by Microsoft with no publicly available specification. Early version of NTLM were less secure than Digest authentication due to faults in the design, however these were fixed in a service pack for Windows NT 4 and the protocol is now considered more secure than Digest authentication.

NTLM authentication requires an instance of NTCredentials be available for the domain name of the server or the default credentials. Note that since NTLM does not use the notion of realms HttpClient uses the domain name of the server as the name of the realm. Also note that the username provided to the NTCredentials should not be prefixed with the domain - ie: "adrian" is correct whereas "DOMAIN\adrian" is not correct.

There are some significant differences in the way that NTLM works compared with basic and digest authentication. These differences are generally handled by HttpClient, however having an understanding of these differences can help avoid problems when using NTLM authentication.

  1. NTLM authentication works almost exactly the same as any other form of authentication in terms of the HttpClient API. The only difference is that you need to supply 'NTCredentials' instead of 'UsernamePasswordCredentials' (NTCredentials actually extends UsernamePasswordCredentials so you can use NTCredentials right throughout your application if need be).
  2. The realm for NTLM authentication is the domain name of the computer being connected to, this can be troublesome as servers often have multiple domain names that refer to them. Only the domain name that HttpClient connects to (as specified by the HostConfiguration) is used to look up the credentials. It is generally advised that while initially testing NTLM authentication, you pass the realm in as null which is used as the default.
  3. NTLM authenticates a connection and not a request, so you need to authenticate every time a new connection is made and keeping the connection open during authentication is vital. Due to this, NTLM cannot be used to authenticate with both a proxy and the server, nor can NTLM be used with HTTP 1.0 connections or servers that do not support HTTP keep-alives.

For a detailed explanation of how NTLM authentication works, please see http://davenport.sourceforge.net/ntlm.html.

Alternate authentication

Some servers support multiple schemes for authenticating users. Given that only one scheme may be used at a time for authenticating, HttpClient must choose which scheme to use. To accompish this, HttpClient uses an order of preference to select the correct authentication scheme. By default this order is: NTLM, Digest, Basic.

In certain cases it may be desirable to change this default. The default preference of the authentication schemes may be altered using the 'http.auth.scheme-priority' parameter. The parameter value is expected to be a List of Strings containing names of authentication schemes in descending order of preference.

HttpClient client = new HttpClient();
List authPrefs = new ArrayList(2);
authPrefs.add(AuthPolicy.DIGEST);
authPrefs.add(AuthPolicy.BASIC);
// This will exclude the NTLM authentication scheme
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

Custom authentication scheme

HttpClient natively supports basic, digest, and NTLM authentication. It also contains a mechanism to plugin additional custom authentication schemes via the AuthScheme interface. The following steps are required to make use of a custom authentication scheme.

  1. Implement the AuthScheme interface.
  2. Register the custom AuthScheme with AuthPolicy.registerAuthScheme().
  3. Include the custom AuthScheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference (see the Alternate authentication section).

Examples

There are a number of authentication examples in the example directory, including:

Known limitations and problems

  1. Authentication schemes that rely on persistent connection state do not work on Sun's JVMs below 1.4 if SSL is used

    For details please refer to the Known limitations and problems section of the SSL Guide

    Workaround: Disable stale connection check or upgrade to Java 1.4 or above.

  2. Cannot authenticate with Microsoft IIS using NTLM authentication scheme

    NT Lan Manager (NTLM) authentication is a proprietary, closed challenge/response authentication protocol for Microsoft Windows. Only some details about NTLM protocol are available through reverse engineering. HttpClient provides limited support for what is known as NTLMv1, the early version of the NTLM protocol. HttpClient does not support NTLMv2 at all.

    Workaround: Disable NTLMv2. For details refer to this Microsoft Support Article

Troubleshooting

Some authentication schemes may use cryptographic algorithms. It is recommended to include the Java Cryptography Extension in your runtime environment prior to JDK 1.4. Also note that you must register the JCE implementation manually as HttpClient will not do so automatically. For instance to register the Sun JCE implementation, you should execute the following code before attempting to use HttpClient.

String secProviderName = "com.sun.crypto.provider.SunJCE");
java.security.Provider secProvider = 
    (java.security.Provider)Class.forName(secProviderName).newInstance();
Security.addProvider(secProvider);
	  

commons-httpclient-3.1/docs/changelog-report.html100644 0 0 77537 10661532631 17457 0ustar 0 0 HttpClient - Changelog Report

Changelog Report

Total number of change sets: 1

Changes between 2007-07-19 and 2007-08-19

Total Commits: 16

Total Number of Files Changed: 39

Date Author File/Message
2007-08-18 10:49:31 Oleg Kalnichevski

/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1 (from /jakarta/httpcomponents/oac.hc3x/trunk:567247) v567248

HttpClient 3.1 final release
2007-08-18 10:47:06 Oleg Kalnichevski

/jakarta/httpcomponents/oac.hc3x/trunk/project.xml v567246

Fixed web site url
2007-08-17 15:02:59 Oleg Kalnichevski

/jakarta/httpcomponents/oac.hc3x/trunk/src/resources/META-INF/NOTICE.txt v567049

/jakarta/httpcomponents/oac.hc3x/trunk/src/resources/META-INF/README.txt v567049

Changed eol-style from native to CRLF
2007-08-15 16:39:27 Oleg Kalnichevski

/jakarta/httpcomponents/oac.hc3x/trunk/NOTICE.txt v566195

/jakarta/httpcomponents/oac.hc3x/trunk/README.txt v566195

/jakarta/httpcomponents/oac.hc3x/trunk/project.xml v566195

/jakarta/httpcomponents/oac.hc3x/trunk/src/resources v566195

/jakarta/httpcomponents/oac.hc3x/trunk/src/resources/META-INF v566195

/jakarta/httpcomponents/oac.hc3x/trunk/src/resources/META-INF/NOTICE.txt v566195

/jakarta/httpcomponents/oac.hc3x/trunk/src/resources/META-INF/README.txt v566195

* Fixed NOTICE.txt * Added README.txt and NOTICE.txt to META-INF
2007-08-15 12:44:27 Oleg Kalnichevski

/jakarta/httpcomponents/oac.hc3x/trunk/project.xml v566098

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/downloads.xml v566098

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/news.xml v566098

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/status.xml v566098

Updated web site for release 3.1 final; fixed download links
2007-08-15 10:34:30 Oleg Kalnichevski

/jakarta/httpcomponents/oac.hc3x/trunk/build.xml v566065

/jakarta/httpcomponents/oac.hc3x/trunk/project.xml v566065

/jakarta/httpcomponents/oac.hc3x/trunk/release_notes.txt v566065

/jakarta/httpcomponents/oac.hc3x/trunk/src/java/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.java v566065

Updated release notes and project files for release 3.1 final
2007-08-11 22:51:47 Oleg Kalnichevski

/jakarta/httpcomponents/oac.hc3x/trunk/release_notes.txt v564973

/jakarta/httpcomponents/oac.hc3x/trunk/src/java/org/apache/commons/httpclient/URI.java v564973

/jakarta/httpcomponents/oac.hc3x/trunk/src/test/org/apache/commons/httpclient/TestURI.java v564973

HTTPCLIENT-679: Fixed RFC3986 compliance problem in URI absolutization code Contributed by Jeff Dalton <jeffdalton104 at hotmail dot> Reviewed by Oleg Kalnichevski
2007-08-11 14:27:18 rolandw

/jakarta/httpcomponents/oac.hc3x/trunk/release_notes.txt v564906

/jakarta/httpcomponents/oac.hc3x/trunk/src/java/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.java v564906

HTTPCLIENT-675 and HTTPCLIENT-676
2007-08-11 14:03:44 rolandw

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/developerguide.xml v564901

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/downloads.xml v564901

updated download links, removed link to Jakarta mission
2007-08-11 11:35:55 rolandw

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/index.xml v564883

added History section to index.html, to explain the Jakarta and Commons parts of the project name
2007-08-11 10:53:32 rolandw

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/navigation.xml v564873

removed the Commons section of the navigation
2007-08-11 10:34:42 rolandw

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/developerguide.xml v564860

removed reference to /commons/volunteering
2007-08-11 10:31:12 rolandw

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/logging.xml v564858

updated links to Commons Logging and the dev mailing list
2007-08-11 10:23:12 rolandw

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/features.xml v564855

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/index.xml v564855

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/overview.xml v564855

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/proposal.xml v564855

/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/status.xml v564855

replaced commons-dev@j.a.o with httpcomponents-dev@j.a.o
2007-08-11 10:00:44 rolandw

/jakarta/httpcomponents/oac.hc3x/trunk/project.properties v564851

/jakarta/httpcomponents/oac.hc3x/trunk/project.xml v564851

updated some Commons and HttpClient URLs
2007-07-30 21:41:17 rolandw

/jakarta/httpcomponents/oac.hc3x/trunk/release_notes.txt v561099

/jakarta/httpcomponents/oac.hc3x/trunk/src/java/org/apache/commons/httpclient/HttpState.java v561099

HTTPCLIENT-665

commons-httpclient-3.1/docs/charencodings.html100644 0 0 16573 10661532631 17017 0ustar 0 0 HttpClient - Character Encodings

Introduction

This document provides an overview of how HttpClient handles character encodings and how to use HttpClient in an encoding safe way. There are three main sections: HTTP Headers, Request/Response Body and URLs.

HTTP Headers

The headers of a HTTP request or response must be in US-ASCII format. It is not possible to use non US-ASCII characters in the header of a request or response. Generally this is not an issue however, because the HTTP headers are designed to facilite the transfer of data rather than to actually transfer the data itself.

One exception however are cookies. Since cookies are transfered as HTTP Headers they are confined to the US-ASCII character set. See the Cookie Guide for more information.

Request/Response Body

The request or response body can be any encoding, but by default is ISO-8859-1. The encoding may be specified in the Content-Type header, for example:

Content-Type: text/html; charset=UTF-8

In this case the application should be careful to use UTF-8 encoding when converting the body to a String or some characters may be corrupt. You can set the content type header for a request with the addRequestHeader method in each method and retrieve the encoding for the response body with the getResponseCharSet method.

If the response is known to be a String, you can use the getResponseBodyAsString method which will automatically use the encoding specified in the Content-Type header or ISO-8859-1 if no charset is specified.

Note that some document types, such as HTML and XML allow the author to specify the content type of the file. In this case, you should consult the appropriate standards regarding how to resovle any conflicts in the reported charsets.

URLs

The standard for URLs (RFC1738) explictly states that URLs may only contain graphic printable characters of the US-ASCII coded character set and is defined in terms of octets. The octets 80-FF hexadecimal are not used in US-ASCII and the octets OO-1F hexadecimal represent control characters; characters in these ranges must be encoded.

Characters which cannot be represented by an 8-bit ASCII code, can not be used in an URL as there is no way to reliably encode them (the encoding scheme for URLs is based off of octets). Despite this, some servers do support varying means of encoding double byte characters in URLs, the most common technique seems to be to use UTF-8 encoding and encode each octet separately even if a pair of octets represents one character. This however, is not specified by the standard and is highly prone to error, so it is recommended that URLs be restricted to the 8-bit ASCII range.


commons-httpclient-3.1/docs/cookies.html100644 0 0 25241 10661532631 15634 0ustar 0 0 HttpClient - HttpClient Cookie Guide

Introduction

HttpClient supports automatic management of cookies, including allowing the server to set cookies and automatically return them to the server when required. It is also possible to manually set cookies to be sent to the server.

Unfortunately, there are several at times conflicting standards for handling Cookies: the Netscape Cookie draft, RFC2109, RFC2965 and a large number of vendor specific implementations that are compliant with neither specification. To deal with this, HttpClient provides policy driven cookie management. This guide will explain how to use the different cookie specifications and identify some of the common problems people have when using Cookies and HttpClient.

Available Specifications

The following cookie specifications are supported by HttpClient.

Netscape Draft

The Netscape draft is the original cookie specification which formed the basis for RFC2109. Despite this it has some significant differences with RFC2109 and thus may be required for compatibility with some servers.

The Netscape cookie draft is available at http://wp.netscape.com/newsref/std/cookie_spec.html

RFC2109

RFC2109 is the first official cookie specification released by the W3C. Theoretically, all servers that handle version 1 cookies should use this specification and as such this specification is used by default within HttpClient.

Unfortunately, many servers either incorrectly implement this standard or are still using the Netscape draft so occasionally this specification is too strict. If this is the case, you should switch to the compatibility specification as described below.

RFC2109 is available at http://www.w3.org/Protocols/rfc2109/rfc2109.txt

RFC2109 is the default cookie policy used by HttpClient.

Browser Compatibility

The compatibility specification is designed to be compatible with as many different servers as possible even if they are not completely standards compliant. If you are encountering problems with parsing cookies, you should probably try using this specification.

There are many web sites with badly written CGI scripts that only work when all cookies are put into one request header. It is advisable to set http.protocol.single-cookie-header parameter to true for maximum compatibility.

Ignore Cookies

This cookie specification ignores all cookies. It should be used to keep HttpClient from accepting and sending cookies.

Unsupported Specifications

The following cookie specifications are not presently supported by HttpClient.

RFC2965

RFC2965 defines cookie version 2 and attempts to address the shortcomings of the RFC2109 regarding cookie version 1. RFC2965 is intended to eventually supersede RFC2109.

Currently HttpClient does not implement this specification. Support for version 2 cookies will be added in the future

RFC2965 is available at http://www.w3.org/Protocols/rfc2965/rfc2965.txt

Specifying the Specification

There are two ways to specify which cookie specification should be used, either for each HttpMethod instance using the HttpMethodParams, or by setting the default value on CookiePolicy.

Per HttpMethod

In most cases, the best way to specify the cookie spec to use is the setCookiePolicy(String policy) method on HttpMethodParams. The value of policy must be one of the values registered with CookiePolicy.registerCookieSpec().

        HttpMethod method = new GetMethod();
        method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
        

Manual handling of cookies

The cookie management API of HttpClient can co-exist with the manual cookie handling. One can manually set request Cookie headers or process response Set-Cookie headers in addition or instead of the automatic cookie management

        HttpMethod method = new GetMethod();
        method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        method.setRequestHeader("Cookie", "special-cookie=value");
        

Common Problems

The most common problems encountered with parsing cookies is due to non-compliant servers. In these cases, switching to the compatibility cookie specification usually solves the problem.

Encoding Issues

Since cookies are transfered as HTTP Headers they are confined to the US-ASCII character set. Other characters will be lost or mangeled. Cookies are typically set and read by the same server, so a custom scheme for escaping non-ASCII characters can be used, for instance the well-established URL encoding scheme. If cookies are used to transfer data between server and client both parties must agree on the escaping scheme used in a custom way. The HttpClient cookie implementation provides no special means to handle non-ASCII characters nor does it issue warnings.


commons-httpclient-3.1/docs/dependencies.html100644 0 0 15732 10661532631 16632 0ustar 0 0 HttpClient - Dependencies

Dependencies

The following is a list of dependencies for this project. These dependencies are required to compile and run the application:

Artifact ID Type Version Scope URL Comment
commons-codec jar 1.2 http://commons.apache.org/codec/
commons-logging jar 1.0.4 http://commons.apache.org/logging/
junit jar 3.8.1 test http://www.junit.org/

commons-httpclient-3.1/docs/developer-activity-report.html100644 0 0 12630 10661532631 21326 0ustar 0 0 HttpClient - Developer Activity Analysis

Activity by Developer

Changes between 2007-07-19 and 2007-08-19

Timeframe: 30days

Total Commits: 16

Total Number of Files Changed: 39

Name Number of Commits Number of files changed
Oleg Kalnichevski 7 22

commons-httpclient-3.1/docs/developerguide.html100644 0 0 11525 10661532631 17203 0ustar 0 0 HttpClient - HttpClient Developer Guide

Developer Guide

This section contains supplementary information relating to the development of HttpClient. You should be sure to read the general jakarta documentation. These pages describe how to contribute to any Jakarta project and will not only help you contribute, but give you a grounding in what Apache and the Jakarta project is all about.

Some other links that may be of interest:


commons-httpclient-3.1/docs/development-process.html100644 0 0 7550 10661532631 20161 0ustar 0 0 HttpClient - Development Process

commons-httpclient-3.1/docs/downloads.html100644 0 0 14613 10661532631 16173 0ustar 0 0 HttpClient - HttpClient Downloads

Downloads

The following releases are available for download:

The Subversion repository for HttpClient can be browsed online.

The best way to get the HttpClient source is to checkout directly from our public Subversion repository. Instructions are available here.

If you are using Maven for your project, you can create a dependency in your project.xml with one of the following:

3.1

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
    <url>http://jakarta.apache.org/commons/httpclient/</url>
</dependency>
         

3.0.1

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.0.1</version>
    <url>http://jakarta.apache.org/commons/httpclient/</url>
</dependency>
         

There are also other jar versions available. You can check HttpClient on ibiblio for exactly what is available.


commons-httpclient-3.1/docs/exception-handling.html100644 0 0 51561 10661532631 17764 0ustar 0 0 HttpClient - HttpClient exception handling guide

Exception handling

There are two main type of exceptions that the user of HttpClient may encounter when executing HTTP methods:

  1. transport exceptions
  2. protocol exceptions
Not all of these exceptions will be propagated to the user in regular HttpClient use. Exceptions handled internally by HttpClient are marked below as INTERNAL.

Transport exceptions

Transport exceptions are those caused by input/output failures such as an unreliable connection or an inability to complete the execution of an HTTP method within the given time constraint (socket timeout). Generally transport exceptions are non-fatal and may be recovered from by retrying the failed method. However, special care must be taken when recovering from exceptions in non-idempotent methods (refer to HTTP transport safety for details).

java.io.IOException

Generic transport exceptions in HttpClient are represented by the standard Java java.io.IOException class or its sub classes such as java.net.SocketException and java.net.InterruptedIOException.

In addition to standard input/output exception classes HttpClient defines several custom transport exceptions that convey HttpClient specific information.

org.apache.commons.httpclient.NoHttpResponseException

java.io.IOException
  +- org.apache.commons.httpclient.NoHttpResponseException

In some circumstances, usually when under heavy load, the web server may be able to receive requests but unable to process them. A lack of sufficient resources like worker threads is a good example. This may cause the server to drop the connection to the client without giving any response. HttpClient throws NoHttpResponseException when it encounters such a condition. In most cases it is safe to retry a method that failed with NoHttpResponseException.

org.apache.commons.httpclient.ConnectTimeoutException

java.io.IOException
  +- java.io.InterruptedIOException
    +- org.apache.commons.httpclient.ConnectTimeoutException

This exception signals that HttpClient is unable to establish a connection with the target server or proxy server within the given period of time.

org.apache.commons.httpclient.ConnectionPoolTimeoutException

java.io.IOException
  +- java.io.InterruptedIOException
    +- org.apache.commons.httpclient.ConnectTimeoutException
      +- org.apache.commons.httpclient.ConnectionPoolTimeoutException

This exception can only occur when using the multithreaded connection manager. The exception signals that the connection manager fails to obtain a free connection from the connection pool within the given period of time.

org.apache.commons.httpclient.HttpRecoverableException

java.io.IOException
  +- org.apache.commons.httpclient.HttpException
    +- org.apache.commons.httpclient.HttpRecoverableException

Deprecated and no longer thrown any of the standard HttpClient classes.

Protocol exceptions

Protocol exceptions generally indicate logical errors caused by a mismatch between the client and the server (web server or proxy server) in their interpretation of the HTTP specification. Usually protocol exceptions cannot be recovered from without making adjustments to either the client request or the server. Some aspects of the HTTP specification allow for different, at times conflicting, interpretations. HttpClient can be configured to support different degrees of HTTP specification compliance varying from very lenient to very strict.

org.apache.commons.httpclient.HttpException

java.io.IOException
  +- org.apache.commons.httpclient.HttpException

HttpException represents an abstract logical error in HttpClient. Generally this kind of exception cannot be automatically recovered from.

org.apache.commons.httpclient.ProtocolException

java.io.IOException
  +- org.apache.commons.httpclient.HttpException
    +- org.apache.commons.httpclient.ProtocolException

ProtocolException signals a violation of the HTTP specification. It is important to note that HTTP proxies and HTTP servers can have different level of HTTP specification compliance. It may be possible to recover from some HTTP protocol exceptions by configuring HttpClient to be more lenient about non-fatal protocol violations.

org.apache.commons.httpclient.auth.MalformedChallengeException

java.io.IOException
  +- org.apache.commons.httpclient.HttpException
    +- org.apache.commons.httpclient.ProtocolException
      +- org.apache.commons.httpclient.auth.MalformedChallengeException

INTERNAL

MalformedChallengeException signals that an authentication challenge is in some way invalid or illegal in the given authentication context.

org.apache.commons.httpclient.auth.AuthenticationException

java.io.IOException
  +- org.apache.commons.httpclient.HttpException
    +- org.apache.commons.httpclient.ProtocolException
      +- org.apache.commons.httpclient.auth.AuthenticationException

INTERNAL

AuthenticationException signals a failure in the authentication process. Usually authentication exceptions are handled internally when executing HTTP methods and are not propagated to the caller.

org.apache.commons.httpclient.auth.AuthChallengeException

java.io.IOException
  +- org.apache.commons.httpclient.HttpException
    +- org.apache.commons.httpclient.ProtocolException
      +- org.apache.commons.httpclient.auth.AuthenticationException
        +- org.apache.commons.httpclient.auth.AuthChallengeException

INTERNAL

AuthenticationException is thrown when HttpClient is unable to respond to any of the authentication challenges sent by the server.

org.apache.commons.httpclient.auth.CredentialsNotAvailableException

java.io.IOException
  +- org.apache.commons.httpclient.HttpException
    +- org.apache.commons.httpclient.ProtocolException
      +- org.apache.commons.httpclient.auth.AuthenticationException
        +- org.apache.commons.httpclient.auth.CredentialsNotAvailableException

INTERNAL

CredentialsNotAvailableException indicates that credentials required to respond to the authentication challenge are not available.

org.apache.commons.httpclient.auth.InvalidCredentialsException

java.io.IOException
  +- org.apache.commons.httpclient.HttpException
    +- org.apache.commons.httpclient.ProtocolException
      +- org.apache.commons.httpclient.auth.AuthenticationException
        +- org.apache.commons.httpclient.auth.InvalidCredentialsException

INTERNAL

InvalidCredentialsException indicates that the credentials used to respond to the authentication challenge have been rejected by the server.

org.apache.commons.httpclient.cookie.MalformedCookieException

java.io.IOException
  +- org.apache.commons.httpclient.HttpException
    +- org.apache.commons.httpclient.ProtocolException
      +- org.apache.commons.httpclient.cookie.MalformedCookieException

INTERNAL

MalformedCookieException signals that the cookie is in some way invalid or illegal in the given HTTP session context.

There are several cookie specifications that are often incompatible. Thus the validity of a cookie is established within a context of a specific cookie specification used to parse and validate the cookie header(s) sent by the server. If the application needs to process cookies differently from the commonly used cookie specifications, it may choose to provide a custom cookie policy or extend the existing one. Please see cookies for more details.

org.apache.commons.httpclient.RedirectException

java.io.IOException
  +- org.apache.commons.httpclient.HttpException
    +- org.apache.commons.httpclient.ProtocolException
      +- org.apache.commons.httpclient.RedirectException

RedirectException signals violation of the HTTP specification caused by an invalid redirect response. If the application that uses HttpClient needs to be more lenient about redirect responses, it may choose to disable automatic redirect processing and implement a custom redirect strategy.

org.apache.commons.httpclient.URIException

java.io.IOException
  +- org.apache.commons.httpclient.HttpException
    +- org.apache.commons.httpclient.URIException

URIException is thrown when the request URI violates the URI specification.

HTTP transport safety

It is important to understand that the HTTP protocol is not well suited for all types of applications. HTTP is a simple request/response oriented protocol which was initially designed to support static or dynamically generated content retrieval. It has never been intended to support transactional operations. For instance, the HTTP server will consider its part of the contract fulfilled if it succeeds in receiving and processing the request, generating a response and sending a status code back to the client. The server will make no attempts to roll back the transaction if the client fails to receive the response in its entirety due to a read timeout, a request cancellation or a system crash. If the client decides to retry the same request, the server will inevitably end up executing the same transaction more than once. In some cases this may lead to application data corruption or inconsistent application state.

Even though HTTP has never been designed to support transactional processing, it can still be used as a transport protocol for mission critical applications provided certain conditions are met. To ensure HTTP transport layer safety the system must ensure the idempotency of HTTP methods on the application layer.

Idempotent methods

HTTP/1.1 specification defines idempotent method as

Methods can also have the property of "idempotence" in that (aside from error or expiration issues) the side-effects of N > 0 identical requests is the same as for a single request.

In other words the application ought to ensure that it is prepared to deal with the implications of multiple execution of the same method. This can be achieved, for instance, by providing a unique transaction id and by other means of avoiding execution of the same logical operation.

Please note that this problem is not specific to HttpClient. Browser based applications are subject to exactly the same issues related to HTTP methods non-idempotency.

Automatic exception recovery

By default HttpClient attempts to automatically recover from exceptions. The default auto-recovery mechanism is limited to just a few exceptions that are known to be safe.

HttpClient will make no attempt to recover from any logical or HTTP protocol error (those derived from HttpException class).

HttpClient will automatically retry up to 5 times those methods that fail with a transport exception while the HTTP request is still being transmitted to the target server (i.e. the request has not been fully transmitted to the server).

HttpClient will automatically retry up to 5 times those methods that have been fully transmitted to the server, but the server failed to respond with an HTTP status code (the server simply drops the connection without sending anything back). In this case it is assumed that the request has not been processed by the server and the application state has not changed. If this assumption may not hold true for the web server your application is targeting it is highly recommended to provide a custom exception handler.

Custom exception handler

In order to enable a custom exception recovery mechanism one should provide an implementation of the HttpMethodRetryHandler interface.

HttpClient client = new HttpClient();

HttpMethodRetryHandler myretryhandler = new HttpMethodRetryHandler() {
    public boolean retryMethod(
        final HttpMethod method, 
        final IOException exception, 
        int executionCount) {
        if (executionCount >= 5) {
            // Do not retry if over max retry count
            return false;
        }
        if (exception instanceof NoHttpResponseException) {
            // Retry if the server dropped connection on us
            return true;
        }
        if (!method.isRequestSent()) {
            // Retry if the request has not been sent fully or
            // if it's OK to retry methods that have been sent
            return true;
        }
        // otherwise do not retry
        return false;
    }
};
        
GetMethod httpget = new GetMethod("http://www.whatever.com/");
httpget.getParams().
    setParameter(HttpMethodParams.RETRY_HANDLER, myretryhandler);
try {
    client.executeMethod(httpget);
    System.out.println(httpget.getStatusLine().toString());
} finally {
    httpget.releaseConnection();
}

commons-httpclient-3.1/docs/features.html100644 0 0 21154 10661532631 16015 0ustar 0 0 HttpClient - HttpClient Features

Features

  • Standards based, pure Java, implementation of HTTP versions 1.0 and 1.1
  • Full implementation of all HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible OO framework.
  • Supports encryption with HTTPS (HTTP over SSL) protocol.
  • Granular non-standards configuration and tracking.
  • Transparent connections through HTTP proxies.
  • Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
  • Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.
  • Authentication using Basic, Digest and the encrypting NTLM (NT Lan Manager) methods.
  • Plug-in mechanism for custom authentication methods.
  • Multi-Part form POST for uploading large files.
  • Pluggable secure sockets implementations, making it easier to use third party solutions
  • Connection management support for use in multi-threaded applications. Supports setting the maximum total connections as well as the maximum connections per host. Detects and closes stale connections.
  • Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
  • Plug-in mechanism for custom cookie policies.
  • Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
  • Response input streams to efficiently read the response body by streaming directly from the socket to the server.
  • Persistent connections using KeepAlive in HTTP/1.0 and persistance in HTTP/1.1
  • Direct access to the response code and headers sent by the server.
  • The ability to set connection timeouts.
  • HttpMethods implement the Command Pattern to allow for parallel requests and efficient re-use of connections.
  • Source code is freely available under the Apache Software License.

Standards Compliance

HttpClient implements the following specifications endorsed by the Internet Engineering Task Force (IETF) and the internet at large:

  • RFC1945 Hypertext Transfer Protocol -- HTTP/1.0
  • RFC2616 Hypertext Transfer Protocol -- HTTP/1.1
  • RFC2617 HTTP Authentication: Basic and Digest Access Authentication
  • RFC2109 HTTP State Management Mechanism (Cookies)
  • RFC2396 Uniform Resource Identifiers (URI): Generic Syntax
  • RFC1867 Form-based File Upload in HTML

Product Comparision

The HTTP protocol is so ubiquitous on the internet that you can find other client side implementations written in Java. The jdk has the HttpUrlConnection which is limited and in many ways flawed. This is one reason why Jakarta, and others free and commercial vendors, have implemented independant HTTP clients. To help you choose the right solution, one of those commercial vendors, Oakland Software, has a fair product comparison.


commons-httpclient-3.1/docs/file-activity-report.html100644 0 0 37040 10661532631 20262 0ustar 0 0 HttpClient - File Activity Analysis

Activity by File

Changes between 2007-07-19 and 2007-08-19

Timeframe: 30days

Total Commits: 16

Total Number of Files Changed: 39

File Name Number of times changed
/jakarta/httpcomponents/oac.hc3x/trunk/project.xml 5
/jakarta/httpcomponents/oac.hc3x/trunk/release_notes.txt 4
/jakarta/httpcomponents/oac.hc3x/trunk/src/resources/META-INF/NOTICE.txt 2
/jakarta/httpcomponents/oac.hc3x/trunk/src/resources/META-INF/README.txt 2
/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/developerguide.xml 2
/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/downloads.xml 2
/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/index.xml 2
/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/status.xml 2
/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1 (from /jakarta/httpcomponents/oac.hc3x/trunk:567247) 1
/jakarta/httpcomponents/oac.hc3x/trunk/NOTICE.txt 1
/jakarta/httpcomponents/oac.hc3x/trunk/README.txt 1
/jakarta/httpcomponents/oac.hc3x/trunk/build.xml 1
/jakarta/httpcomponents/oac.hc3x/trunk/project.properties 1
/jakarta/httpcomponents/oac.hc3x/trunk/src/java/org/apache/commons/httpclient/HttpState.java 1
/jakarta/httpcomponents/oac.hc3x/trunk/src/java/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.java 1
/jakarta/httpcomponents/oac.hc3x/trunk/src/java/org/apache/commons/httpclient/URI.java 1
/jakarta/httpcomponents/oac.hc3x/trunk/src/java/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.java 1
/jakarta/httpcomponents/oac.hc3x/trunk/src/resources 1
/jakarta/httpcomponents/oac.hc3x/trunk/src/resources/META-INF 1
/jakarta/httpcomponents/oac.hc3x/trunk/src/test/org/apache/commons/httpclient/TestURI.java 1
/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/features.xml 1
/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/logging.xml 1
/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/navigation.xml 1
/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/news.xml 1
/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/overview.xml 1
/jakarta/httpcomponents/oac.hc3x/trunk/xdocs/proposal.xml 1

commons-httpclient-3.1/docs/images/add.gif100644 0 0 317 10661532627 15740 0ustar 0 0 GIF89a*|~Η0XpN>tA9CGOs+ج!,|I8kl_@4DJ,l Ѡ*e|q8HH ET8(`"B`A`iM0[!KǸ|NianVXp\ KXDNNRmKcEXcJn#;commons-httpclient-3.1/docs/images/banner.jpg100644 0 0 1550 10661532627 16510 0ustar 0 0 JFIFddDuckydAdobed]     u!"1A2# QBa$3Rqb%C&4r 5'S6DTsEF7Gc(UVWdte)8fu*9:HIJXYZghijvwxyzm!1"AQ2aqB#Rb3 $Cr4%ScD&5T6Ed' sFtUeuV7)(GWf8vgwHXhx9IYiy*:JZjz ?Gރu' 7trO{^A^!?֫{u?+saGG{QD3~t(Ѿ˿^/_commons-httpclient-3.1/docs/images/breadcrumbs.jpg100644 0 0 535 10661532627 17516 0ustar 0 0 JFIFHHExifMM*C  !"$"$C " RTa ?~x OL5hFJojcommons-httpclient-3.1/docs/images/collapsed.gif100644 0 0 65 10661532627 17136 0ustar 0 0 GIF89a! , D`c5 ;commons-httpclient-3.1/docs/images/expanded.gif100644 0 0 64 10661532627 16757 0ustar 0 0 GIF89a! , j ;commons-httpclient-3.1/docs/images/external.png100644 0 0 346 10661532627 17053 0ustar 0 0 PNG  IHDR Ӻ&gAMA7tEXtSoftwareAdobe ImageReadyqe< PLTEuuuPtRNS@*PIDATxb`&& @ P6#@ `XĆ2 d@A3 ( *tIENDB`commons-httpclient-3.1/docs/images/fix.gif100644 0 0 265 10661532627 16000 0ustar 0 0 GIF89a-H/Ʊ8)&#騦rT:$TRTxwv!,b9 ^+_'nYE1REAeWܮQ!{pKe0`!5 VJ`Q7  );commons-httpclient-3.1/docs/images/h3.gif100644 0 0 310 10661532627 15513 0ustar 0 0 GIF89a˙,M %dQ$ED$ϴ}S'DnG` @` ]$Ty[PŸ|N|<;commons-httpclient-3.1/docs/images/h5.jpg100644 0 0 545 10661532627 15542 0ustar 0 0 JFIFHHExifMM*C  !"$"$C " ?՛s}c?w5tBX?fh}+ 康0commons-httpclient-3.1/docs/images/httpclient_logo.png100644 0 0 10237 10661532627 20467 0ustar 0 0 PNG  IHDREd"z pHYs  ~gAMA|Q cHRMz%u0`:o_FIDATxb?(` BqQ0  F Q0 F(@4Z(Q0 FBqQ0 @`QhP`$@(` -G( h8 F(H F Q0 F(@4Z(Q0 FBqQ0 @`QhP`$@(` -G( h8 F(H F Q0 F(@4Z(Q0 F EFFFTW@rma Vs@@u'( +G1Qsj08pi_(\A-Jz!PH&*iFNcA K$H 'j0H@ Pa PhnE#(,s;`h06XdeaW~|2ˆiU!8qo g~UD( >۟P5],]R"Æ=.p܊$H GȤu\= nfᶚDaxԅaqEԏ}Iw Z ܲ-Hn!uG1" DST PeNi}!%ZC3. _WD-m@0jnC,jh$Ab_Wa̐qLzX@$K3a<"B#& 1_BhR"ϡxA$?ɐDSs\N(  ҲabbhjvjuKhJE 5M}dQ/AcC $cR-VVAÊ'a`I-`iJ0Bʒ ꋠQ+i *">H|[şVѪ% -)/|<1JۨW9 x#-OTpn] -C)C̡U4 և}_률Bcd^xBRҺU(b^>&*'m6jh?#V"dxH)N'5V9Lj,tC3qbVҒ`v FKOB0Ǒ.1䳚ܱJqFdKpVesw[2Z#Lh hpDfHc>#mϔEt^< ~F֊*iP}X=IMBh Piv`%b0r*c b-T㻄åPH>K]jbIDiBGF`9ZBY@1[FiFB@<\ 3_$ Oqw h xwjaTk LUfQ >H{pZPR@Z!XM0"d -H#C_̀K NK O ]3F=ЏTcd:e2򺩐´6څqiZY.4)vK`]jj$.)ZK fQ+SRo֖LJfWjZFM:MNcyPaN!=o/hQK @uv#}ںXMp6-ЮT( v-e2V#a bIY ln/wB%1,h83F=@ oA-_Mc,,y.-(w͂6jqlM;EA v[0w"ֻ!q-iBq1a Mo5Rki"PQ= 2)wTBFCd1g@=՗^- gPvuZÐ O5E$a8Ңt|șΕ%_`mϴ1& [;XBkK9af-LWHZ Deh'!BaDl:YMTG6Mĕ_R#q8 D-`Q0)eh8 F(-@`B h8 F(-@`B h8 F(-@`B h8 F(-@`B h8 F(-@`B #)G(Ha02( b[D@HDK!~cffʇp ?dɓTm&u (-/5"6l5d`ȳ9@C0`")mP]h84Z(PWa3Z(RNùPBqPBݼB6v \(h8Z(XHhH;p.hP-\8Z(L4Z(t/iѭ-ikfB F B"Z/"B684 Ez%^z X gRz,h8 EJƃ6l B- F BqHeNJ"@#P"1n-~e4Z(B{ai)SZ-GN@)R8zPޅ"@QP߿Bq,Fr-G Ejj:ϟ?L.*-G EjbB` ^0 Q0 -EVVV߿:RX>oSV;ObK >H F ŁXC@-S(}CPBqPqP-k@T_3u"G EC@.K8Z(RP46 E-G`8[ihH@)i/A33$!z[l"@$El vvvP; Q0 h4Ennn6"06 y \l8bȀ3ׯ_  &hG Q@@-Q@Qol (F.(i F[3@F( pqq=daaaV0!Xñ8 hKq؄.aیJšh8 (B}y@ChKq^|h 2# Vx( u4̼C5܈(+^"NvE攚Gm-G E333&Za EbNj=y{PhP-Isab+a-va3 F_B?`Ǐ05 6z@$ `ƶ@mkߐm--];@$ X`pZQ-GXvyAZ3XkG4Z('`k t7r* A_q yF/4[h q-GBqsssKfha3[P*~/ .a&0E/0A|XA ][HLLL-# K`Q4Z(Q0 FBqQ0 @`QhP`$` =IENDB`commons-httpclient-3.1/docs/images/icon_error_sml.gif100644 0 0 1762 10661532627 20251 0ustar 0 0 GIF89a  q x v m;@GJf46_     i [        ~ } s q p n X V L     v l ~ "",9?6;{6:df島$')OWͱ-/*"4"3s}%8&:(=*@+A*?5H=MM\+B.F/G0I2M3O2N%9J.FprN3Ovx{@-EL6RO8V08G3O1:bGm3=4>7 C5AgOx?2ME7TmW|d}gu^V!,; H AJgN޴Yc* FrM/]HIh $5iΌ %BT 0P8$2,ㅋ,Z(DL@;Gk$<Hd >`'!\2?vhp  u@ .X = q0 )f$Tp"FQGr̉C;commons-httpclient-3.1/docs/images/icon_info_sml.gif100644 0 0 1136 10661532627 20046 0ustar 0 0 GIF89ar 'SG]}]yVpOgLcJ`EYxCWtI^~FZyehgjlmpXltvdyw|~wunzw…ǘƂ˦ΩЭҬџ԰ӵָؼݲ@TpAUqy}ŞɧŹ!r,r`fg`l\d LG^qqopnQmbj.MObhNgr\oP6 [ig%dmE4k_^eL PRah YcHBjfV F`\- 5Z=97D`] I' 130@KICA@,"c $XA ?tr兊!8h2† @Pab ;commons-httpclient-3.1/docs/images/icon_success_sml.gif100644 0 0 1736 10661532627 20571 0ustar 0 0 GIF89aΧμc~w˗éSq*/%(#8='*!37,/(CH'AF&>B/2*,)FI"!PrkjtŲFcO7G;ȝȣ֩۴߲2B.ᥳ⦷㫸䬸䭺导屏€㩲ࢲࣜΈޘܙٗۗ]B΅ԋۑ̈́՗]>Ԅሻfrmjb7Jw*U0W2im;Ag$r?o=e8f8b7Z2Y1S.Jt)Qy1WYuQeFcE{{hGv@u?k:h7`3Jr(E^3Q|,S~-Dh%}DEi&QŢIm&Qx+Ot)Mo(Ll&Ig%Gc$!, HA!,XE aCF5pAƏ *01#"NT0A=Y& NRI1bJ':o8b3-e˓у>|¥ (qŋ4hԱ(ЋmT"J;*d("4lp ,P( ;commons-httpclient-3.1/docs/images/icon_warning_sml.gif100644 0 0 1100 10661532627 20547 0ustar 0 0 GIF89ab`awr}~j|fsη⣴[M@K? kTN G J$wsrpiffecb_[ZTQOJ E D E ? i2 nm]XWVH A = h2 ]-bz{z&Zi&i(j&127m-D2%p4BI|Du@Ya\}R׈[v[mI:2̓`vّs=.()+*砅.!ӗ<,&餍5&!:*%y*vp묜*,-~zǟ!v,v oaed][sv iT u^PW\ZMIgXUGADSRQ?4VONK)#CnJHFE0=7'6*v B@%+8, l !5"9.:/Lt"$&(-3:c Yf3cđ# ;;commons-httpclient-3.1/docs/images/jakarta-logo.gif100644 0 0 17506 10661532627 17633 0ustar 0 0 GIF89a^d!!!111999BBBcccsss{{{籠ބJB!ƵZ9RBk1B{RRk1R֜{{9絔sc{B{JkcskcRƽZνƭkcZJ֥{֭B)΄sZ)έέ޽c{{s{sBc99c)B!Z9kkޜ)scJkcΌ{{k1{c{ZJ!{99RRRk1!{1,^d@ CCBBDB33*BE *||s|xwux}&##-"84Пڡ BDQIHJHLRQSRTT^V_Wa`cakinmos3M<@ * Bl3jȱo.T$` C`$P͘3byy'ŊvMӈ#H Id $MM"-[x7M|h#G?:}C9t晰!L@@ xݫ"n `H>xX4\w˗/`n%&9%G!iN&준o/\'JdhO=e0s/NzmuS nML@A|sOZ7wڸy>?5tq&~i=cbs=}TH[LEWpaE^xA|CHPD`@! Žo&d,PAp4X%2a@P+H&\ Dө? QH VBoc#0 B>@̈́2Vi p,WDZ$! FH:&Mg ` /|( Bv@$ZT(7)@Br d@&( *)0@!C Ӈ<^0=k0:̡c60V7$PF6zE ڸ:yIU ܀g4oԳXy2:Z}JhYAI 2BPE4e -DN $0$hiH+6g] FJMU8  Ia ZLwѻ!a-IR-eZ\Jc5,٪SQFlk ?T, `VULu4R]Iэ"kwxDR 1M(8,!t Vr,^0R:#K01XV8@d]EmT8X+wvlg&ඃ(-mm[UE۹mrڢ?jp B"P# `_U@F,O. f Z$xA#iv+yLIdR0 )؛ @*,]! kȢ~V׺6ayrw@G-;$n`:N 08)RB(P -\4oA;E\PЂ܀p7©CA]( %\pRv2l&,TBg2_@ i42seY*m$ Wb |uF!,aC 2Qi >#0>j]@O!LTN5|Cd(y8ZpXN[A{uMoO @Yc x RX3r \B<'4GcQȄ$)MCzv> w&|ԅ"@MsG(%"  S 0D|{0M0@:#B&HAZG8I'!6AB/Fj(i~F= gv4HKl0Zg!|P!S dk!W"5] \ഇ!,P Yhu  >ѣ:@3p~SAA7)N8ȔuP$8 @0p0A[N  yCЁ}!1u@/7!Xq_I@/1pbH ąxӑ=x|H:@@:P[9{ (OOJb P'@|` cC|fvt@waLs AKi`55"k9@{cb9JN woRIR{RxSR3VW@xPy82Wc+@5TŒ*ÎZtVeRŘ+x1 +UXWe0$hk?3Iy+v`EinSa Ƞg9jsD(5b,0Ep5ePfjgd)sa!Pg `8-B[9S[pVpq V:qCc&@# תF",`9NLpqM`2/mnp('Vgc d::OIN:?Q|4ҳQWa:hZdr.K0%p>pkJh *E:1{ dH]ݣ*Ks|Š|- P+,9, T7a]G|M5y=&:1E!kbrdVba!-; m b)!I9U(ѶGh'' r*$F#K~d:s@x&笃&-6K󄄾m gpF t=ku\׿EAqqaB\@ydvaLq^z0z Lzo0:FAlt-!\`[:&S@èWz>QF={n=ЋCSC1`S8t`'6" @Yh3:WyGFWJTƦqGrLMc;a0jѫVLw@ ` tCE{wdk+wJ }Ӕi :pqVa B 4YWztdGO0FѿAɆ+dBg`3MIl47$4>&s&@|pؗAt0Mm`M1gMVE@HS0OG`GPaiv5q5G{I>`,̿gǂpagߧEīW& F$GBupW ;1,B#90N;gG-$. !D(@|A8h}KD=f _r^Ѡ#%Tpgv7,"*-"DN6@؅HP|: @6&@vxba}FT@Y`\3>2$ 4:fP#H7H":0]OTh.pXlP m! |Ż'zxojLUԼkE)85ts@N|}#I64?>+ན)mOZ{'"J9}@$'Xd}"vCTbcqVkpg w@ 0|   v  `d.vsHr;,THK…=N3sCrPz{OpH=@¿%D\লiw_HpN(r8 0Gi 岡@8윰rP07űSȉ29HU`5/ Y@)TY!/^ @H!9u,st9)Ȋ'E^ )ԉPYM?)Չ5*0Q).VORIE5RHDsЮ,*B?^p )ˈ6_' /ibOG/^E9GPxZ 29 9Dr؉|_h"9 xNB"2672YCO7Ó89?X4?)?I-s8TD0-*؂e~85VPE L CR BB B. .ԃ*ؑیѡ׃ٚȾޕ.ƭʃ̾yҫV`#-+@qs5C4c!!2kGڱe:)2]P[1䢑.|Y  XtC1(1E$0jӌjl'EZ4c26@B3piZ.PjvQ_;b?g[ ™vaCMӨ2Nͺװc˞u2ۯHьwҽ{69Im o|]vp7UҀ\v^!0`@f+H~ + h߁u$pSZ|3,@\Jr@ ,%y,w.ԉ3꣒((֘CX@VBH7dP CT 3ne^$I]#'df8 P Iz%"r@{'+bnP}UHcH~(^ Y qcq$ꢨi/mvj|@a 69뭸뮼;klb#c,{EئmB-@'@@*,قk$| @@h9fb$dފdp!"h1l0,# !B|p(zq- kXVl(,0,!;EW av[n1jpw\C7[оWb!$y'rX`u-ސ7@6Uxw] H`ws X y]8;cPfxe T65Awsnyh39pn:8]hFb ׮bxXižh&Xܶ,N4[%!j"ǻd;"\f4sG5g!K7f\;\~ݡP@]wq(iFaMG~ϻ>Oh\A`B:>\%R}!"fwѓ~@?9r ?o!è x[TG,W\=vxKBP3%o!Yj\^plkDaKx!np]E!Ch')V!fsE3kB7)!9{;1!뫡ߖ.2±w5cxH}ф ya5@d"2qhvD0_'Ph73%*J"be$%)Y7!BCd1H @ SWD> eGPRSMGFDd$2v͌)D=Sc!KDH6\7eԓ焖F@(A-Y!@ƐgOo"$T YD;8O '5<z;#)6.:eJ)QSp!5' ^ #b+3, /΅. Xo-pNk#WWE+y&!c]x-Jʥ?: e0Yc&s|f4#2 ;commons-httpclient-3.1/docs/images/logos/mavenlogo_builtby_w.png100644 0 0 4324 10661532627 22443 0ustar 0 0 PNG  IHDRZ#/ pHYs.#.#x?vtIME5BasIDATXY}LS[{_b6(_i _ڠA+ D+*5وp dQyFC$XkX\*R>  VDOj G>|a?Ι3̙sJ!`&^`/&)--{hW^1 ;2j0~!pwtt>|СC"hݳu|~`` |8::ZRR%ɖ-[WXA,hܚJY֯^ R߰aåKFg\]]RD"!իW%&&VWWڵݻ[n%$$cǔJׅ~zr<66uuuslll.B!fx<EQnnn*؁Di***fS5>>>]mX***֭[ ))))FoD0L\\\\\ٳg ERRRaa.]G,TVVV=عsg{{}Ε+WH2jl6fQe9! }}}aaa3t.zqUUU``{ω/mccc|>Ņ(,Z(Lfo8>s,A֖޽{-˗hi:44 }S?L!55uƍ$F02á 3{l/n&'S˲ 1CBCC7Z aFquwwJD1e{6wO+l.@ !͛hJc6KU*J*..BVg\.%R$z||\VT覦'Nxzz:99)ʊyd23&&wRh4Vupp ;UvT6Noooݍc^^^& !t9wtt$9rOimmihdWeddd~ਫ#v˱ O:Eؾ}dpqĽ~޾^z }2VY|9U__9(({^RR~:v5** CVSS#UPP@z߭[>}:22DN8rss?m4ׇoB^Ȍ 1M+v-8nŃj*++C]x?n޼8j}'8p:s 6`4?\\}}=f/^Ln5BBB0SҞ!{BOQ fHtL&|]$ ϟ?OQTcc#YVIx28Ÿ!sDzlcc#WZEǏcӓ`D+Woad( ܃)_+lQ+fz}^^^OO*VݝGHPH.3s5/^HttpClient - HttpClient Home

Introduction

The Hyper-Text Transfer Protocol (HTTP) is perhaps the most significant protocol used on the Internet today. Web services, network-enabled appliances and the growth of network computing continue to expand the role of the HTTP protocol beyond user-driven web browsers, while increasing the number of applications that require HTTP support.

Although the java.net package provides basic functionality for accessing resources via HTTP, it doesn't provide the full flexibility or functionality needed by many applications. The Jakarta Commons HttpClient component seeks to fill this void by providing an efficient, up-to-date, and feature-rich package implementing the client side of the most recent HTTP standards and recommendations. See the Features page for more details on standards compliance and capabilities.

Designed for extension while providing robust support for the base HTTP protocol, the HttpClient component may be of interest to anyone building HTTP-aware client applications such as web browsers, web service clients, or systems that leverage or extend the HTTP protocol for distributed communication.

There are many projects that use HttpClient to provide the core HTTP functionality. Some of these are open source with project pages you can find on the web while others are closed source that you would never see or hear about. The Apache Source License provides maximum flexibility for source and binary reuse. Please see the Applications page for projects using HttpClient.

History

HttpClient was started in 2001 as a subproject of the Jakarta Commons, based on code developed by the Jakarta Slide project. It was promoted out of the Commons in 2004, graduating to a separate Jakarta project. In 2005, the HttpComponents project at Jakarta was created, with the task of developing a successor to HttpClient 3.x and to maintain the existing codebase until the new one is ready to take over. The Commons project, cradle of HttpClient, left Jakarta in 2007 to become an independent Top Level Project. For the time being, HttpClient still has it's home with HttpComponents at Jakarta.


commons-httpclient-3.1/docs/issue-tracking.html100644 0 0 11036 10661532631 17125 0ustar 0 0 HttpClient - Issue Tracking

Issue Tracking

This project uses an Issue Management System to manage its issues.

Issues, bugs, and feature requests for this project should be submitted to the following issue tracking system:


commons-httpclient-3.1/docs/javadoc-warnings-report.html100644 0 0 12365 10661532631 20751 0ustar 0 0 HttpClient - JavaDoc Audit Results

JavaDoc Warnings

The following document contains JavaDoc warnings.

Summary

Files Errors
0 0

Files

Files Errors

commons-httpclient-3.1/docs/javadoc.html100644 0 0 16343 10661532631 15612 0ustar 0 0 HttpClient - Javadoc Report

Javadoc Report

  Generating Javadoc
  Javadoc execution
  Loading source files for package org.apache.commons.httpclient...
  src/java/org/apache/commons/httpclient/HttpContentTooLargeException.java:6: warning: unmappable character for encoding UTF8
   * @author Ortwin Gl?
                      ^
  Loading source files for package org.apache.commons.httpclient.auth...
  Loading source files for package org.apache.commons.httpclient.cookie...
  Loading source files for package org.apache.commons.httpclient.methods...
  Loading source files for package org.apache.commons.httpclient.methods.multipart...
  Loading source files for package org.apache.commons.httpclient.params...
  Loading source files for package org.apache.commons.httpclient.protocol...
  Loading source files for package org.apache.commons.httpclient.util...
  Constructing Javadoc information...
  Standard Doclet version 1.5.0_11
  Building tree for all the packages and classes...
  Generating target/docs/apidocs/serialized-form.html...
  Copying file /home/oleg/.maven/cache/maven-javadoc-plugin-1.9/plugin-resources/stylesheet.css to file target/docs/apidocs/stylesheet.css...
  Building index for all the packages and classes...
  Building index for all classes...
  Generating target/docs/apidocs/help-doc.html...
  1 warning
  Generating Javadoc
  Javadoc execution
  Loading source files for package org.apache.commons.httpclient...
  src/java/org/apache/commons/httpclient/HttpContentTooLargeException.java:6: warning: unmappable character for encoding UTF8
   * @author Ortwin Gl?
                      ^
  Loading source files for package org.apache.commons.httpclient.auth...
  Loading source files for package org.apache.commons.httpclient.cookie...
  Loading source files for package org.apache.commons.httpclient.methods...
  Loading source files for package org.apache.commons.httpclient.methods.multipart...
  Loading source files for package org.apache.commons.httpclient.params...
  Loading source files for package org.apache.commons.httpclient.protocol...
  Loading source files for package org.apache.commons.httpclient.util...
  Constructing Javadoc information...
  Standard Doclet version 1.5.0_11
  Building tree for all the packages and classes...
  Generating target/docs/apidocs/serialized-form.html...
  Copying file /home/oleg/.maven/cache/maven-javadoc-plugin-1.9/plugin-resources/stylesheet.css to file target/docs/apidocs/stylesheet.css...
  Building index for all the packages and classes...
  Building index for all classes...
  Generating target/docs/apidocs/help-doc.html...
  1 warning

commons-httpclient-3.1/docs/jdepend-report.html100644 0 0 206241 10661532631 17143 0ustar 0 0 HttpClient - JDepend Source Code Analysis

Metric Results

[ summary] [ packages] [ cycles] [ explanations]

The following document contains the results of a JDependmetric analysis. The various metrics are defined at the bottom of this document.

Summary

[ summary] [ packages] [ cycles] [ explanations]

Package TC AC CC AC EC A I D
org.apache.commons.httpclient 68 7 61 6 15 0.1 71% 18%
org.apache.commons.httpclient.auth 20 5 15 1 10 0.25 91% 16%
org.apache.commons.httpclient.cookie 23 4 19 1 6 0.17 86% 3%
org.apache.commons.httpclient.methods 15 3 12 1 8 0.2 89% 9%
org.apache.commons.httpclient.methods.multipart 8 3 5 1 7 0.38 88% 25%
org.apache.commons.httpclient.params 9 2 7 5 5 0.22 50% 28%
org.apache.commons.httpclient.protocol 9 3 6 1 10 0.33 91% 24%
org.apache.commons.httpclient.util 15 0 15 6 11 0 65% 35%

Packages

[ summary] [ packages] [ cycles] [ explanations]

org.apache.commons.httpclient

Afferent Couplings Efferent Couplings Abstractness Instability Distance
6 15 10% 71% 18%
Abstract Classes Concrete Classes Used by Packages Uses Packages

org.apache.commons.httpclient.methods.multipart

Afferent Couplings Efferent Couplings Abstractness Instability Distance
1 7 38% 88% 25%
Abstract Classes Concrete Classes Used by Packages Uses Packages

Cycles

[ summary] [ packages] [ cycles] [ explanations]

Package Cyclic Dependencies
org.apache.commons.httpclient
  • org.apache.commons.httpclient.util
  • org.apache.commons.httpclient
org.apache.commons.httpclient.auth
  • org.apache.commons.httpclient.util
  • org.apache.commons.httpclient
  • org.apache.commons.httpclient.util
org.apache.commons.httpclient.cookie
  • org.apache.commons.httpclient
  • org.apache.commons.httpclient.util
  • org.apache.commons.httpclient
org.apache.commons.httpclient.methods
  • org.apache.commons.httpclient
  • org.apache.commons.httpclient.util
  • org.apache.commons.httpclient
org.apache.commons.httpclient.methods.multipart
  • org.apache.commons.httpclient.util
  • org.apache.commons.httpclient
  • org.apache.commons.httpclient.util
org.apache.commons.httpclient.params
  • org.apache.commons.httpclient
  • org.apache.commons.httpclient.util
  • org.apache.commons.httpclient
org.apache.commons.httpclient.protocol
  • org.apache.commons.httpclient.util
  • org.apache.commons.httpclient
  • org.apache.commons.httpclient.util
org.apache.commons.httpclient.util
  • org.apache.commons.httpclient
  • org.apache.commons.httpclient.util

Explanations

[ summary] [ packages] [ cycles] [ explanations]

The following explanations are for quick reference and are lifted directly from the original JDepend documentation.

Term Description
Number of Classes The number of concrete and abstract classes (and interfaces) in the package is an indicator of the extensibility of the package.
Afferent Couplings The number of other packages that depend upon classes within the package is an indicator of the package's responsibility.
Efferent Couplings The number of other packages that the classes in the package depend upon is an indicator of the package's independence.
Abstractness The ratio of the number of abstract classes (and interfaces) in the analyzed package to the total number of classes in the analyzed package. The range for this metric is 0 to 1, with A=0 indicating a completely concrete package and A=1 indicating a completely abstract package.
Instability The ratio of efferent coupling (Ce) to total coupling (Ce / (Ce + Ca)). This metric is an indicator of the package's resilience to change. The range for this metric is 0 to 1, with I=0 indicating a completely stable package and I=1 indicating a completely instable package.
Distance The perpendicular distance of a package from the idealized line A + I = 1. This metric is an indicator of the package's balance between abstractness and stability. A package squarely on the main sequence is optimally balanced with respect to its abstractness and stability. Ideal packages are either completely abstract and stable (x=0, y=1) or completely concrete and instable (x=1, y=0). The range for this metric is 0 to 1, with D=0 indicating a package that is coincident with the main sequence and D=1 indicating a package that is as far from the main sequence as possible.
Cycles Packages participating in a package dependency cycle are in a deadly embrace with respect to reusability and their release cycle. Package dependency cycles can be easily identified by reviewing the textual reports of dependency cycles. Once these dependency cycles have been identified with JDepend, they can be broken by employing various object-oriented techniques.

commons-httpclient-3.1/docs/junit-report.html100644 0 0 2070001 10661532631 16676 0ustar 0 0 HttpClient - JUnit Test Results

Summary

[summary] [package list] [test cases]

Tests Errors Failures Success rate Time(s)
591 0 0 100.00% 32.26

Note: failures are anticipated and checked for with assertions while errors are unanticipated.

Package List

[summary] [package list] [test cases]

PackageTestsErrorsFailuresSuccess RateTime
org.apache.commons.httpclient 591 0 0 100.00% 32.26

Note: package statistics are not computed recursively, they only sum up all of its testsuites numbers.

org.apache.commons.httpclient

ClassTestsErrorsFailuresSuccess RateTime
Success TestAll 591 0 0 100.00% 32.258

Test Cases

[summary] [package list] [test cases]

TestAll

Success testHttpMethodBasePaths 0.03
Success testHttpMethodBaseDefaultPath 0.00
Success testHttpMethodBasePathConstructor 0.01
Success testHttpMethodBaseTEandCL 0.05
Success testConnectionAutoClose 0.00
Success testSetGetQueryString1 0.00
Success testQueryURIEncoding 0.00
Success testSetGetQueryString2 0.00
Success testReleaseConnection 0.00
Success testEmptyBodyAsString 0.11
Success testEmptyBodyAsByteArray 0.00
Success testLongBodyAsString 0.21
Success testUrlGetMethodWithPathQuery 0.00
Success testUrlGetMethodWithPath 0.00
Success testUrlGetMethod 0.00
Success testUrlGetMethodWithInvalidProtocol 0.00
Success testHttpMethodBasePaths 0.01
Success testHttpMethodBaseDefaultPath 0.00
Success testHttpMethodBasePathConstructor 0.00
Success testHttpMethodBaseTEandCL 0.01
Success testConnectionAutoClose 0.00
Success testSetGetQueryString1 0.00
Success testQueryURIEncoding 0.00
Success testSetGetQueryString2 0.00
Success testReleaseConnection 0.01
Success testEmptyBodyAsString 0.11
Success testEmptyBodyAsByteArray 0.00
Success testLongBodyAsString 0.21
Success testUrlGetMethodWithPathQuery 0.00
Success testUrlGetMethodWithPath 0.00
Success testUrlGetMethod 0.00
Success testUrlGetMethodWithInvalidProtocol 0.00
Success testStatusText 0.00
Success testStatusTextNegative 0.00
Success testStatusTextAll 0.00
Success testIfStatusLine 0.00
Success testSuccess 0.00
Success testFailure 0.00
Success testRequestLineGeneral 0.00
Success testRequestLineQuery 0.00
Success testRequestLinePath 0.00
Success testToExternalFormNull 0.00
Success testToExternalFormNullName 0.00
Success testToExternalFormNullValue 0.00
Success testToExternalForm 0.00
Success testEqualToNVP 0.00
Success testGet 0.00
Success testSet 0.00
Success testHashCode 0.00
Success testEquals 0.00
Success testOldMain 0.00
Success testFringeCase1 0.00
Success testFringeCase2 0.00
Success testFringeCase3 0.00
Success testGet 0.00
Success testSet 0.00
Success testHashCode 0.00
Success testEquals 0.00
Success testAddRequestHeader 0.00
Success testRemoveRequestHeader 0.00
Success testOverwriteRequestHeader 0.00
Success testGetResponseHeader 0.00
Success testHostRequestHeader 0.10
Success testHeaders 0.00
Success testDuplicateContentLength 0.00
Success testDuplicateConnection 0.10
Success testNoContentLength 0.11
Success testInvalidContentLength1 0.00
Success testInvalidContentLength2 0.00
Success testProxyNoContentLength 0.11
Success testNullHeaders 0.00
Success testFoldedHeaders 0.00
Success testForceCloseConnection 0.00
Success testForceCloseConnection2 0.00
Success testNoContent 0.11
Success testNullHeader 0.00
Success testHostHeaderPortHTTP80 0.00
Success testHostHeaderPortHTTP81 0.00
Success testHostHeaderPortHTTPS443 0.00
Success testHostHeaderPortHTTPS444 0.00
Success testHeadersPreserveCaseKeyIgnoresCase 0.00
Success testChunkedInputStream 0.00
Success testCorruptChunkedInputStream1 0.00
Success testEmptyChunkedInputStream 0.00
Success testContentLengthInputStream 0.00
Success testContentLengthInputStreamSkip 0.00
Success testChunkedConsitance 0.00
Success testChunkedOutputStream 0.00
Success testChunkedOutputStreamLargeChunk 0.00
Success testChunkedOutputStreamSmallChunk 0.00
Success testAutoCloseInputStream 0.00
Success testParsing 0.00
Success testParsingEscapedChars 0.00
Success testParsingBlankParams 0.00
Success testBasicValueFormatting 0.00
Success testGet 0.00
Success testSet 0.00
Success testHashCode 0.00
Success testEquals 0.00
Success testRequestCharEncoding 0.00
Success testNoExplicitCharEncoding 0.00
Success testExplicitCharEncoding 0.00
Success testLatinAccentInRequestBody 0.00
Success testRussianInRequestBody 0.00
Success testQueryParams 0.00
Success testUrlEncodedRequestBody 0.00
Success testRequestEntityLength 0.00
Success testHttpVersionInvalidConstructorInput 0.00
Success testHttpVersionParsing 0.00
Success testInvalidHttpVersionParsing 0.00
Success testHttpVersionEquality 0.00
Success testHttpVersionComparison 0.00
Success testClientLevelHttpVersion 0.00
Success testMethodLevelHttpVersion 0.00
Success testHostLevelHttpVersion 0.00
Success testReadHttpLine 0.00
Success testReadWellFormedHttpHeaders 0.00
Success testReadMalformedHttpHeaders 0.00
Success testHeadersTerminatorLeniency1 0.00
Success testHeadersTerminatorLeniency2 0.00
Success test1Lenient 0.10
Success test1Strict 0.10
Success testProtocol 0.00
Success testProtocolSocketFactory 0.00
Success testProtocolSocketFactorySublass 0.00
Success testHostConfiguration 0.00
Success testGetMethodQueryString 0.00
Success testGetMethodQueryString2 0.01
Success testGetMethodParameters 0.00
Success testGetMethodMultiParameters 0.00
Success testGetMethodParameterWithoutValue 0.00
Success testGetMethodParameterAppearsTwice 0.00
Success testGetMethodOverwriteQueryString 0.00
Success testPostMethodParameterAndQueryString 0.00
Success testGetCause 0.00
Success testStackTraceWriter 0.02
Success testStackTraceStream 0.00
Success testHttpStateCredentials 0.00
Success testToString 0.00
Success testHttpStateNoCredentials 0.00
Success testHttpStateDefaultCredentials 0.00
Success testHttpStateProxyCredentials 0.00
Success testHttpStateProxyNoCredentials 0.00
Success testHttpStateProxyDefaultCredentials 0.00
Success testDefaultCredentials 0.00
Success testRealmCredentials 0.00
Success testHostCredentials 0.00
Success testWrongHostCredentials 0.00
Success testWrongRealmCredentials 0.00
Success testScopeMatching 0.00
Success testCredentialsMatching 0.00
Success testDefaultConstuctor 0.00
Success testComparator 0.00
Success testDefaultConstuctor 0.00
Success testComparator 0.00
Success testParseAttributeInvalidAttrib 0.00
Success testParseAttributeInvalidCookie 0.00
Success testParseAttributeNullPath 0.00
Success testParseAttributeBlankPath 0.00
Success testParseAttributeNullDomain 0.00
Success testParseAttributeBlankDomain 0.00
Success testParseAttributeNullMaxAge 0.00
Success testParseAttributeInvalidMaxAge 0.00
Success testParseAttributeNullExpires 0.00
Success testParseAttributeUnknownValue 0.00
Success testValidateNullHost 0.00
Success testValidateBlankHost 0.00
Success testValidateNullPath 0.00
Success testValidateBlankPath 0.00
Success testValidateInvalidPort 0.00
Success testValidateInvalidCookieVersion 0.00
Success testDomainCaseInsensitivity 0.00
Success testParse1 0.00
Success testParse2 0.00
Success testParse3 0.00
Success testQuotedExpiresAttribute 0.00
Success testSecurityError 0.00
Success testParseSimple 0.00
Success testParseSimple2 0.00
Success testParseNoName 0.00
Success testParseNoValue 0.00
Success testParseWithWhiteSpace 0.00
Success testParseWithQuotes 0.00
Success testParseWithPath 0.00
Success testParseWithDomain 0.00
Success testParseWithSecure 0.00
Success testParseWithComment 0.00
Success testParseWithExpires 0.00
Success testParseWithAll 0.00
Success testParseMultipleDifferentPaths 0.00
Success testParseMultipleSamePaths 0.00
Success testParseRelativePath 0.00
Success testParseWithWrongDomain 0.00
Success testParseWithNullHost 0.00
Success testParseWithBlankHost 0.00
Success testParseWithNullPath 0.00
Success testParseWithBlankPath 0.00
Success testParseWithNegativePort 0.00
Success testParseWithNullHostAndPath 0.00
Success testParseWithPathMismatch 0.00
Success testParseWithPathMismatch2 0.00
Success testParseWithInvalidHeader1 0.00
Success testParseWithInvalidHeader2 0.00
Success testCookieNameWithBlanks 0.00
Success testCookieNameStartingWithDollarSign 0.00
Success testCookieWithComma 0.00
Success testDateFormats 0.01
Success testSecondDomainLevelCookie 0.00
Success testSecondDomainLevelCookieMatch1 0.00
Success testSecondDomainLevelCookieMatch2 0.00
Success testSecondDomainLevelCookieMatch3 0.00
Success testInvalidSecondDomainLevelCookieMatch1 0.00
Success testInvalidSecondDomainLevelCookieMatch2 0.00
Success testMatchNullHost 0.00
Success testMatchBlankHost 0.00
Success testMatchInvalidPort 0.00
Success testMatchNullPath 0.00
Success testMatchBlankPath 0.00
Success testMatchNullCookie 0.00
Success testMatchNullCookieDomain 0.00
Success testMatchNullCookiePath 0.00
Success testCookieMatch1 0.00
Success testCookieMatch2 0.00
Success testCookieMatch3 0.00
Success testCookieMatch4 0.00
Success testCookieMismatch1 0.00
Success testCookieMismatch2 0.00
Success testCookieMismatch3 0.00
Success testCookieMismatch4 0.00
Success testCookieMatch5 0.00
Success testCookieMismatch6 0.00
Success testMatchNullCookies 0.00
Success testMatchedCookiesOrder 0.00
Success testInvalidMatchDomain 0.00
Success testFormatInvalidCookie 0.00
Success testGenericCookieFormatting 0.00
Success testGenericCookieFormattingAsHeader 0.00
Success testNullCookieValueFormatting 0.00
Success testFormatInvalidCookies 0.00
Success testFormatZeroCookies 0.00
Success testFormatSeveralCookies 0.00
Success testFormatOneCookie 0.00
Success testFormatSeveralCookiesAsHeader 0.00
Success testKeepCloverHappy 0.00
Success testParseAttributeInvalidAttrib 0.00
Success testParseAttributeInvalidCookie 0.00
Success testParseAttributeNullPath 0.00
Success testParseAttributeBlankPath 0.00
Success testCookieNameWithBlanks 0.00
Success testCookieNameStartingWithDollarSign 0.00
Success testCookieWithComma 0.00
Success testSecondDomainLevelCookie 0.00
Success testNullCookieValueFormatting 0.00
Success testFormatInvalidCookies 0.00
Success testParseAttributeNullVersion 0.00
Success testParseAttributeInvalidVersion 0.00
Success testParseVersion 0.00
Success testParseDomainEqualsHost 0.00
Success testParseWithIllegalDomain1 0.00
Success testParseWithIllegalDomain2 0.00
Success testParseWithIllegalDomain3 0.00
Success testParseWithIllegalDomain4 0.00
Success testSecondDomainLevelCookieMatch 0.00
Success testParseWithWrongPath 0.00
Success testInvalidDomainWithSimpleHostName 0.00
Success testRFC2109CookieFormatting 0.00
Success testRFC2109CookiesFormatting 0.00
Success testCookieNullDomainNullPathFormatting 0.00
Success testFormatInvalidCookie 0.00
Success testParseVersion 0.00
Success testParseInvalidParams 0.00
Success testParsePath 0.00
Success testParsePathDefault 0.00
Success testParseNullPath 0.00
Success testParseBlankPath 0.00
Success testParseDomain 0.00
Success testParseDomainDefault 0.00
Success testParseNullDomain 0.00
Success testParseBlankDomain 0.00
Success testParsePort 0.00
Success testParsePortDefault 0.00
Success testParseNullPort 0.00
Success testParseBlankPort 0.00
Success testParseInvalidPort 0.00
Success testParseNegativePort 0.00
Success testParseNameValue 0.00
Success testParseNullVersion 0.00
Success testParseNegativeVersion 0.00
Success testParseMaxage 0.00
Success testParseMaxageDefault 0.00
Success testParseNullMaxage 0.00
Success testParseNegativeMaxage 0.00
Success testParseSecure 0.00
Success testParseDiscard 0.00
Success testParseOtherAttributes 0.00
Success testCookiesWithComma 0.00
Success testValidateNoDomain 0.00
Success testValidateDomainLeadingDot 0.00
Success testValidateDomainEmbeddedDot 0.00
Success testValidateDomainLocal 0.00
Success testValidateDomainEffectiveHost 0.00
Success testValidateDomainIllegal 0.00
Success testValidatePath 0.00
Success testValidateCookieName 0.00
Success testValidatePort 0.00
Success testValidateVersion 0.00
Success testMatchPath 0.00
Success testMatchDomain 0.00
Success testMatchDomainLocal 0.00
Success testMatchPort 0.00
Success testCookieExpiration 0.00
Success testCookieSecure 0.00
Success testRFC2965CookieFormatting 0.00
Success testRFC2965CookiesFormatting 0.00
Success testCompatibilityWithSetCookie 0.00
Success testParseAttributeInvalidAttrib 0.00
Success testParseAttributeInvalidCookie 0.00
Success testParseRelativePath 0.00
Success testParseWithNullHost 0.00
Success testParseWithBlankHost 0.00
Success testParseWithNullPath 0.00
Success testParseWithBlankPath 0.00
Success testParseWithNegativePort 0.00
Success testParseWithInvalidHeader1 0.00
Success testCookieWithComma 0.00
Success testParseAttributeInvalidCookieExpires 0.00
Success testParseAbsPath 0.00
Success testParseAbsPath2 0.00
Success testParseWithIllegalNetscapeDomain1 0.00
Success testParseWithWrongNetscapeDomain2 0.00
Success testNetscapeCookieFormatting 0.00
Success testNetscapeCookieExpireAttribute 0.00
Success testNetscapeCookieExpireAttributeNoTimeZone 0.00
Success testKeepCloverHappy 0.00
Success testIgnoreCookies 0.00
Success testRegisterNullPolicyId 0.00
Success testRegisterNullPolicy 0.00
Success testUnregisterNullPolicy 0.00
Success testGetPolicyNullId 0.00
Success testRegisterUnregister 0.00
Success testGetDefaultPolicy 0.00
Success testFourDigitYear 0.00
Success testThreeDigitYear 0.00
Success testTwoDigitYear 0.00
Success testUnequality1 0.00
Success testUnequality2 0.00
Success testEquality1 0.00
Success testEquality2 0.00
Success testEquality3 0.00
Success testEquality4 0.00
Success testCookieVersionSupportHeader1 0.05
Success testCookieVersionSupportHeader2 0.04
Success testCookieVersionSupportHeader3 0.04
Success testSetCookieVersionMix 0.00
Success testCredentialConstructors 0.00
Success testCredentialEquals 0.00
Success testParsingChallenge 0.00
Success testChallengeSelection 0.00
Success testInvalidChallenge 0.00
Success testUnsupportedChallenge 0.00
Success testChallengeProcessing 0.00
Success testInvalidChallengeProcessing 0.00
Success testBasicAuthenticationWithNoCreds 0.00
Success testBasicAuthenticationWithNoCredsRetry 0.08
Success testBasicAuthenticationWithNoRealm 0.00
Success testBasicAuthenticationWith88591Chars 0.00
Success testBasicAuthenticationWithDefaultCreds 0.04
Success testBasicAuthentication 0.04
Success testBasicAuthenticationWithInvalidCredentials 0.05
Success testBasicAuthenticationWithMutlipleRealms1 0.04
Success testBasicAuthenticationWithMutlipleRealms2 0.04
Success testPreemptiveAuthorizationTrueWithCreds 0.00
Success testPreemptiveAuthorizationTrueWithoutCreds 0.00
Success testCustomAuthorizationHeader 0.00
Success testHeadBasicAuthentication 0.01
Success testPostBasicAuthentication 0.05
Success testPutBasicAuthentication 0.04
Success testPreemptiveAuthorizationFailure 0.00
Success testBasicAuthenticationWithNoCreds 0.01
Success testBasicAuthenticationWithNoCredsRetry 0.09
Success testBasicAuthenticationWithNoRealm 0.00
Success testBasicAuthenticationWith88591Chars 0.00
Success testBasicAuthenticationWithDefaultCreds 0.05
Success testBasicAuthentication 0.04
Success testBasicAuthenticationWithInvalidCredentials 0.05
Success testBasicAuthenticationWithMutlipleRealms1 0.05
Success testBasicAuthenticationWithMutlipleRealms2 0.05
Success testPreemptiveAuthorizationTrueWithCreds 0.01
Success testPreemptiveAuthorizationTrueWithoutCreds 0.00
Success testCustomAuthorizationHeader 0.01
Success testHeadBasicAuthentication 0.05
Success testPostBasicAuthentication 0.09
Success testPutBasicAuthentication 0.09
Success testPreemptiveAuthorizationFailure 0.01
Success testDigestAuthenticationWithNoRealm 0.00
Success testDigestAuthenticationWithNoRealm2 0.00
Success testDigestAuthenticationWithDefaultCreds 0.00
Success testDigestAuthentication 0.00
Success testDigestAuthenticationWithQueryStringInDigestURI 0.00
Success testDigestAuthenticationWithMultipleRealms 0.00
Success testDigestAuthenticationMD5Sess 0.00
Success testDigestAuthenticationMD5SessNoQop 0.00
Success testDigestAuthenticationMD5SessInvalidQop 0.00
Success testDigestAuthenticationWithStaleNonce 0.10
Success testNTLMAuthenticationResponse1 0.00
Success testNTLMAuthenticationResponse2 0.00
Success testNTLMAuthenticationRetry 0.09
Success testPreemptiveAuthorization 0.00
Success testBasicRedirect300 0.00
Success testBasicRedirect301 0.10
Success testBasicRedirect302 0.10
Success testBasicRedirect303 0.10
Success testBasicRedirect304 0.00
Success testBasicRedirect305 0.00
Success testBasicRedirect307 0.10
Success testNoRedirect 0.01
Success testMaxRedirectCheck 0.02
Success testCircularRedirect 0.02
Success testPostRedirect 0.00
Success testRelativeRedirect 0.04
Success testRejectRelativeRedirect 0.00
Success testRejectBogusRedirectLocation 0.00
Success testRejectInvalidRedirectLocation 0.00
Success testCrossSiteRedirect 0.00
Success testRedirectWithCookie 0.10
Success testBasicRedirect300 0.00
Success testBasicRedirect301 0.11
Success testBasicRedirect302 0.11
Success testBasicRedirect303 0.11
Success testBasicRedirect304 0.00
Success testBasicRedirect305 0.01
Success testBasicRedirect307 0.11
Success testNoRedirect 0.00
Success testMaxRedirectCheck 0.02
Success testCircularRedirect 0.02
Success testPostRedirect 0.04
Success testRelativeRedirect 0.05
Success testRejectRelativeRedirect 0.00
Success testRejectBogusRedirectLocation 0.00
Success testRejectInvalidRedirectLocation 0.00
Success testCrossSiteRedirect 0.00
Success testRedirectWithCookie 0.11
Success testConstructThenClose 0.00
Success testConnTimeoutRelease 0.01
Success testConnTimeout 0.01
Success testForIllegalStateExceptions 0.00
Success testReleaseConnection 0.02
Success testConnectMethodFailureRelease 0.21
Success testGetConnection 0.00
Success testDroppedThread 1.26
Success testWriteRequestReleaseConnection 0.00
Success testResponseAutoRelease 0.00
Success testConnectionReclaiming 0.00
Success testShutdownAll 0.00
Success testShutdown 0.00
Success testMaxConnections 0.10
Success testMaxConnectionsPerHost 0.31
Success testHostReusePreference 0.20
Success testMaxConnectionsPerServer 0.01
Success testDeleteClosedConnections 0.00
Success testWaitingThreadInterrupted 0.50
Success testReclaimUnusedConnection 0.30
Success testGetFromMultipleThreads 0.10
Success testTimeout 1.00
Success testConnPersisenceHTTP10 0.10
Success testConnPersisenceHTTP11 0.05
Success testConnClose 0.01
Success testConnKeepAlive 0.10
Success testRequestConnClose 0.00
Success testProxyConnClose 0.01
Success testHandler 0.51
Success testTimeoutThread 0.51
Success testAbortMethod 0.51
Success testAbortedMethodExecute 0.00
Success testDefaultHeaders 0.05
Success testDefaults 0.04
Success testTunnellingParamsAgentLevel 0.47
Success testTunnellingParamsHostLevel 0.45
Success testTunnellingParamsHostHTTP10AndMethodHTTP11 0.42
Success testVirtualHostHeader 0.01
Success testNoVirtualHostHeader 0.00
Success testRedirectWithVirtualHost 0.21
Success testRelativeURLHitWithDefaultHost 0.00
Success testRelativeURLHitWithoutDefaultHost 0.00
Success testAbsoluteURLHitWithoutDefaultHost 0.00
Success testAbsoluteURLOverridesClientDefaultHost 0.03
Success testAbsoluteURLOverridesDefaultHostParam 0.13
Success testClientClonesHostConfiguration 0.00
Success testIPv4Address 0.00
Success testUrl 0.00
Success testRelativeURIConstructor 0.01
Success testTestURIAuthorityString 0.00
Success testTestHttpUrlAuthorityString 0.00
Success testTestHttpsUrlAuthorityString 0.00
Success testURIEscaping 0.00
Success testBug578 0.00
Success testVariousCharacters 0.00
Success testRelativeWithScheme 0.00
Success testRelativeWithDoubleSlash 0.00
Success testGetPath 0.00
Success testGetQueryString 0.00
Success testGetPath 0.00
Success testGetQueryString 0.00
Success testEnclosedEntityAutoLength 0.00
Success testEnclosedEntityExplicitLength 0.00
Success testEnclosedEntityChunked 0.00
Success testEnclosedEntityChunkedHTTP1_0 0.00
Success testEnclosedEntityRepeatable 0.04
Success testEnclosedEntityNonRepeatable 0.00
Success testEnclosedEntityNegativeLength 0.00
Success testEnclosedEntityNegativeLengthHTTP1_0 0.00
Success testEmptyPostMethod 0.13
Success testPostParametersEncoding 0.00
Success testPostSetRequestBody 0.00
Success testParametersBodyToParamServlet 0.01
Success testStringBodyToParamServlet 0.00
Success testStringBodyToBodyServlet 0.00
Success testAddParametersToParamServlet 0.00
Success testAddRemoveParametersToParamServlet 0.00
Success testRemoveParameterReturnValue 0.00
Success testAddParameterFollowedBySetParameter 0.00
Success testFilePartResendsFileData 0.01
Success testStringPartResendsData 0.00
Success testFilePartNullFileResendsData 0.00
Success testPostStringPart 0.01
Success testPostFilePart 0.00
Success testPostFilePartUnknownLength 0.00
Success testPostStringPart 0.01
Success testPostFilePart 0.01
Success testPostFilePartUnknownLength 0.00
Success testNoncompliantPostMethodString 0.00
Success testNoncompliantStatusLine 0.00
Success testNoncompliantHeadWithResponseBody 0.00
Success testNoncompliantHeadStrictMode 0.00
Success testMalformed304Response 0.00
Success testMalformed204Response 0.00
Success testSimpleGet 0.00
Success testGetHostAuthConnKeepAlive 0.06
Success testGetHostAuthConnClose 0.11
Success testGetHostInvalidAuth 0.05
Success testGetInteractiveHostAuthConnKeepAlive 0.09
Success testGetInteractiveHostAuthConnClose 0.21
Success testGetProxyAuthHostAuthConnKeepAlive 0.09
Success testGetAuthProxy 0.04
Success testGetProxyAuthHostAuthConnClose 0.11
Success testGetProxyAuthHostInvalidAuth 0.10
Success testGetInteractiveProxyAuthHostAuthConnKeepAlive 0.18
Success testGetInteractiveProxyAuthHostAuthConnClose 0.26
Success testSimplePost 0.01
Success testPostHostAuthConnKeepAlive 0.09
Success testPostHostAuthConnClose 0.11
Success testPostHostInvalidAuth 0.09
Success testPostInteractiveHostAuthConnKeepAlive 0.18
Success testPostInteractiveHostAuthConnClose 0.21
Success testPostAuthProxy 0.04
Success testPostProxyAuthHostAuthConnKeepAlive 0.13
Success testPostProxyAuthHostAuthConnClose 0.11
Success testPostProxyAuthHostInvalidAuth 0.13
Success testPostInteractiveProxyAuthHostAuthConnKeepAlive 0.26
Success testPostInteractiveProxyAuthHostAuthConnClose 0.26
Success testPreemptiveAuthProxy 0.00
Success testGetProxyAuthHostAuthHTTP10 0.11
Success testSimpleGet 0.48
Success testGetHostAuthConnKeepAlive 0.56
Success testGetHostAuthConnClose 0.69
Success testGetHostInvalidAuth 0.63
Success testGetInteractiveHostAuthConnKeepAlive 0.58
Success testGetInteractiveHostAuthConnClose 0.93
Success testGetProxyAuthHostAuthConnKeepAlive 0.60
Success testGetAuthProxy 0.46
Success testGetProxyAuthHostAuthConnClose 0.73
Success testGetProxyAuthHostInvalidAuth 0.52
Success testGetInteractiveProxyAuthHostAuthConnKeepAlive 0.64
Success testGetInteractiveProxyAuthHostAuthConnClose 0.80
Success testSimplePost 0.63
Success testPostHostAuthConnKeepAlive 0.59
Success testPostHostAuthConnClose 0.68
Success testPostHostInvalidAuth 0.61
Success testPostInteractiveHostAuthConnKeepAlive 0.57
Success testPostInteractiveHostAuthConnClose 0.94
Success testPostAuthProxy 0.47
Success testPostProxyAuthHostAuthConnKeepAlive 0.63
Success testPostProxyAuthHostAuthConnClose 0.68
Success testPostProxyAuthHostInvalidAuth 0.53
Success testPostInteractiveProxyAuthHostAuthConnKeepAlive 0.58
Success testPostInteractiveProxyAuthHostAuthConnClose 0.78
Success testPreemptiveAuthProxy 0.55
Success testGetProxyAuthHostAuthHTTP10 0.56
Success testAuthProxyWithRedirect 0.11
Success testAuthProxyWithCrossSiteRedirect 0.11
Success testPreemptiveAuthProxyWithCrossSiteRedirect 0.20

commons-httpclient-3.1/docs/license.html100644 0 0 35211 10661532631 15620 0ustar 0 0 HttpClient - Project License

Project License

                                 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

commons-httpclient-3.1/docs/logging.html100644 0 0 44656 10661532631 15641 0ustar 0 0 HttpClient - HttpClient Logging Practices

Logging Practices

Being a library HttpClient is not to dictate which logging framework the user has to use. Therefore HttpClient utilizes the logging interface provided by the Commons Logging package. Commons Logging provides a simple and generalized log interface to various logging packages. By using Commons Logging, HttpClient can be configured for a variety of different logging behaviours. That means the user will have to make a choice which logging framework to use. By default Commons Logging supports the following logging frameworks:

By implementing some simple interfaces Commons Logging can be extended to support basically any other custom logging framework. Commons Logging tries to automatically discover the logging framework to use. If it fails to select the expected one, you must configure Commons Logging by hand. Please refer to the Commons Logging documentation for more information.

HttpClient performs two different kinds of logging: the standard context logging used within each class, and wire logging.

Context Logging

Context logging contains information about the internal operation of HttpClient as it performs HTTP requests. Each class has its own log named according to the class's fully qualified name. For example the class HttpClient has a log named org.apache.commons.httpclient.HttpClient. Since all classes follow this convention it is possible to configure context logging for all classes using the single log named org.apache.commons.httpclient.

Wire Logging

The wire log is used to log all data transmitted to and from servers when executing HTTP requests. This log should only be enabled to debug problems, as it will produce an extremely large amount of log data, some of it in binary format.

Because the content of HTTP requests is usually less important for debugging than the HTTP headers, these two types of data have been separated into different wire logs. The content log is httpclient.wire.content and the header log is httpclient.wire.header.

Configuration Examples

Commons Logging can delegate to a variety of loggers for processing the actual output. Below are configuration examples for Commons Logging, Log4j and java.util.logging.

Commons Logging Examples

Commons Logging comes with a basic logger called SimpleLog. This logger writes all logged messages to System.err. The following examples show how to configure Commons Logging via system properties to use SimpleLog.

Note: The system properties must be set before a reference to any Commons Logging class is made.

Enable header wire + context logging - Best for Debugging

System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");

System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");

System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug");

System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");

Enable full wire(header and content) + context logging

System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");

System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");

System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");

System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");

Enable just context logging

System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");

System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");

System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");

Log4j Examples

The simplest way to configure Log4j is via a log4j.properties file. Log4j will automatically read and configure itself using a file named log4j.properties when it's present at the root of the application classpath. Below are some Log4j configuration examples.

Note: Log4j is not included in the HttpClient distribution.

Enable header wire + context logging - Best for Debugging

log4j.rootLogger=INFO, stdout



log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p [%c] %m%n



log4j.logger.httpclient.wire.header=DEBUG

log4j.logger.org.apache.commons.httpclient=DEBUG

Enable full wire(header and content) + context logging

log4j.rootLogger=INFO, stdout



log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p [%c] %m%n



log4j.logger.httpclient.wire=DEBUG

log4j.logger.org.apache.commons.httpclient=DEBUG

Log wire to file + context logging

log4j.rootLogger=INFO



log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p [%c] %m%n



log4j.appender.F=org.apache.log4j.FileAppender

log4j.appender.F.File=wire.log

log4j.appender.F.layout=org.apache.log4j.PatternLayout

log4j.appender.F.layout.ConversionPattern =%5p [%c] %m%n



log4j.logger.httpclient.wire=DEBUG, F

log4j.logger.org.apache.commons.httpclient=DEBUG, stdout

Enable just context logging

log4j.rootLogger=INFO, stdout



log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p [%c] %m%n



log4j.logger.org.apache.commons.httpclient=DEBUG

Note that the default configuration for Log4J is very inefficient as it causes all the logging information to be generated but not actually sent anywhere. The Log4J manual is the best reference for how to configure Log4J. It is available at http://logging.apache.org/log4j/docs/manual.html

java.util.logging Examples

Since JDK 1.4 there has been a package java.util.logging that provides a logging framework similar to Log4J. By default it reads a config file from $JAVA_HOME/jre/lib/logging.properties which looks like this (comments stripped):

handlers=java.util.logging.ConsoleHandler

.level=INFO

java.util.logging.FileHandler.pattern = %h/java%u.log

java.util.logging.FileHandler.limit = 50000

java.util.logging.FileHandler.count = 1

java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter

java.util.logging.ConsoleHandler.level = INFO

java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

com.xyz.foo.level = SEVERE

To customize logging a custom logging.properties file should be created in the project directory. The location of this file must be passed to the JVM as a system property. This can be done on the command line like so:
$JAVA_HOME/java -Djava.util.logging.config.file=$HOME/myapp/logging.properties -classpath $HOME/myapp/target/classes com.myapp.Main
Alternatively LogManager#readConfiguration(InputStream) can be used to pass it the desired configuration.

Enable header wire + context logging - Best for Debugging

.level=INFO



handlers=java.util.logging.ConsoleHandler

java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter



httpclient.wire.header.level=FINEST

org.apache.commons.httpclient.level=FINEST

Enable full wire(header and content) + context logging

.level=INFO



handlers=java.util.logging.ConsoleHandler

java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter



httpclient.wire.level=FINEST

org.apache.commons.httpclient.level=FINEST

Enable just context logging

.level=INFO



handlers=java.util.logging.ConsoleHandler

java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter



org.apache.commons.httpclient.level=FINEST

More detailed information is available from the Java Logging documentation.


commons-httpclient-3.1/docs/mail-lists.html100644 0 0 15113 10661532631 16253 0ustar 0 0 HttpClient - Mailing Lists

Mailing Lists

These are the mailing lists that have been established for this project. For each list, there is a subscribe, unsubscribe, and an archive link.

List Name Subscribe Unsubscribe Post Archive Other Archives
HttpComponents Developer List Subscribe Unsubscribe Not Available Archive
HttpClient User List Subscribe Unsubscribe Not Available Archive

commons-httpclient-3.1/docs/maven-reports.html100644 0 0 31773 10661532631 17011 0ustar 0 0 HttpClient - Project Reports

Maven Generated Reports

This document provides an overview of the various reports that are automatically generated by Maven . Each report is briefly described below.

Overview

Document Description
Change Log Report on the source control changelog.
Developer Activity Report on the amount of developer activity.
File Activity Report on file activity.
JavaDocs JavaDoc API documentation.
JavaDoc Report Report on the generation of JavaDoc.
JavaDoc Warnings Report Formatted report of JavaDoc warnings.
Metrics Report on source code metrics.
Unit Tests Report on the results of the unit tests.
Source Xref A set of browsable cross-referenced sources.
Test Xref A set of browsable cross-referenced test sources.
Project License Displays the primary license for the project.
Task List Report on tasks specified in the source code.

commons-httpclient-3.1/docs/methods.html100644 0 0 17063 10661532631 15646 0ustar 0 0 HttpClient - HttpClient Methods

Introduction

These documents provide a brief introduction to using the methods provided by HttpClient. The information here does not cover all the possible options, but covers enough of the basics to get you up and running. For more information on the available options, refer to the API Reference.

The examples on the following pages are not complete and are only used to highlight the important features that are unique to each method. For complete examples, please refer to the sample code.

Overview

Document Description
Options The OPTIONS method represents a request for information about the communication options available.
Get The GET method means retrieve whatever information is identified by the requested URL. Also refer to the tutorial.
Head The HEAD method is identical to GET except that the server must not return a message-body in the response. This method can be used for obtaining metainformation about the document implied by the request without transferring the document itself.
Post The POST method is used to request that the origin server accept the data enclosed in the request as a new child of the request URL. POST is designed to allow a uniform method to cover a variety of functions such as appending to a database, providing data to a data-handling process or posting to a message board.
Multipart Post The multipart post method is identical to the POST method, except that the request body is separated into multiple parts. This method is generally used when uploading files to the server.
Put The PUT method requests that the enclosed document be stored under the supplied URL. This method is generally disabled on publicly available servers because it is generally undesireable to allow clients to put new files on the server or to replace existing files.
Delete The DELETE method requests that the server delete the resource identified by the request URL. This method is generally disabled on publicly available servers because it is generally undesireable to allow clients to delete files on the server.
Trace The TRACE method is used to invoke a remote, application-layer loop-back of the request message. This allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information.

commons-httpclient-3.1/docs/methods/delete.html100644 0 0 14232 10661532631 17103 0ustar 0 0 HttpClient - Delete Method

Introduction

The delete method requests that the origin server delete the resource identified by the request URL. This method may be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server should not indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.

A successful response should be 200 (OK) if the response includes a response body describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include a response body.

If the request passes through a cache and the URL identifies one or more currently cached entities, those entries should be treated as stale. Responses to this method are not cacheable.

Typical Usage

The delete method is used by supplying a URL to delete the resource at and reading the response from the server.

        DeleteMethod delete = new DeleteMethod("http://jakarata.apache.org");
        // execute the method and handle any error responses.
        ...
        // Ensure that if there is a response body it is read, then release the
        // connection.
        ...
        delete.releaseConnection();
      
      

Common Problems

The DELETE method is not widely supported on public servres due to security concerns and generally FTP is used to delete files on the webserver. Before executing a DELETE method, it may be worth checking that DELETE is supported using the OPTIONS method.

RFC Section

The delete method is defined in section 9.7 of RFC2616.


commons-httpclient-3.1/docs/methods/get.html100644 0 0 15561 10661532631 16426 0ustar 0 0 HttpClient - Get Method

Introduction

The GET method retrieves whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.

The semantics of the GET method change to a "conditional GET" if the request message includes an If-ModifiedSince, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s). This reduces unnecessary network usage by allowing cached entities to be refreshed without requiring multiple requests or transferring data already held by the client.

If a Range header field is included, the request is for only the part of the entity specified by the range header. This allows partially retrieved entities to be completed without transferring previously received data.

Typical Usage

Typically the get method is used to download a document from a web server. This can be achieved with the method, getResponseBody, getResponseBodyAsStream or getResponseBodyAsString. Of these methods, getResponseBodyAsStream is generally the best choice as it avoids unnessecary buffering of all data into memory before processing.

See the tutorial for a full example of using the GET method. There are also a number of examples in the sample code.

        GetMethod get = new GetMethod("http://jakarta.apache.org");
        // execute method and handle any error responses.
        ...
        InputStream in = get.getResponseBodyAsStream();
        // Process the data from the input stream.
        get.releaseConnection();
        
      

Common Problems

The most common mistake when using the GET method is failing to read the entire response body even if an error code, redirect or any other response status is received. As with all methods, one must also be sure to call method.releaseConnection(), regardless of the response code received.

RFC Section

The get method is defined in section 8.1 of RFC1945 and similarly defined for HTTP 1.1 in section 9.3 of RFC2616.


commons-httpclient-3.1/docs/methods/head.html100644 0 0 14134 10661532631 16543 0ustar 0 0 HttpClient - Head Method

Introduction

The HEAD method is identical to the GET method except that the server must not return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request should be identical to the information sent in response to a GET request. This allows a client to obtain meta-information about a resource without actually transferring the resource itself.

The head method is often used for testing hyperlinks, accessibility and for determining if a document has been recently modifed.

When your program is implementing caching, it is important to note that if the HEAD response indicates that the cached entity differs from the current entity, such as by a change in the Content-Length, Content-MD5, ETag or Last-Modified, the cache must treat the cached entry as stale.

Typical Usage

Typically the head method is used to retrieve the meta-information for a resource, perhaps to check if the resource has been modifed. There are no methods specific to HeadMethod as the headers can be retreived using getResponseHeaders() as with any other method.

        HeadMethod head = new HeadMethod("http://jakarta.apache.org");
        // execute the method and handle any error responses.
        ...
        // Retrieve all the headers.
        Header[] headers = head.getResponseHeaders();

        // Retrieve just the last modified header value.
        String lastModified =
            head.getResponseHeader("last-modified").getValue();
        
      

Common Problems

None.

RFC Section

The head method is defined in section 8.2 of RFC1945 and similarly redefined for HTTP 1.1 in section 9.4 of RFC2616.


commons-httpclient-3.1/docs/methods/multipartpost.html100644 0 0 17722 10661532631 20577 0ustar 0 0 HttpClient - Multipart Post Method

Introduction

The multipart post method is a different request body format for a POST method. The media-type multipart/form-data follows the rules of all multipart MIME data streams as outlined in RFC 1521. It is intended for use in returning the data that comes about from filling out a form, particularly when the form requires binary data to be uploaded such as the contents of a file.

Typical Usage

Like for the standard POST method, there are two main steps to using the multipart post method, setting the request data and retrieving the response data.

The request data is specified by adding parameters to the method, these are defined by the org.apache.commons.httpclient.methods.multipart.Part class and it's various subclasses. A description of each of these is below.

Part Description
StringPart The string part is a simple part that takes a name for the part and the value of the part as a string. This is typically used for standard form elements such as a text area within a multipart form.
FilePart The file part is actually a very generic type of part that can contain any type of data and specify a name, content type and charset for the data. In it's simplest form, it takes just a name and a File object and uploads the contents of the file, however it can also be passed a PartSource object to upload. See the part source section below for more information.

Part Sources

The PartSource interface provides a generic container for providing data to the FilePart class. There are two concrete implementations of PartSource provided with HttpClient (described below) but you can also provide your own implementation easily. The input for the multipart post could come from anywhere, perhaps it's being received from another server or process, and all that the PartSource class needs to be able to do is provide the length of the data that will be provided, an input stream to retrieve the data from and a file name (or some name identifying the data).

The two concrete implementations of PartSource are FilePartSource and ByteArrayPartSource. FilePartSource simply takes a File to upload whereas ByteArrayPartSource allows for the case where the data has been cached in memory and takes a file name and a byte array to upload.

Common Problems

The most common problem people run into with multipart uploads is that the length of the data must be known before hand. If the length of the data can not be determined in advance, it needs to be cached either in memory or to a file and then uploaded using either ByteArrayPartSource or FilePartSource. The HTTP specification does not allow for POST data to be of an unknown length.

RFC Section

The multipart form data uses the POST method from the HTTP standard which is defined in section 8.3 of RFC1945 and similarly redefined for HTTP 1.1 in section 9.5 of RFC2616.

The multipart/form-data MIME type used to format the body of the request is defined in RFC1867.


commons-httpclient-3.1/docs/methods/options.html100644 0 0 12236 10661532631 17336 0ustar 0 0 HttpClient - Options Method

Introduction

The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the request URL. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

Typical Usage

Typically the options method is used to determine what methods are supported by the server, and this is accomodated by the getAllowedMethods function.

        OptionsMethod options = new OptionsMethod("http://jakarta.apache.org");
        // execute method and handle any error responses.
        ...
        Enumeration allowedMethods = options.getAllowedMethods();
        options.releaseConnection();
      
      

Common Problems

None.

RFC Section

The options method is defined in section 9.2 of RFC2616.


commons-httpclient-3.1/docs/methods/post.html100644 0 0 16307 10661532631 16633 0ustar 0 0 HttpClient - Post Method

Introduction

The post method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. Essentially this means that the POST data will be stored by the server and usually will be processed by a server side application.

Post is designed to allow a uniform method to cover the following functions:

  • Annotation of existing resources.
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles.
  • Providing a block of data, such as the result of submitting a form, to a data-handling process.
  • Extending a database through an append operation.

It is generally expected that a POST request will have some side effect on the server such as writing to a database, and the HTTP specification suggests that user agents represent user actions which result in a POST request in a special way, so that the user is made aware of the fact that a possibly unsafe action is being requested. This however, is not a requirement.

Typical Usage

There are two major steps to using the POST method, firstly providing the data for the request and secondly reading the response from the server.

The request data is supplied by one of the variants of setRequestBody which can either take an InputStream an array of NameValuePair objects or a String. The simplest form is to pass in a NameValuePair and allow HttpClient to format the request body according to the standard, however this requires that the full content be stored in memory which may not be desireable. In this case, passing in an InputStream would be more appropriate.

The POST response body can be read using any of the getResponseBody* methods much like the GET method.

        PostMethod post = new PostMethod("http://jakarata.apache.org/");
        NameValuePair[] data = {
          new NameValuePair("user", "joe"),
          new NameValuePair("password", "bloggs")
        };
        post.setRequestBody(data);
        // execute method and handle any error responses.
        ...
        InputStream in = post.getResponseBodyAsStream();
        // handle response.
        
      

Common Problems

The most common problem when using the post method is not reading the entire response body and calling releaseConnection regardless of the response received from the server or whether or not the response body is useful to your application.

RFC Section

The post method is defined in section 8.3 of RFC1945 and similarly redefined for HTTP 1.1 in section 9.5 of RFC2616.


commons-httpclient-3.1/docs/methods/put.html100644 0 0 15350 10661532631 16453 0ustar 0 0 HttpClient - Put Method

Introduction

The PUT method requests that the enclosed entity be stored under the supplied URL. If the URL refers to an already existing resource, the enclosed entity should be considered as a modified version of the one residing on the origin server. If the URL does not point to an existing resource, and that URL is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URL.

If the request passes through a cache and the URL identifies one or more currently cached entities, those entries should be treated as stale. Responses to this method are not cacheable.

The fundamental difference between POST and PUT requests is reflected in the different meaning of the request URL. The URL in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URL in a PUT request identifies the entity enclosed with the request -- the user agent knows what URL is intended and the server must not attempt to apply the request to some other resource.

Unless otherwise specified for a particular entity-header, the entity-headers in the PUT request should be applied to the resource created or modified by the PUT.

Typical Usage

The put method is very simple, it takes a URL to put to and requires that the body of the request method be set to the data to upload. The body can be set with an input stream or a string.

        PutMethod put = new PutMethod("http://jakarta.apache.org");
        put.setRequestBody(new FileInputStream("UploadMe.gif"));
        // execute the method and handle any error responses.
        ...
        // Handle the response.  Note that a successful response may not be
        // 200, but may also be 201 Created, 204 No Content or any of the other
        // 2xx range responses.
      
      

Common Problems

The PUT method is not widely supported on public servers due to security concerns and generally FTP is used to upload new and modified files to the webserver. Before executing a PUT method on a URL, it may be worth checking that PUT is supported using the OPTIONS method.

RFC Section

The put method is defined in section 9.6 of RFC2616.


commons-httpclient-3.1/docs/methods/trace.html100644 0 0 13121 10661532631 16733 0ustar 0 0 HttpClient - Trace Method

Introduction

The TRACE method is primarily used for debugging and testing purposes, and simply requests that the server echo back the request it received. This can be useful for identifying any changes to the request that is made by proxies.

The TRACE method is used to invoke a remote, application-layer loop-back of the request message. The final recipient of the request should reflect the message received back to the client as the entity-body of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive a max-Forwards value of zero (0) in the request (see section 14.31 of RFC2616).

Typical Usage

The trace method simply requires providing a URL and reading the response received. Additional headers can be added with the addRequestHeader method as with any other HttpMethod.

        TraceMethod trace = new TraceMethod("http://jakarata.apache.org");
        // Execute the method and handle any errors.
        ...
        // Read the response body.
        String request = trace.getResponseBodyAsString();
        trace.releaseConnection();
      
      

Common Problems

None.

RFC Section

The trace method is defined in section 9.6 of RFC2616.


commons-httpclient-3.1/docs/news.html100644 0 0 75556 10661532631 15172 0ustar 0 0 HttpClient - HttpClient News

22 August 2007 - HttpClient 3.1 released

HttpClient 3.1 has been released. This version adds a number improvements to the connection management code and fixes a number of minor bugs. It is likely to be the last non bug fixing release of the HttpClient 3.x codeline.

16 March 2007 - HttpClient 3.1-rc1 released

HttpClient 3.1-rc1 has been released. This version fixes a number of issues found since 3.1-beta1. This release is expected to be the last one before HttpClient 3.1 goes final.

30 October 2006 - HttpClient 3.1-beta1 released

HttpClient 3.1-beta1 has been released. This version finalizes the RFC 2965 cookie management API and adds a number of improvements to the HTTP connection management classes.

26 June 2006 - HttpClient 3.1-alpha1 released

HttpClient 3.1-alpha1 has been released. This version adds support for the RFC 2965 cookie management (also known as Cookie2 or port sensitive cookies). All upstream projects dependent on HttpClient are strongly encouraged to review the new API and test new features for compatibility with their products.

12 May 2006 - HttpClient issue tracking migrated to Jira

HttpClient issue tracking has migrated from Bugzilla to Jira. Please do not enter new bug reports and update exiting ones in Bugzilla. HttpComponents project will be using Jira to manage HttpClient related issues as of today. Please use this project in Jira to report new issues against HttpClient and search for reported ones. All existing issue reports can be accessed in Jira by their original Bugzilla bug id.

08 May 2006 - HttpClient 3.0.1 released

HttpClient 3.0.1 has been released. This version fixes a number of bugs found since the release of 3.0. All HttpClient users are encouraged to upgrade.

27 February 2006 - HttpClient 2.x codebase declared 'End of Life'

HttpClient 2.x will no longer be supported. There will be no more HttpClient 2.x releases

19 December 2005 - HttpClient 3.0 released

The Jakarta Commons HttpClient project is pleased to announce the release of HttpClient 3.0. This release fixes all of the bugs discovered in RC4. As before, we strongly recommend that all users upgrade to HttpClient 3.0. Please download and enjoy.

HttpClient 3.0 provides the following new features:

  • Architecture
    • New preference architecture
    • Improved exception handling framework
    • Granular non-standards configuration and tracking
    • Improved HTTP Version configuration and tracking
    • Support for streaming entities
    • Support for tunneled HTTP proxies via the ProxyClient
    • Ability to abort execution of HTTP methods
  • Connection management
    • Support for closing idle connections
    • Support for JDK1.4 connect timeout through reflection
    • Support for connection manager shutdown
  • Authentication
    • Improved authentication framework
    • Plug-in mechanism for authentication modules
    • Interactive authentication support
    • Alternate authentication support
  • Cookie management
    • Cookie specification plug-in mechanism
    • 'Ignore cookies' cookie policy
    • Improved Netscape cookie support
  • Redirects
    • Cross-site redirect support

11 October 2005 - HttpClient 3.0 RC4 released

The Jakarta Commons HttpClient project is pleased to announce the fourth and hopefully final release candidate of HttpClient 3.0. RC4 fixes a number of hard to find bugs left over in the previous release. We strongly recommend that all users upgrade to HttpClient 3.0 RC4. Please download and enjoy.

26 June 2005 - HttpClient 3.0 RC3 released

The Jakarta Commons HttpClient project is pleased to announce the third release candidate of HttpClient 3.0. RC3 has undergone quite a lot of user testing and it fixes a number of bugs from RC2. We strongly recommend that all users upgrade to HttpClient 3.0 RC3. Please download and enjoy.

09 April 2005 - HttpClient 3.0 RC2 released

The Jakarta Commons HttpClient project is pleased to announce the second release candidate of HttpClient 3.0. Several minor issues have been fixed since RC1 and HttpClient 3.0 has made significant progess towards the final release. We are confident HttpClient 3.0 is ready to replace HttpClient 2.0 as a production quality release. We strongly recommend upgrading to HttpClient 3.0. Please download and enjoy.

06 February 2005 - HttpClient 3.0 RC1 released

We are pleased to announce the HttpClient 3.0 RC1 release. The 3.0 API is frozen and all known bugs have been fixed. Assuming no major problems are discovered in RC1 a final 3.0 release will follow shortly. We strongly encourage all current HttpClient users to start migrating. Please download and enjoy.

30 January 2005 - Source control switched to Subversion

Along with the rest of the Jakarta Commons projects, HttpClient's version control has been switched to Subversion. Please see the links below for more information:

21 November 2004 - HttpClient 3.0 beta1 released

We are pleased to announce the first beta release of HttpClient 3.0. As of this release the 3.0 API is frozen. We will now focus on creating additional documentation and test cases. All current HttpClient 2.0 users are strongly encouraged to migrate to 3.0. As always we encourage suggestions and bug reports. Please download and enjoy.

The HttpClient 3.0 site can be found here.

23 October 2004 - New HttpClient mailing lists

Starting today HttpClient has two new mailing lists for developer and user discussion. People previously subscribed to commons-httpclient-dev have been automatically moved to the new developer mailing list. People subscribed to commons-user who are interested in HttpClient will have to join the HttpClient user mailing list manually.

Please see the HttpClient mailing list page for (un)subscription and archive details.

11 October 2004 - HttpClient issue tracking in Bugzilla

HttpClient project has taken a very important step toward becoming a full-fledged Jakarta level project. From today, HttpClient is a separate project in Apache Bugzilla issue tracking system. It is no longer a component of the Commons project. Please use the following details when filing bug reports for 2.0 and 3.0 branches of HttpClient:

Product: HttpClient
Component: Commons HttpClient

Use the following URL for convenience: Jakarta HttpClient new issue report.

Currently HttpClient project is debating whether we should continue using Bugzilla as an issue tracking system or migrate to JIRA. JIRA is a newer, more flexible issue tracking system. However, JIRA is not open-source software. If you have a strong opinion on this matter, please let us know.

11 October 2004 - HttpClient 2.0.2 released

We are pleased to announce the latest stable release of HttpClient, version 2.0.2. This release greatly improves the performance of executing methods where the response contains little or no content. Please see the release notes for more detail.

Please download and enjoy.

19 September 2004 - HttpClient 3.0 alpha2 released

We are pleased to announce the final alpha release of HttpClient 3.0. At this point HttpClient is fully feature-complete and is just a few issue reports short of being code and documentation complete. All of the important new features such as the new preferences architecture and exception handling framework are completely documented. We strongly encourage comment and criticism of the current API so we can have everything worked out by the first beta release. Following this release the development effort will focus on stabilizing the 3.0 API and adding more documentation. Depending on on how well this release is received, as well as the quality and quantity of feedback, we are looking at an API freeze in one to two months time.

The preview of the HttpClient 3.0 site can be found here.

Please download and enjoy.

1 August 2004 - HttpClient 2.0.1 released

We are pleased to announce the latest stable release of HttpClient, version 2.0.1. This release contains a few minor bug fixes and enhancements. Please see the release notes for more detail.

Please download and enjoy.

17 May 2004 - HttpClient 3.0 alpha1 released

We are pleased to announce the first HttpClient 3.0 release. HttpClient 3.0 provides a wealth of features and enhancements that did not make it into the 2.0 release, while preserving API compatibility as much as possible. In a relatively few cases API compatibility with HttpClient 2.0 could not maintained.

Noteworthy enhancements include:

  • New preference architecture
  • Improved exception handling framework
  • Granular non-standards configuration and tracking
  • Improved authentication framework
  • Plug-in mechanism for authentication modules
  • Cookie specification plug-in mechanism
  • Cross-site redirect support

We see our fellow Apache developers as well as other open-source projects already reliant on HttpClient as the primary target audience for this release. This is the right time to evaluate HttpClient 3.0 and give us some feedback, critique or other thought on the new API. Please feel free to file requests for additional features.

The goal of the second ALPHA release is to incorporate the feedback, polish the API, and update documentation. The next ALPHA release will target the wider audience beyond the Apache Jakarta and Apache WS communities.

Please download and let us know what you think.

16 April 2004 - Welcome Jakarta HttpClient!

By the count 26 votes in favor, none against, Jakarta Commons HttpClient as been promoted to the Jakarta sub-project level. The move to the Jakarta sub-project level is a next step in HttpClient evolution which will result in many exiting changes and new developments. So, stay tuned.

15 February 2004 - HttpClient 2.0 Final released

At last 2.0 final is upon us. This release represents a great deal of work by quite a number of people. We would like to thank all of those who contributed to this release.

Please download and enjoy.

16 January 2004 - HttpClient 2.0 Release Candidate 3 released

While a final 2.0 release still eludes us, we have continued to make good progress. This release fixes some significant bugs that crept into RC2. Assuming that there are no major bugs found in this release a final release should follow shortly.

13 October 2003 - HttpClient 2.0 Release Candidate 2 released

Releasing a final version of HttpClient 2.0 by the end of Summer 2003, as originally planned, was not possible. There were a significant number of minor bugs reported against RC1. None of them were major, but verifying, fixing, and testing simply took time more time than anticipated. We are pleased to announce the second release candidate of HttpClient 2.0 and hope to follow up with a final release shortly.

At the same time we have been busy working on our next release, currently designated as 2.1. It it shaping up quite well. We already have a new preferences architecture in place that will help us provide greater control over HttpClient without polluting its API with too many options. We have also completely reworked redirect/authentication/retry logic and can now support cross-host redirects, a much complained about limitation of HttpClient 2.0.

1 August 2003 - HttpClient 2.0 Release Candidate 1 released

The HttpClient 2.0 BETA development phase has been concluded. The number of bugs discovered in the course of the BETA development was surprisingly low. We are confident that HttpClient 2.0 has reached the required level of maturity, and we hope to have a final 2.0 release by the end of the Summer.

02 July 2003 - HttpClient 2.0 Beta 2 released

This release contains some minor bug fixes and documentation enhancements. Most likely this will be the final beta release before 2.0 Release Candidate 1. As always thank you to the HttpClient users and developers for their efforts. Please download HttpClient 2.0 Beta 2 and enjoy.

25 May 2003 - HttpClient 2.0 Beta 1 released

This is the first feature-complete release of HttpClient 2.0. A lot of effort has been put into making this release functional, stable and reliable. Many thanks to everyone who contributed code, time and testing. Please download HttpClient 2.0 Beta 1 and enjoy.

Note: The binary distributions were updated on 2 June, 2003 to fix a problem with the original jar's MANIFEST.MF. Using the original HttpClient jar from within a servlet container or J2EE managed environment may have caused some problems.

25 February 2003 - HttpClient 2.0 Alpha 3 released

This is an intermediate alpha release. The build process used in the previous Alpha 2 changed from generating 4 build artifacts to a single distribution. This one zip contains everything: all the source, the binary jar, the logging dependancy, generated javadoc and required build files for Ant builds and JUnit tests.

"One zip to rule them all, one zip to find them, one zip to bring them all and in the darkness bind them"

19 February, 2003 - Welcome new committer Michael Becke

Mike been an active contributor for many months. He has worked on a diverse range of problems with high quality results. In particular he is known for the massive HttpClient/HttpMultiClient merger that took place in December.

Welcome to Middle Earth Mike!

26 January 2003 - new mailing list archives

There are two new mailing list archives of the commons-httpclient-dev mailing list. It looks like someone up there is starting to like us!

25 January 2003 - HttpClient 2.0 Alpha 2 released

After many months and a great resurgence of developers, the new build of HttpClient is finally here. The new group of developers has done extensive refactoring to move the project along the new vision. The code base has reached a significant level of maturity and we expect that the beta builds will come quickly and that the final release of 2.0 is not far away!

Also check out the new HttpClient logo!

21 December, 2002 - Welcome new committer Oleg Kalnichevski

Oleg is the first committer to be voted in on the dedicated httpclient mailing list. Welcome to the fellowship Olegolas!

3 December, 2002 - HttpClient/HttpMultiClient merger

The initial merger of the top level classes HttpClient and HttpMultiClient is complete. Thanks for the patches and hard work from everyone particularly to Michale Becke for supplying the primary patch.

3 October, 2002 - commons-httpclient-dev mailing list

The mailing list was renamed to be commons-httpclient-dev. Sorry for the confusion.

If you wish to subscribe to this new mailing list, you can send mail to commons-httpclient-dev-subscribe@jakarta.apache.org

12 July, 2002 - HttpClient 2.0 Release Planning

The HttpClient project has go through some very active development leading up to Alpha 1 last year, but unfortunately lost momentum shortly after that. There is now renewed interest and greatly increased activity on the dev-commons mailing list. The committers and contributors are working on a new release plan for 2.0.

The 2.0 release plan is expected to be posted to the mailing list for review by July 22, 2002.

5 October, 2001 - HttpClient 2.0 Alpha 1 Released

The HttpClient revision 2.0 alpha 1 is available at http://jakarta.apache.org/builds/jakarta-commons/release/commons-httpclient/v2.0/.

25 April, 2001 - HttpClient Proposal Accepted

The HttpClient proposal has been accepted by the Jakarta Commons team and the source has been moved into the Subversion repository.

18 April, 2001 - HttpClient Proposed

HttpClient, originally developed by the Jakarta Slide team, has been proposed as a Jakarta Commons component.


commons-httpclient-3.1/docs/overview.html100644 0 0 22451 10661532631 16046 0ustar 0 0 HttpClient - Overview

Scope

The HttpClient component supports the client-side of RFC 1945 (HTTP/1.0) and RFC 2616 (HTTP/1.1), several related specifications (RFC 2109 (Cookies), RFC 2617 (HTTP Authentication), etc.), and provides a framework by which new request types (methods) or HTTP extensions can be created easily.

The org.apache.commons.httpclient Package

The basis for the abstraction is provided by three primary types:

    HttpConnection
    represents a network connection to some HTTP host.
    HttpMethod
    represents a request to be made over some HttpConnection and contains the server's response.
    HttpState
    contains the HTTP attributes that may persist from request to request, such as cookies and authentication credentials.

and several simple bean-style classes:

HttpClient provides a simple "user-agent" implementation that will suffice for many applications, but whose use is not required.

HttpClient also provides several utilities that may be useful when extending the framework:

    HttpMethodBase
    an abstract base implementation of HttpMethod, which may be extended to create new method types or to support additional HTTP protocol features.
    HttpStatus
    an enumeration of HttpStatus codes.
    RequestOutputStream
    an OutputStream wrapper supporting the "chunked" transfer encoding.
    ResponseInputStream
    an InputStream wrapper supporting the "chunked" transfer encoding.
    URIUtil
    provides utilities for encoding and decoding URI's in the %HH format.

The org.apache.commons.httpclient.methods Package

The org.apache.commons.httpclient.methods package provides HttpMethod implementations of the most commonly used HTTP methods, including GET, POST, PUT, OPTIONS, HEAD and DELETE.


commons-httpclient-3.1/docs/performance.html100644 0 0 31656 10661532631 16510 0ustar 0 0 HttpClient - HttpClient Performance Optimization Guide

Introduction

By default HttpClient is configured to provide maximum reliability and standards compliance rather than raw performance. There are several configuration options and optimization techniques which can significantly improve the performance of HttpClient. This document outlines various techniques to achieve maximum HttpClient performance.

Reuse the HttpClient instance

Generally it is recommended to have a single instance of HttpClient per communication component or even per application. However, if the application makes use of HttpClient only very infrequently, and keeping an idle instance of HttpClient in memory is not warranted, it is highly recommended to explicitly shut down the multithreaded connection manager prior to disposing the HttpClient instance. This will ensure proper closure of all HTTP connections in the connection pool.

Connection persistence

HttpClient always does its best to reuse connections. Connection persistence is enabled by default and requires no configuration. Under some situations this can lead to leaked connections and therefore lost resources. The easiest way to disable connection persistence is to provide or extend a connection manager that force-closes connections upon release in the releaseConnection method.

Concurrent execution of HTTP methods

If the application logic allows for execution of multiple HTTP requests concurrently (e.g. multiple requests against various sites, or multiple requests representing different user identities), the use of a dedicated thread per HTTP session can result in a significant performance gain. HttpClient is fully thread-safe when used with a thread-safe connection manager such as MultiThreadedHttpConnectionManager. Please note that each respective thread of execution must have a local instance of HttpMethod and can have a local instance of HttpState or/and HostConfiguration to represent a specific host configuration and conversational state. At the same time the HttpClient instance and connection manager should be shared among all threads for maximum efficiency.

For details on using multiple threads with HttpClient please refer to the HttpClient Threading Guide.

Request/Response entity streaming

HttpClient is capable of efficient request/response body streaming. Large entities may be submitted or received without being buffered in memory. This is especially critical if multiple HTTP methods may be executed concurrently. While there are convenience methods to deal with entities such as strings or byte arrays, their use is discouraged. Unless used carefully they can easily lead to out of memory conditions, since they imply buffering of the complete entity in memory.

Response streaming: It is recommended to consume the HTTP response body as a stream of bytes/characters using HttpMethod#getResponseBodyAsStream method. The use of HttpMethod#getResponseBody and HttpMethod#getResponseBodyAsString are strongly discouraged.

  HttpClient httpclient = new HttpClient();
  GetMethod httpget = new GetMethod("http://www.myhost.com/");
  try {
    httpclient.executeMethod(httpget);
    Reader reader = new InputStreamReader(
            httpget.getResponseBodyAsStream(), httpget.getResponseCharSet()); 
    // consume the response entity
  } finally {
    httpget.releaseConnection();
  }

Request streaming: The main difficulty encountered when streaming request bodies is that some entity enclosing methods need to be retried due to an authentication failure or an I/O failure. Obviously non-buffered entities cannot be reread and resubmitted. The recommended approach is to create a custom RequestEntity capable of reconstructing the underlying input stream.

public class FileRequestEntity implements RequestEntity {

    private File file = null;
    
    public FileRequestEntity(File file) {
        super();
        this.file = file;
    }

    public boolean isRepeatable() {
        return true;
    }

    public String getContentType() {
        return "text/plain; charset=UTF-8";
    }
    
    public void writeRequest(OutputStream out) throws IOException {
        InputStream in = new FileInputStream(this.file);
        try {
            int l;
            byte[] buffer = new byte[1024];
            while ((l = in.read(buffer)) != -1) {
                out.write(buffer, 0, l);
            }
        } finally {
            in.close();
        }
    }

    public long getContentLength() {
        return file.length();
    }
}

File myfile = new File("myfile.txt");
PostMethod httppost = new PostMethod("/stuff");
httppost.setRequestEntity(new FileRequestEntity(myfile));

Expect-continue handshake

The purpose of the HTTP 100 (Continue) status is to allow a client sending a request entity to determine if the target server is willing to accept the request (based on the request headers) before the client sends the request entity. It is highly inefficient for the client to send the request entity if the server will reject the request without looking at the body. Authentication failures are the most common reason for the request to be rejected based on the request headers alone. Therefore, use of the 'Expect-continue' handshake is especially recommended with those target servers that require HTTP authentication. For proxied requests caution must be taken as older HTTP/1.0 proxies may be unable to correctly handle the 'Expect-continue' handshake.

See the http.protocol.expect-continue parameter documentation for more information.

Stale connection check

HTTP specification permits both the client and the server to terminate a persistent (keep-alive) connection at any time without notice to the counterpart, thus rendering the connection invalid or stale. By default HttpClient performs a check, just prior to executing a request, to determine if the active connection is stale. The cost of this operation is about 15-30 ms, depending on the JRE used. Disabling stale connection check may result in slight performance improvement, especially for small payload responses, at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.

See the http.connection.stalecheck parameter documentation for more information.

Cookie processing

If an application, such as web spider, does not need to maintain conversational state with the target server, a small performance gain can made by disabling cookie processing. For details on cookie processing please to the HttpClient Cookies Guide.


commons-httpclient-3.1/docs/preference-api.html100644 0 0 102173 10661532631 17105 0ustar 0 0 HttpClient - HttpClient preference architecture and configuration guide

HttpClient preference architecture

Quality and extent of the HTTP/1.0 and HTTP/1.1 spec compliance vary significantly among commonly used HTTP agents and HTTP servers. That requires of HttpClient to be able to

  • mimic (mis-)behavior of widely used web browsers;
  • support flexible and configurable level of leniency toward non-critical protocol violations especially in those gray areas of the specification subject to different, at times conflicting, interpretations;
  • apply a different set of parameters to individual HTTP methods, hosts, or client instances using common interface;

HTTP parameters

As of version 3 HttpClient sports a new preference API based on HttpParams interface. All major components of the HttpClient toolkit (agents, host configurations, methods, connections, connection managers) contain a collection of HTTP parameters, which determine the runtime behavior of those components.

HttpClient httpclient = new HttpClient();
HttpVersion ver = (HttpVersion)httpclient.getParams().getParameter("http.protocol.version");

In a nutshell HTTP parameters is a collection of name/object pairs that can be linked with other collections to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the upper level collection of parameters.

HttpClient httpclient = new HttpClient();
httpclient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
httpclient.getParams().setParameter("http.socket.timeout", new Integer(1000));
httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8");

HostConfiguration hostconfig = new HostConfiguration();
hostconfig.setHost("www.yahoo.com");
hostconfig.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_0);
		
GetMethod httpget = new GetMethod("/");
httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));
		
try {
  // Internally the parameter collections will be linked together
  // by performing the following operations: 
  // hostconfig.getParams().setDefaults(httpclient.getParams());
  // httpget.getParams().setDefaults(hostconfig.getParams());
  httpclient.executeMethod(hostconfig, httpget);
  System.out.println(httpget.getParams().getParameter("http.protocol.version"));
  System.out.println(httpget.getParams().getParameter("http.socket.timeout"));
  System.out.println(httpget.getParams().getParameter("http.protocol.content-charset"));
} finally {
  httpget.releaseConnection();
}

The code above will produce the following output:

HTTP/1.0
5000
UTF-8

When resolving a parameter HttpClient uses the following algorithm:

  • start parameter lookup from the lowest level at which this parameter applies
  • if the parameter is undefined at the current level, defer its resolution to the next level up in the hierarchy
  • return parameter value from the lowest level in the hierarchy the parameter defined at
  • return null if the parameter is undefined

This architecture enables the users to define generic parameters at a higher level (for instance, at the agent level or host level) and selectively override specific parameters at a lower level (for instance, at the method level). Whenever a parameter is not explicitly defined at a given level, the defaults of the upper levels will apply.

HTTP parameter hierarchy

Presently HttpClient provides the following parameter hierarchy:

global--+                            | DefaultHttpParams
        |                            |
      client                         | HttpClient
        |                            |
        +-- connection manager       | HttpConnectionManager
        |     |                      |
        |     +-- connection         | HttpConnection
        |                            |
        +-- host                     | HostConfiguration
              |                      |
              +-- method             | HttpMethod

Supported parameters

HTTP method parameters

Applicable at the following levels: global -> client -> host -> method

Name Type Description Default

http.useragent

String

The content of the User-Agent header used by the HTTP methods.

official release name, e.g. "Jakarta Commons-HttpClient/3.0"

http.protocol.version

HttpVersion

The HTTP protocol version used per default by the HTTP methods.

HttpVersion.HTTP_1_1

http.protocol.unambiguous-statusline

Boolean

Defines whether HTTP methods should reject ambiguous HTTP status line.

<undefined>

http.protocol.single-cookie-header

Boolean

Defines whether cookies should be put on a single response header.

<undefined>

http.protocol.strict-transfer-encoding

Boolean

Defines whether responses with an invalid Transfer-Encoding header should be rejected.

<undefined>

http.protocol.reject-head-body

Boolean

Defines whether the content body sent in response to HEAD request should be rejected.

<undefined>

http.protocol.head-body-timeout

Integer

Sets period of time in milliseconds to wait for a content body sent in response to HEAD response from a non-compliant server. If the parameter is not set or set to -1 non-compliant response body check is disabled.

<undefined>

http.protocol.expect-continue

Boolean

Activates 'Expect: 100-Continue' handshake for the entity enclosing methods. The 'Expect: 100-Continue' handshake allows 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 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.

<undefined>

http.protocol.credential-charset

String

The charset to be used when encoding credentials. If not defined then the value of the 'http.protocol.element-charset' should be used.

<undefined>

http.protocol.element-charset

String

The charset to be used for encoding/decoding HTTP protocol elements (status line and headers).

'US-ASCII'

http.protocol.content-charset

String

The charset to be used for encoding content body.

'ISO-8859-1'

http.protocol.cookie-policy

String

The cookie policy to be used for cookie management.

CookiePolicy.RFC_2109

http.protocol.warn-extra-input

Boolean

Defines HttpClient's behavior when a response provides more bytes than expected (specified with Content-Length header, for example).

Such surplus data makes the HTTP connection unreliable for keep-alive requests, as malicious response data (faked headers etc.) can lead to undesired results on the next request using that connection.

If this parameter is set to true, any detection of extra input data will generate a warning in the log.

<undefined>

http.protocol.status-line-garbage-limit

Integer

Defines the maximum number of ignorable lines before we expect a HTTP response's status code.

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

Set this to 0 to disallow any garbage/empty lines before the status line. To specify no limit, use Integer#MAX_VALUE.

<undefined>

http.socket.timeout

Integer

Sets the socket timeout (SO_TIMEOUT) in milliseconds to be used when executing the method. A timeout value of zero is interpreted as an infinite timeout.

<undefined>

http.method.retry-handler

HttpMethodRetryHandler

The method retry handler used for retrying failed methods. For details see the Exception handling guide.

default implementation

http.dateparser.patterns

Collection

Date patterns used for parsing. The patterns are stored in a Collection and must be compatible with SimpleDateFormat.

'EEE, dd MMM yyyy HH:mm:ss zzz',

'EEEE, dd-MMM-yy HH:mm:ss zzz',

'EEE MMM d HH:mm:ss yyyy',

'EEE, dd-MMM-yyyy HH:mm:ss z',

'EEE, dd-MMM-yyyy HH-mm-ss z',

'EEE, dd MMM yy HH:mm:ss z',

'EEE dd-MMM-yyyy HH:mm:ss z',

'EEE dd MMM yyyy HH:mm:ss z',

'EEE dd-MMM-yyyy HH-mm-ss z',

'EEE dd-MMM-yy HH:mm:ss z',

'EEE dd MMM yy HH:mm:ss z',

'EEE,dd-MMM-yy HH:mm:ss z',

'EEE,dd-MMM-yyyy HH:mm:ss z',

'EEE, dd-MM-yyyy HH:mm:ss z'

http.method.response.buffer.warnlimit

Integer

The maximum buffered response size (in bytes) that triggers no warning. Buffered responses exceeding this size will trigger a warning in the log. If not set, the limit is 1 MB.

<undefined>

http.method.multipart.boundary

String

The multipart boundary string to use in conjunction with the MultipartRequestEntity. When not set a random value will be generated for each request.

<undefined>

Whenever a parameter is left undefined (no value is explicitly set anywhere in the parameter hierarchy) HttpClient will use its best judgment to pick up a value. This default behavior is likely to provide the best compatibility with widely used HTTP servers.

HTTP connection parameters

Applicable at the following levels: global -> client -> connection manager -> connection

Name Type Description Default

http.socket.timeout

Integer

The default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the HTTP method parameters.

<undefined>

http.tcp.nodelay

Boolean

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 (by enabling TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption and number of packets.

<undefined>

http.socket.sendbuffer

Integer

The value to set on Socket.setSendBufferSize(int). This value is a suggestion to the kernel from the application about the size of buffers to use for the data to be sent over the socket.

<undefined>

http.socket.receivebuffer

Integer

The value to set on Socket.setReceiveBufferSize(int). This value is a suggestion to the kernel from the application about the size of buffers to use for the data to be received over the socket.

<undefined>

http.socket.linger

Integer

The linger time (SO_LINGER) in seconds. This option disables/enables immediate return from a close() of a TCP Socket. Enabling this option with a non-zero Integer timeout means that a close() will block pending the transmission and acknowledgement of all data written to the peer, at which point the socket is closed gracefully. Value 0 implies that the option is disabled. Value -1 implies that the JRE default is used.

<undefined>

http.connection.timeout

Integer

The timeout until a connection is established. A value of zero means the timeout is not used.

<undefined>

http.connection.stalecheck

Boolean

Determines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.

<undefined>

Whenever a parameter is left undefined (no value is explicitly set anywhere in the parameter hierarchy) HttpClient will use its best judgment to pick up a value. This default behavior is likely to provide the best compatibility with widely used HTTP servers.

HTTP connection manager parameters

Applicable at the following levels: global -> client -> connection manager

Name Type Description Default

http.connection-manager.max-per-host

Map

Defines the maximum number of connections allowed per host configuration. These values only apply to the number of connections from a particular instance of HttpConnectionManager.

This parameter expects a value of type Map. The value should map instances of HostConfiguration to Integers. The default value can be specified using ANY_HOST_CONFIGURATION.

<undefined>

http.connection-manager.max-total

Integer

Defines the maximum number of connections allowed overall. This value only applies to the number of connections from a particular instance of HttpConnectionManager.

<undefined>

Whenever a parameter is left undefined (no value is explicitly set anywhere in the parameter hierarchy) HttpClient will use its best judgment to pick up a value. This default behavior is likely to provide the best compatibility with widely used HTTP servers.

Host configuration parameters

Applicable at the following levels: global -> client -> host

Name Type Description Default

http.default-headers

Collection

The request headers to be sent per default with each request. This parameter expects a value of type Collection. The collection is expected to contain HTTP headers

<undefined>

Whenever a parameter is left undefined (no value is explicitly set anywhere in the parameter hierarchy) HttpClient will use its best judgment to pick up a value. This default behavior is likely to provide the best compatibility with widely used HTTP servers.

HTTP client parameters

Applicable at the following levels: global -> client

Name Type Description Default

http.connection-manager.timeout

Long

The timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager. 0 means to wait indefinitely.

<undefined>

http.connection-manager.class

Class

The default HTTP connection manager class.

SimpleHttpConnectionManager class

http.authentication.preemptive

Boolean

Defines whether authentication should be attempted preemptively. See authentication guide.

<undefined>

http.protocol.reject-relative-redirect

Boolean

Defines whether relative redirects should be rejected. Although redirects are supposed to be absolute it is common internet practice to use relative URLs.

<undefined>

http.protocol.max-redirects

Integer

Defines the maximum number of redirects to be followed. The limit on number of redirects is intended to prevent infinite loops.

<undefined>

http.protocol.allow-circular-redirects

Boolean

Defines whether circular redirects (redirects to the same location) should be allowed. The HTTP spec is not sufficiently clear whether circular redirects are permitted, therefore optionally they can be enabled.

<undefined>

Whenever a parameter is left undefined (no value is explicitly set anywhere in the parameter hierarchy) HttpClient will use its best judgment to pick up a value. This default behavior is likely to provide the best compatibility with widely used HTTP servers.


commons-httpclient-3.1/docs/project-info.html100644 0 0 16233 10661532631 16600 0ustar 0 0 HttpClient - Project Information

General Project Information

This document provides an overview of the various documents and links that are part of this project's general information. All of this content is automatically generated by Maven on behalf of the project.

Overview

Document Description
Mailing Lists This document provides subscription and archive information for this project's mailing lists.
Project Team This document provides information on the members of this project. These are the individuals who have contributed to the project in one form or another.
Dependencies This document lists the projects dependencies and provides information on each dependency.
Source Repository This is a link to the online source repository that can be viewed via a web browser.
Issue Tracking This is a link to the issue tracking system for this project. Issues (bugs, features, change requests) can be created and queried using this link.

commons-httpclient-3.1/docs/proposal.html100644 0 0 17410 10661532631 16036 0ustar 0 0 HttpClient - Proposal

Rationale

HTTP is the main protocol used today on the internet. Although the JDK includes basic support for building HTTP-aware client applications, it doesn't provide the flexibility or ease of use needed for many projects.

A Commons package would give committers an opportunity to coordinate their efforts to create and maintain a efficient, feature-rich package under the ASF license.

Scope of the Package

The package shall create and maintain a Java library implementing the client side of the HTTP/1.1 protocol, as defined in RFC 2616 and RFC 2617.

The package should :

  • Have an API which should be as simple to use as possible
  • Be as easy to extend as possible
  • Provide unconditional support for HTTP/1.1
The package is quite different from the HTTP client provided as part of the JDK (java.net.HttpURLConnection), as it focuses on the HTTP methods being sent (instead of making that transparent to the user), and generally allows more interaction with the lower level connection. The JDK client is also not very intuitive to use.

The package is used by the Slide project to build a WebDAV client library supporting WebDAV level 2.

Interaction With Other Packages

HttpClient relies on:

  • Java Development Kit (Version 1.1 or later; 1.3 or later recommended)

Initial Source of the Package

The initial codebase exists in the jakarta-slide cvs tree under the org.apache.webdav.lib package. It would be moved to commons under the http subdirectory.

The proposed package name for the new component is org.apache.commons.httpclient.

Required Jakarta-Commons Resources

  • CVS Repository - New directory httpclient in the jakarta-commons CVS repository.
  • Initial Committers - The list is provided below. Some of the proposed committers are not currently jakarta-commons committers, but are committers on the jakarta-slide project, and contributed to this component.
  • Mailing List - Discussions will take place on the general jakarta-commons@jakarta.apache.org mailing list. To help list subscribers identify messages of interest, it is suggested that the message subject of messages about this component be prefixed with [httpclient].
  • Bugzilla - New component "HttpClient" under the "Commons" product category, with appropriate version identifiers as needed.
  • Jyve FAQ - New category "commons-httpclient" (when available).

Initial Committers

The initial committers on the HttpClient component shall be:

  • Remy Maucherat
  • B.C.Holmes
  • Sung-Gu Park
  • Juergen Pill
  • Costin Manolache

Proposal ChangeLog

2002/07/19 - Replace uses of HTTP Client with HttpClient for consistency.


commons-httpclient-3.1/docs/redirects.html100644 0 0 17631 10661532631 16170 0ustar 0 0 HttpClient - Cross Host Redirects

Introduction

This document provides a brief guide to custom handling of redirects with HttpClient.

There are a few types of redirect that HttpClient can't handle automatically either because they require user interaction, or they are outside of the scope of HttpClient (these status codes are listed below), or due to internal limitations. Currently HttpClient is unable to automatically handle redirects of entity enclosing methods such as POST and PUT. There can also be situations when manual processing of redirects is desired due to specific application requirements.

Handling redirects manually

All response codes between 300 and 399 inclusive are redirect responses of some form. The most common redirect response codes are:

  • 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY
  • 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY
  • 303 See Other. HttpStatus.SC_SEE_OTHER
  • 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT

Note: there are a number of response codes in the 3xx range which do not simply indicate a different URI to send the request to. These response codes are listed below and the manner they are handled will be application specific.

When your application receives one of the "simple" redirect responses, it should extract the new URL from the HttpMethod object and retry downloading from that URL. Additionally, it is usually a good idea to limit the number of redirects that will be followed in case the redirects form a recursive loop.

The URL to connect to can be extracted from the Location header.

        String redirectLocation;
        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null) {
            redirectLocation = locationHeader.getValue();
        } else {
            // The response is invalid and did not provide the new location for
            // the resource.  Report an error or possibly handle the response
            // like a 404 Not Found error.
        }
      

Once you have determined the new location, you can reattempt the connection as normal. See the Tutorial for more information on this.

Special Redirect Codes

The HTTP specification defines a number of somewhat unusual redirect response codes that will likely need to be handled in a different manner to the codes above. In particular these are:

  • 300 Multiple Choices. HttpStatus.SC_MULTIPLE_CHOICES

    There are multiple choices available for the redirection. A preferred redirect URI may be specified in the location header, however generally it is expected that the user will be given the choice of which URI to be redirected to. It is however permissible to simply select one of the available choices arbitrarily.

  • 304 Not Modified. HttpStatus.SC_NOT_MODIFIED

    The resource has not been modified since it was last requested. You should retrieve the resource from cache instead. If the resource is no longer available in the cache the request should be retried without the conditional headers.

  • 305 Use Proxy. HttpStatus.SC_USE_PROXY

    The resource must be accessed through the specified proxy. The proxy is specified in the Location header.


commons-httpclient-3.1/docs/scm-usage.html100644 0 0 15375 10661532631 16073 0ustar 0 0 HttpClient - Source Repository

Web Access

This is a link to the online source repository that can be viewed via a web browser:

Source Repository

This project uses Subversion to manage its source code. Instructions for using Subversion can be found at http://svnbook.red-bean.com/.

Anonymous Access with Maven

This project's source can be checked out anonymously from SVN with the following instruction set on a single line:

            
      maven scm:checkout
        -Dmaven.scm.method=svn
        -Dmaven.scm.url=scm:svn:http://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/trunk
        -Dmaven.scm.checkout.dir=commons-httpclient
    

Anonymous Access

This project's source can be checked out anonymously from SVN with the following command:

svn checkout http://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/trunk commons-httpclient

Access through a proxy

The Subversion client can go through a proxy, if you configure it to do so. First, edit your "servers" configuration file to indicate which proxy to use. The files location depends on your operating system. On Linux or Unix it is located in the directory "~/.subversion". On Windows it is in "%APPDATA%\Subversion". (Try "echo %APPDATA%", note this is a hidden directory.)

There are comments in the file explaining what to do. If you don't have that file, get the latest Subversion client and run any command; this will cause the configuration directory and template files to be created.

Example : Edit the 'servers' file and add something like:

[global]
http-proxy-host = your.proxy.name
http-proxy-port = 3128

commons-httpclient-3.1/docs/sslguide.html100644 0 0 46020 10661532631 16015 0ustar 0 0 HttpClient - HttpClient SSL Guide

Introduction

HttpClient provides full support for HTTP over Secure Sockets Layer (SSL) or IETF Transport Layer Security (TLS) protocols by leveraging the Java Secure Socket Extension (JSSE). JSSE has been integrated into the Java 2 platform as of version 1.4 and works with HttpClient out of the box. On older Java 2 versions JSSE needs to be manually installed and configured. Installation instructions can be found here

Standard SSL in HttpClient

Once you have JSSE correctly installed, secure HTTP communication over SSL should be as simple as plain HTTP communication.

  HttpClient httpclient = new HttpClient();
  GetMethod httpget = new GetMethod("https://www.verisign.com/"); 
  try { 
    httpclient.executeMethod(httpget);
    System.out.println(httpget.getStatusLine());
  } finally {
    httpget.releaseConnection();
  }

HTTPS communication via an authenticating proxy server is also no different from plain HTTP communication. All the low-level details of establishing a tunneled SSL connection are handled by HttpClient:

  HttpClient httpclient = new HttpClient();
  httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);
  httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
  new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
  GetMethod httpget = new GetMethod("https://www.verisign.com/");
  try { 
    httpclient.executeMethod(httpget);
    System.out.println(httpget.getStatusLine());
  } finally {
    httpget.releaseConnection();
  }

Customizing SSL in HttpClient

The default behaviour of HttpClient is suitable for most uses, however there are some aspects which you may want to configure. The most common requirements for customizing SSL are:

  • Ability to accept self-signed or untrusted SSL certificates. This is highlighted by an SSLException with the message Unrecognized SSL handshake (or similar) being thrown when a connection attempt is made.
  • You want to use a third party SSL library instead of Sun's default implementation.

Implementation of a custom protocol involves the following steps:

  1. Provide a custom socket factory that implements org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory interface. The socket factory is responsible for opening a socket to the target server using either the standard or a third party SSL library and performing any required initialization such as performing the connection handshake. Generally the initialization is performed automatically when the socket is created.

  2. Instantiate an object of type org.apache.commons.httpclient.protocol.Protocol. The new instance would be created with a valid URI protocol scheme (https in this case), the custom socket factory (discussed above) and a default port number (typically 443 for https). For example:

    Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
          

    The new instance of protocol can then be set as the protocol handler for a HostConfiguration. For example to configure the default host and protocol handler for a HttpClient instance use:

    HttpClient httpclient = new HttpClient();
    httpclient.getHostConfiguration().setHost("www.whatever.com", 443, myhttps);
    GetMethod httpget = new GetMethod("/");
    try {
      httpclient.executeMethod(httpget);
      System.out.println(httpget.getStatusLine());
    } finally {
      httpget.releaseConnection();
    }
  3. Finally, you can register your custom protocol as the default handler for a specific protocol designator (eg: https) by calling the Protocol.registerProtocol method. You can specify your own protocol designator (such as 'myhttps') if you need to use your custom protocol as well as the default SSL protocol implementation.

    Protocol.registerProtocol("myhttps", 
    new Protocol("https", new MySSLSocketFactory(), 9443));
          

    Once registered the protocol be used as a 'virtual' scheme inside target URIs.

    HttpClient httpclient = new HttpClient();
    GetMethod httpget = new GetMethod("myhttps://www.whatever.com/");
    try {
      httpclient.executeMethod(httpget);
      System.out.println(httpget.getStatusLine());
    } finally {
      httpget.releaseConnection();
    }

    If you want this protocol to represent the default SSL protocol implementation, simply register it under 'https' designator, which will make the protocol object take place of the existing one

    Protocol.registerProtocol("https", 
    new Protocol("https", new MySSLSocketFactory(), 443));
    HttpClient httpclient = new HttpClient();
    GetMethod httpget = new GetMethod("https://www.whatever.com/");
    try {
      httpclient.executeMethod(httpget);
      System.out.println(httpget.getStatusLine());
    } finally {
      httpget.releaseConnection();
    }

Examples of SSL customization in HttpClient

There are several custom socket factories available in our contribution package. They can be a good start for those who seek to tailor the behavior of the HTTPS protocol to the specific needs of their application:

  • EasySSLProtocolSocketFactory can be used to create SSL connections that allow the target server to authenticate with a self-signed certificate.
  • StrictSSLProtocolSocketFactory can be used to create SSL connections that can optionally perform host name verification in order to help preventing man-in-the-middle type of attacks.
  • AuthSSLProtocolSocketFactory can be used to optionally enforce mutual client/server authentication. This is the most flexible implementation of a protocol socket factory. It allows for customization of most, if not all, aspects of the SSL authentication.

Known limitations and problems

  1. Persistent SSL connections do not work on Sun's JVMs below 1.4

    Due to what appears to be a bug in Sun's older (below 1.4) implementation of Java Virtual Machines or JSSE there's no reliable way of telling if an SSL connection is 'stale' or not. For example, the HTTP 1.1 specification permits HTTP servers in 'keep-alive' mode to drop the connection to the client after a given period inactivity without having to notify the client, effectively rendering such connection unusable or 'stale'. For the HTTP agent written in Java there's no reliable way to test if a connection is 'stale' other than attempting to perform a read on it. However, a read operation on an idle SSL connection on Sun JVM older than 1.4 returns 'end of stream' instead of an expected read timeout. That effectively makes the connection appear 'stale' to HttpClient, which leaves it with no other way but to drop the connection and to open a new one, thus defeating HTTP 1.1 keep-alive mechanism and resulting in significant performance degradation (SSL authentication is a highly time consuming operation). The problem appears to have been fixed in Sun's Java 1.4 SSL implementation. Sockets which are not using HTTPS are unaffected on any JVM.

    Workaround: Disable stale connection check if upgrade to Java 1.4 or above is not an option. Please note that HttpClient will no longer be able to detect invalid connections and some requests may fail due to transport errors. For details on how transport errors can be recovered from please refer to the Exception Handling Guide. If persistent SSL connections support and transport reliability is an issue for your application we strongly advise you to upgrade to Java 1.4.

  2. Authetication schemes that rely on persistent connection state do not work on Sun's JVMs below 1.4 if SSL is used

    This problem is directly related to the problem described above. Certain authentication schemes or certain implementations of standard authentication schemes are connection based, that is, the user authentication is performed once when the connection is being established, rather than every time a request is being processed. Microsoft NTLM scheme and Digest scheme as implemented in Microsoft Proxy and IIS servers are known to fall into this category. If connections cannot be kept alive the user authorization is lost along with the persistent connection state

    Workaround: Disable stale connection check or upgrade to Java 1.4 or above.

  3. JSSE prior to Java 1.4 incorrectly reports socket timeout.

    Prior to Java 1.4, in Sun's JSSE implementation, a read operation that has timed out incorrect reports end of stream condition instead of throwing java.io.InterruptedIOException as expected. HttpClient responds to this exception by assuming that the connection was dropped and throws a NoHttpResponseException. It should instead report "java.io.InterruptedIOException: Read timed out". If you encounter NoHttpResponseException when working with an older version of JDK and JSSE, it can be caused by the timeout waiting for data and not by a problem with the connection.

    Work-around: One possible solution is to increase the timeout value as the server is taking too long to start sending the response. Alternatively you may choose to upgrade to Java 1.4 or above which does not exhibit this problem.

    The problem has been discovered and reported by Daniel C. Amadei.

  4. HttpClient does not work with IBM JSSE shipped with IBM Websphere Application Platform

    Several releases of the IBM JSSE exhibit a bug that cause HttpClient to fail while detecting the size of the socket send buffer (java.net.Socket.getSendBufferSize method throws java.net.SocketException: "Socket closed" exception).

    Solution: Make sure that you have all the latest Websphere fix packs applied and IBMJSSE is at least version 1.0.3. HttpClient users have reported that IBM Websphere Application Server versions 4.0.6, 5.0.2.2, 5.1.0 and above do not exhibit this problem.

Troubleshooting

JSSE is prone to configuration problems, especially on older JVMs, which it is not an integral part of. As such, if you do encounter problems with SSL and HttpClient it is important to check that JSSE is correctly installed.

The application below can be used as an ultimate test that can reliably tell if SSL configured properly, as it relies on a plain socket in order to communicate with the target server. If an exception is thrown when executing this code, SSL is not correctly installed and configured. Please refer to Sun's official resources for support or additional details on JSSE configuration.

  import java.io.BufferedReader;
  import java.io.InputStreamReader;
  import java.io.OutputStreamWriter;
  import java.io.Writer;
  import java.net.Socket;

  import javax.net.ssl.SSLSocketFactory;

  public class Test {
        
     public static final String TARGET_HTTPS_SERVER = "www.verisign.com"; 
     public static final int    TARGET_HTTPS_PORT   = 443; 
        
     public static void main(String[] args) throws Exception {
        
       Socket socket = SSLSocketFactory.getDefault().
         createSocket(TARGET_HTTPS_SERVER, TARGET_HTTPS_PORT);
       try {
         Writer out = new OutputStreamWriter(
            socket.getOutputStream(), "ISO-8859-1");
         out.write("GET / HTTP/1.1\r\n");  
         out.write("Host: " + TARGET_HTTPS_SERVER + ":" + 
             TARGET_HTTPS_PORT + "\r\n");  
         out.write("Agent: SSL-TEST\r\n");  
         out.write("\r\n");  
         out.flush();  
         BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream(), "ISO-8859-1"));
         String line = null;
         while ((line = in.readLine()) != null) {
            System.out.println(line);
         }
       } finally {
         socket.close(); 
       }
     }
  }
        

commons-httpclient-3.1/docs/status.html100644 0 0 11532 10661532631 15521 0ustar 0 0 HttpClient - Status

Current Status

HttpClient 3.1 adds support for the RFC 2965 cookie management (also known as Cookie2 or port sensitive cookies) and a number of improvements to the HTTP connection management. HttpClient 3.1 is backward compatible with HttpClient 3.0

HttpClient 3.1 is likely to be the last non-bug fixing release of the HttpClient 3.x code line

Release Info

Current Stable Release (recommended): Release 3.1

HttpClient 2.0 is no longer being actively developed and supported.


commons-httpclient-3.1/docs/style/maven-base.css100644 0 0 5227 10661532627 17171 0ustar 0 0 body { margin: 0px; padding: 0px; } img { border:none; } table { padding:0px; width: 100%; margin-left: -2px; margin-right: -2px; } acronym { cursor: help; border-bottom: 1px dotted #feb; } table.bodyTable th, table.bodyTable td { padding: 2px 4px 2px 4px; vertical-align: top; } div.clear{ clear:both; visibility: hidden; } div.clear hr{ display: none; } #organizationLogo, #projectLogo { font-size: xx-large; font-weight: bold; } #organizationLogo img, #projectLogo img, #organizationLogo span, #projectLogo span{ margin: 0px; } #organizationLogo span, #projectLogo span{ border: 1px solid; padding: 4px 10px 4px 10px; background-color: #eee; cursor: pointer; } .xleft, #organizationLogo img{ float:left; } .xright, #projectLogo img, #projectLogo span{ float:right; text-shadow: #7CFC00; } #banner { padding: 0px; } #banner img { border: none; } #breadcrumbs { padding: 3px 10px 3px 10px; } #leftColumn { width: 150px; float:left; } #bodyColumn { margin-right: 1.5em; margin-left: 177px; } #legend { padding: 8px 0 8px 0; } #navcolumn { padding: 8px 4px 0 8px; } #navcolumn h5 { margin: 0; padding: 0; font-size: small; } #navcolumn ul { margin: 0; padding: 0; font-size: small; } #navcolumn li { list-style-type: none; background-image: none; background-repeat: no-repeat; background-position: 0 0.4em; padding-left: 16px; list-style-position: outside; line-height: 1.2em; font-size: smaller; } #navcolumn li.expanded { background-image: url(../images/expanded.gif); } #navcolumn li.collapsed { background-image: url(../images/collapsed.gif); } #poweredBy, #poweredByExternal { text-align: center; } #navcolumn img { margin-top: 10px; margin-bottom: 3px; } #poweredBy img { display:block; margin: 20px 0 20px 17px; border: 1px solid black; width: 90px; height: 30px; } #poweredByExternal img { display:block; margin: 20px 0 20px 17px; } #searchbar img { margin: 0px; display: block; } #searchbar #q, #searchbar #btnG { border: 1px solid #999; margin-bottom:10px; } #searchbar form { margin: 0px; } #lastPublished { font-size: x-small; } .navSection { margin-bottom: 2px; padding: 8px; } .navSectionHead { font-weight: bold; font-size: x-small; } .section { padding: 4px; } #footer { padding: 3px 10px 3px 10px; font-size: x-small; } #breadcrumbs { font-size: x-small; margin: 0pt; } .source { padding: 12px; margin: 1em 7px 1em 7px; } .source pre { margin: 0px; padding: 0px; } #navcolumn img.imageLink, .imageLink{ padding-left: 0px; padding-bottom: 0px; padding-top: 0px; padding-right: 2px; border: 0px; margin: 0px; } commons-httpclient-3.1/docs/style/maven-classic.css100644 0 0 34057 10661532627 17723 0ustar 0 0 body { background: #fff; color: #000; padding: 0px 0px 10px 0px; } .contentBox h2 { color: #fff; background-color: #036; } .contentBox h3 { color: #fff; background-color: #888; } .a td { background: #ddd; color: #000; } .b td { background: #efefef; color: #000; } .contentBox th { background-color: #bbb; color: #fff; } div#banner { border-top: 1px solid #369; border-bottom: 1px solid #003; } #banner, #banner td { background: #036; color: #fff; } #banner { border-bottom: 1px solid #fff; } #leftColumn { background: #eee; color: #000; border-right: 1px solid #aaa; border-bottom: 1px solid #aaa; border-top: 1px solid #fff; width: 20%; } #bodyColumn { margin-left: 20%; } #navcolumn { /* bad for IE background: #eee; */ color: #000; border-right: none; border-bottom: none; border-top: none; } #breadcrumbs { background-color: #ddd; color: #000; border-top: 1px solid #fff; border-bottom: 1px solid #aaa; } .source { background-color: #fff; color: #000; border-right: 1px solid #888; border-left: 1px solid #888; border-top: 1px solid #888; border-bottom: 1px solid #888; margin-right: 7px; margin-left: 7px; margin-top: 1em; } .source pre { margin-right: 7px; margin-left: 7px; } a[name]:hover, #leftColumn a[name]:hover { color: inherit !important; } a:link, #breadcrumbs a:visited, #navcolumn a:visited, .contentBox a:visited, .tasknav a:visited { color: blue; } a:active, a:hover, #leftColumn a:active, #leftColumn a:hover { color: #f30 !important; } a:link.selfref, a:visited.selfref { color: #555 !important; } #legend li.externalLink { background: url(../images/external-classic.png) left top no-repeat; padding-left: 18px; } a.externalLink, a.externalLink:link, a.externalLink:visited, a.externalLink:active, a.externalLink:hover { background: url(../images/external-classic.png) right center no-repeat; padding-right: 18px; } #legend li.newWindow { background: url(../images/newwindow-classic.png) left top no-repeat; padding-left: 18px; } a.newWindow, a.newWindow:link, a.newWindow:visited, a.newWindow:active, a.newWindow:hover { background: url(../images/newwindow-classic.png) right center no-repeat; padding-right: 18px; } h2, h3 { margin-top: 1em; margin-bottom: 0; } img.handle { border: 0; padding-right: 2px; } #navcolumn div div { background-image: none; background-repeat: no-repeat; } #navcolumn div div { padding-left: 10px; } /* $Id: maven-classic.css 312546 2005-10-10 04:47:22Z ltheussl $ This file defines basic default formatting for HTML conforming to Tigris application style. To extend or override these rules for your instance, edit inst.css instead of this file. */ /* colors, backgrounds, borders, link indication */ .contentBox h2, .contentBox h3, .tabs td, .tabs th, .functnbar { background-image: url(../images/nw_maj_rond.gif); background-repeat: no-repeat; } .functnbar, .functnbar2 { background-color: #aaa; } .functnbar2, .functnbar3 { background-color: #aaa; background-image: url(../images/sw_maj_rond.gif); background-repeat: no-repeat; background-position: bottom left; } .functnbar3 { background-color: #ddd; background-image: url(../images/sw_med_rond.gif); } .functnbar, .functnbar2, .functnbar3 { color: #000; } .functnbar a, .functnbar2 a, .functnbar3 a { color: #000; text-decoration: underline; } #navcolumn .body div, body.docs #toc li li { background-image: url(../images/strich.gif); background-repeat: no-repeat; background-position: .5em .5em; } #searchbox .body div, #navcolumn .body .heading { background-image: none; } a:link.selfref, a:visited.selfref { text-decoration: none; } #leftColumn a, #breadcrumbs a { text-decoration: none; } /* Unsure of this. TODO */ .contentBox h2 a:link, .contentBox h2 a:visited, .contentBox h3 a:link, .contentBox h3 a:visited { color: #fff !important; text-decoration: underline; } table, th, td { border: none; } div.colbar { background: #eee; border-color: #999 #EEE #EEE #999; border-width: 1px; border-style: solid; } .toolgroup { background: #efefef; } .toolgroup .label { border-bottom: 1px solid #666; border-right: 1px solid #666; background: #ddd; color: #555; } .toolgroup .body { border-right: 1px solid #aaa; border-bottom: 1px solid #aaa; } #main { border-top: 1px solid #999; } #rightcol div.www, #rightcol div.help { border: 1px solid #ddd; } body.docs div.docs { background-color: #fff; border-left: 1px solid #ddd; border-top: 1px solid #ddd; } #helptext .label { background-image: url(../images/icon_help_sml.gif); background-repeat: no-repeat; background-position: 97%; } body.docs { background: #eee url(../images/help_logo.gif) top right no-repeat !important; } .docs h2, .docs h3 { border-top: solid 1px #000; } #apphead h2 em { color: #777; } .tabs th { border-right: 1px solid #333; background-color: #ddd; color: #fff; border-left: 1px solid #fff; } .tabs td { background-color: #999; border-bottom: 1px solid #fff; border-right: 1px solid #fff; border-left: 1px solid #fff; } .tabs { border-bottom: 6px #ddd solid; } .tabs th, .tabs th a:link, .tabs th a:visited { color: #555; } .tabs td, .tabs td a:link, .tabs td a:visited { color: #fff; } .tabs a { text-decoration: none; } .axial th { background-color: #ddd; color: black; } .alert { background-color: #ff9; } .expandedwaste { background: url(../images/icon_arrowwaste2_sml.gif) no-repeat; } .collapsedwaste { background: url(../images/icon_arrowwaste1_sml.gif) no-repeat; } .filebrowse .expanded, .filebrowse-alt .expanded { background-image: url(../images/icon_arrowfolderopen2_sml.gif); background-repeat: no-repeat; } .filebrowse .collapsed, .filebrowse-alt .collapsed { background-image: url(../images/icon_arrowfolderclosed1_sml.gif); background-repeat: no-repeat; } .filebrowse .leafnode, .filebrowse-alt .leafnode { background-image: url(../images/icon_folder_sml.gif); background-repeat: no-repeat; } .filebrowse .leaf, .filebrowse-alt .leaf { background-image: url(../images/icon_doc_sml.gif); background-repeat: no-repeat; } .sortup { background: url(../images/icon_sortup.gif) no-repeat; } .sortdown { background: url(../images/icon_sortdown.gif) no-repeat; } .collapsedwaste { background: url(../images/icon_arrowwaste1_sml.gif) no-repeat; } body .grid td { border-top: 1px solid #ccc; border-left: 1px solid #ccc; background-color: transparent; } .confirm { color: #090; } .info { color: #069; } .errormessage, .warningmessage, .donemessage, .infomessage { border-top: 5px solid #900; border-left: 1px solid #900; background-image: url(../images/icon_error_lrg.gif); background-repeat: no-repeat; background-position: 5px 1.33em; } .warningmessage { background-image: url(../images/icon_warning_lrg.gif); border-color: #c60; } .donemessage { background-image: url(../images/icon_success_lrg.gif); border-color: #090; } .infomessage { background-image: url(../images/icon_info_lrg.gif); border-color: #069; } .docinfo { background: url(../images/icon_doc_lrg.gif) no-repeat; } .dirinfo { background: url(../images/icon_folder_lrg.gif) no-repeat; } .memberinfo { background: url(../images/icon_members_lrg.gif) no-repeat; } .usergroupinfo { background: url(../images/icon_usergroups_lrg.gif) no-repeat; } .errormark, .warningmark, .donemark, .infomark { background: url(../images/icon_error_sml.gif) no-repeat; } .warningmark { background-image: url(../images/icon_warning_sml.gif); } .donemark { background-image: url(../images/icon_success_sml.gif); } .infomark { background-image: url(../images/icon_info_sml.gif); } .cvsdiff, .cvsblame { background-color: #ccc; } .cvsdiffadd { background-color: #afa; } .cvsdiffremove { background-color: #faa; } .cvsdiffchanges1 { background-color: #ff7; } .cvsdiffchanges2 { background-color: #ff7; } li.selection ul a { background: #fff; } .band1 { color: #fff; background-color: #663; } .band2 { color: #fff; background-color: #66C; } .band3 { background-color: #C99; } .band4 { background-color: #CFF; } .band5 { color: #fff; background-color: #336; } .band6 { color: #fff; background-color: #966; } .band7 { background-color: #9CC; } .band8 { background-color: #FFC; } .band9 { color: #fff; background-color: #633; } .band10 { color: #fff; background-color: #699; } .band11 { background-color: #CC9; } .band12 { background-color: #CCF; } .band13 { color: #fff; background-color: #366; } .band14 { color: #fff; background-color: #996; } .band15 { background-color: #99C; } .band16 { background-color: #FCC; } .contentBox .helplink, #helptext .helplink { cursor: help; } .legend th, .bars th { background-color: #fff; } /* font and text properties, exclusive of link indication, alignment, text-indent */ body, th, td, input, select { font-family: Verdana, Helvetica, Arial, sans-serif; } code, pre { font-family: 'Andale Mono', Courier, monospace; } body, .contentBox h2, .contentBox h3, #rightcol h2, pre, code, #apphead h2 small, h3, th, td { font-size: x-small; voice-family: "\"}\""; voice-family: inherit; font-size: small; } small, div#footer, div#login, div.tabs th, div.tabs td, input, select, .paginate, .functnbar, .functnbar2, .functnbar3, #breadcrumbs, .courtesylinks, #rightcol div.help, .colbar, .tasknav, body.docs div#toc, #leftColumn, .legend, .bars { font-size: xx-small; voice-family: "\"}\""; voice-family: inherit; font-size: x-small; } .tabs td, .tabs th, dt, .tasknav .selfref, #login .username, .selection { font-weight: bold; } li.selection ul { font-weight: normal; } #apphead h2 em { font-style: normal; } #banner h1 { font-size: 1.25em; } /* box properties (exclusive of borders), positioning, alignments, list types, text-indent */ #bodyColumn h2 { margin-top: .3em; margin-bottom: .5em; } p, ul, ol, dl, .bars table { margin-top: .67em; margin-bottom: .67em; } form { margin: 0; } #bodyColumn { padding-left: 12px; padding-right: 12px; width: 100%; voice-family: "\"}\""; voice-family: inherit; width: auto; } html>body #bodyColumn { width: auto; } .docs { line-height: 1.4; } ol ol { list-style-type: lower-alpha; } ol ol ol { list-style-type: lower-roman; } .contentBox h2, .contentBox h3 { padding: 5px; margin-right: 2px; } .contentBox td, .contentBox th { padding: 2px 3px; } .h2 p, .h3 p, .h2 dt, .h3 dt { margin-right: 7px; margin-left: 7px; } .tasknav { margin-bottom: 1.33em; } div.colbar { padding: 3px; margin: 2px 2px 0; } .tabs { margin-top: .67em; margin-right: 2px; margin-left: 2px; padding-left: 8px; } .tabs td, .tabs th { padding: 3px 9px; } #rightcol div.www, #rightcol div.help { padding: 0 .5em; } body.docs #toc { position: absolute; top: 15px; left: 0px; width: 120px; padding: 0 20px 0 0; } body.docs #toc ul, #toc ol { margin-left: 0; padding-left: 0; } body.docs #toc li { margin-top: 7px; padding-left: 10px; list-style-type: none; } body.docs div.docs { margin: 61px 0 0 150px; padding: 1em 2em 1em 1em !important; } .docs p+p { text-indent: 5%; margin-top: -.67em; } .docs h2, .docs h3 { margin-bottom: .1em; padding-top: .3em; } .functnbar, .functnbar2, .functnbar3 { padding: 5px; margin: .67em 2px; } .functnbar3 { margin-top: 0; } body { padding: 1em; } body.composite, body.docs { margin: 0; padding: 0; } th, td { text-align: left; vertical-align: top; } .right { text-align: right !important; } .center { text-align: center !important; } .axial th, .axial th .strut { text-align: right; } .contentBox .axial td th { text-align: left; } body .stb { margin-top: 1em; text-indent: 0; } body .mtb { margin-top: 2em; text-indent: 0; } .courtesylinks { margin-top: 1em; padding-top: 1em; } dd { margin-bottom: .67em; } .toolgroup { margin-bottom: 6px; } .toolgroup .body { padding: 4px 4px 4px 0; } .toolgroup .label { padding: 4px; } .toolgroup .body div { padding-bottom: .3em; padding-left: 1em; } .toolgroup .body div div { margin-top: .3em; padding-bottom: 0; } .tier1 { margin-left: 0; } .tier2 { margin-left: 1.5em; } .tier3 { margin-left: 3em; } .tier4 { margin-left: 4.5em; } .tier5 { margin-left: 6em; } .tier6 { margin-left: 7.5em; } .tier7 { margin-left: 9em; } .tier8 { margin-left: 10.5em; } .tier9 { margin-left: 12em; } .tier10 { margin-left: 13.5em; } .filebrowse .expanded, .filebrowse .collapsed { padding-left: 34px; } .filebrowse .leafnode, .filebrowse .leaf { padding-left: 20px; } .messagechild { padding-left: 34px; } .filebrowse-alt .expanded, .filebrowse-alt .collapsed, .filebrowse-alt .leaf, .filebrowse-alt .leafnode, .expandedwaste, .collapsedwaste, .sortup, .sortdown { /* hide from macie5\*/ float: left; /* resume */ display: inline-block; height: 15px; width: 34px; padding-left: 0 !important; } .filebrowse-alt .leaf, .filebrowse-alt .leafnode, .sortup, .sortdown { width: 20px; } .filebrowse ul, .filebrowse-alt ul { list-style-type: none; padding-left: 0; margin-left: 0; } .filebrowse ul ul, .filebrowse-alt ul ul { margin-left: 1.5em; margin-top: 0; padding-top: .67em; } .filebrowse li, .filebrowse-alt li { margin-bottom: .67em; } td.filebrowse h2 { margin-top: 0; } .errormessage, .warningmessage, .donemessage, .infomessage, .docinfo, .dirinfo, .memberinfo, .usergroupinfo { margin: .67em 0; padding: .33em 0 .67em 42px; min-height: 32px; } .errormark, .warningmark, .donemark, .infomark { padding-left: 20px; min-height: 15px; } .alt { display: none; } #banner h1 { margin: 0; } .axial th, .axial th .strut, #leftColumn .strut { width: 12em; } #breadcrumbs { padding: 2px 8px; } /* Bad for IE .contentBox h2, .contentBox h3, .bars { clear: both; } */ .legend { float: right; } .legend th, .bars th { text-align: right; padding-left: 1em; } .bars table { table-layout: fixed; } .bars th { width: 12em; } #projectdocumentlist td.filebrowse-alt { padding-right: .75em; } #organizationLogo img, #projectLogo img, #projectLogo span{ margin: 8px; } commons-httpclient-3.1/docs/style/maven-stylus.css100644 0 0 7521 10661532627 17621 0ustar 0 0 body { background-color: #fff; font-family: Verdana, Helvetica, Arial, sans-serif; margin-left: auto; margin-right: auto; background-repeat: repeat-y; font-size: 13px; padding: 0px; } td, td p, select, input, li{ font-family: Verdana, Helvetica, Arial, sans-serif; font-size: 12px; color:#333333; } code{ font-size: 12px; } a { text-decoration: none; } a:link { color:#47a; } a:visited { color:#666666; } a:active, a:hover { color:#990000; } #legend li.externalLink { background: url(../images/external.png) left top no-repeat; padding-left: 18px; } a.externalLink, a.externalLink:link, a.externalLink:visited, a.externalLink:active, a.externalLink:hover { background: url(../images/external.png) right center no-repeat; padding-right: 18px; } #breadcrumbs a.externalLink, #breadcrumbs a.externalLink:link, #breadcrumbs a.externalLink:visited, #breadcrumbs a.externalLink:active, #breadcrumbs a.externalLink:hover { background: none; padding-right: 0px; } #legend li.newWindow { background: url(../images/newwindow.png) left top no-repeat; padding-left: 18px; } a.newWindow, a.newWindow:link, a.newWindow:visited, a.newWindow:active, a.newWindow:hover { background: url(../images/newwindow.png) right center no-repeat; padding-right: 18px; } #breadcrumbs a.newWindow, #breadcrumbs a.newWindow:link, #breadcrumbs a.newWindow:visited, #breadcrumbs a.newWindow:active, #breadcrumbs a.newWindow:hover { background: none; padding-right: 0px; } h2 { font-size: 17px; color: #333333; } h3 { padding: 4px 4px 4px 24px; color: #666; background-color: #ccc; font-weight: bold; font-size: 14px; background-image: url(../images/h3.gif); background-repeat: no-repeat; background-position: left bottom; } p { line-height: 1.3em; font-size: 12px; color: #000; } #breadcrumbs { height: 13px; background-image: url(../images/breadcrumbs.jpg); padding: 5px 10px 14px 20px; } * html #breadcrumbs { padding-bottom: 8px; } #leftColumn { margin: 10px 0 10px 0; border-top-color: #ccc; border-top-style: solid; border-top-width: 1px; border-right-color: #ccc; border-right-style: solid; border-right-width: 1px; border-bottom-color: #ccc; border-bottom-style: solid; border-bottom-width: 1px; padding-right: 5px; padding-left: 5px; } #navcolumn h5 { font-size: smaller; border-bottom: 1px solid #aaaaaa; padding-top: 2px; padding-left: 9px; color: #49635a; background-image: url(../images/h5.jpg); background-repeat: no-repeat; background-position: left bottom; } table.bodyTable th { color: white; background-color: #bbb; text-align: left; font-weight: bold; } table.bodyTable th, table.bodyTable td, table.bodyTable td p { font-size: 11px; } table.bodyTable tr.a { background-color: #ddd; } table.bodyTable tr.b { background-color: #eee; } .source { border: 1px solid #999; overflow:auto } dt { padding: 4px 4px 4px 24px; color: #333333; background-color: #ccc; font-weight: bold; font-size: 14px; background-image: url(../images/h3.gif); background-repeat: no-repeat; background-position: left bottom; } .subsectionTitle { font-size: 13px; font-weight: bold; color: #666; } table { font-size: 10px; } .xright a:link, .xright a:visited, .xright a:active { color: #666; } .xright a:hover { color: #003300; } #banner { height: 93px; background: url(../images/banner.jpg); } #navcolumn ul { margin: 5px 0 15px -0em; } #navcolumn ul ul { margin: 0px 0 0px -0em; } #navcolumn ul a { color: #333333; } #navcolumn ul a:hover { color: red; } #intro { border: solid #ccc 1px; margin: 6px 0px 0px 0px; padding: 10px 40px 10px 40px; } .subsection { margin-left: 3px; color: #333333; } .subsection p { font-size: 12px; } #footer { padding: 10px; margin: 20px 0px 20px 0px; border-top: solid #ccc 1px; color: #333333; } #organizationLogo img, #projectLogo img, #projectLogo span{ margin: 0px; } commons-httpclient-3.1/docs/style/maven-theme.css100644 0 0 3770 10661532627 17362 0ustar 0 0 body { padding: 0px 0px 10px 0px; } body, td, select, input, li{ font-family: Verdana, Helvetica, Arial, sans-serif; font-size: 13px; } code{ font-size: 13px; } a { text-decoration: none; } a:link { color:#36a; } a:visited { color:#47a; } a:active, a:hover { color:#69c; } #legend li.externalLink { background: url(../images/external.png) left top no-repeat; padding-left: 18px; } a.externalLink, a.externalLink:link, a.externalLink:visited, a.externalLink:active, a.externalLink:hover { background: url(../images/external.png) right center no-repeat; padding-right: 18px; } #legend li.newWindow { background: url(../images/newwindow.png) left top no-repeat; padding-left: 18px; } a.newWindow, a.newWindow:link, a.newWindow:visited, a.newWindow:active, a.newWindow:hover { background: url(../images/newwindow.png) right center no-repeat; padding-right: 18px; } h2 { padding: 4px 4px 4px 6px; border: 1px solid #999; color: #900; background-color: #ddd; font-weight:900; font-size: x-large; } h3 { padding: 4px 4px 4px 6px; border: 1px solid #aaa; color: #900; background-color: #eee; font-weight: normal; font-size: large; } p { line-height: 1.3em; font-size: small; } #breadcrumbs { border-top: 1px solid #aaa; border-bottom: 1px solid #aaa; background-color: #ccc; } #leftColumn { margin: 10px 0 0 5px; border: 1px solid #999; background-color: #eee; } #navcolumn h5 { font-size: smaller; border-bottom: 1px solid #aaaaaa; padding-top: 2px; } table.bodyTable th { color: white; background-color: #bbb; text-align: left; font-weight: bold; } table.bodyTable th, table.bodyTable td { font-size: 1em; } table.bodyTable tr.a { background-color: #ddd; } table.bodyTable tr.b { background-color: #eee; } .source { border: 1px solid #999; } dt.question { color: #900; background-color: #eee; } #organizationLogo img, #organizationLogo span, #projectLogo img, #projectLogo span{ margin: 8px; } #banner { border-bottom: 1px solid #fff; } commons-httpclient-3.1/docs/style/print.css100644 0 0 317 10661532627 16262 0ustar 0 0 #banner, #footer, #leftcol, #breadcrumbs, .docs #toc, .docs .courtesylinks, #leftColumn, #navColumn { display: none; } #bodyColumn, body.docs div.docs { margin: 0 !important; border: none !important } commons-httpclient-3.1/docs/style/project.css100644 0 0 102 10661532627 16564 0ustar 0 0 @import url("http://jakarta.apache.org/style/jakarta-maven.css"); commons-httpclient-3.1/docs/task-list.html100644 0 0 340413 10661532631 16134 0ustar 0 0 HttpClient - Todos

Todos

Class Class Todos Count Method Todos Count Field Todos Count
No class, method or field todo found

commons-httpclient-3.1/docs/team-list.html100644 0 0 101165 10661532631 16117 0ustar 0 0 HttpClient - Project Team

The Team

A successful project requires many people to play many roles. Some members write code or documentation, while others are valuable as testers, submitting patches and suggestions.

The team is comprised of Members and Contributors. Members have direct access to the source of a project and actively evolve the code-base. Contributors improve the project through submission of patches and suggestions to the Members. The number of Contributors to the project is unbounded. Get involved today. All contributions to the project are greatly appreciated.

Members

The following is a list of developers with commit privileges that have directly contributed to the project in one way or another.

Name Id Email Organization Roles TZ Offset Time
Michael Becke mbecke mbecke -at- apache.org Release Prime

Java Developer

Unknown
Jeff Dever jsdever jsdever -at- apache.org Independent consultant 2.0 Release Prime

Java Developer

Unknown
dIon Gillard dion dion -at- apache.org Multitask Consulting Java Developer

Unknown
Ortwin Glueck oglueck oglueck -at- apache.org Java Developer

Unknown
Sung-Gu jericho jericho -at- apache.org Java Developer

Unknown
Oleg Kalnichevski olegk olegk -at- apache.org Java Developer

Unknown
Sean C. Sullivan sullis sullis -at- apache.org Independent consultant Java Developer

Unknown
Adrian Sutton adrian adrian.sutton -at- ephox.com Intencha Java Developer

Unknown
Rodney Waldhoff rwaldhoff rwaldhoff -at- apache Britannica Java Developer

Unknown

Contributors

The following additional people have contributed to this project through the way of suggestions, patches or documentation.

Name Email Organization Roles TZ Offset Time
Armando Anton armando.anton -at- newknow.com Unknown
Sebastian Bazley sebb -at- apache.org Unknown
Ola Berg Unknown
Sam Berlin sberlin -at- limepeer.com Unknown
Mike Bowler Unknown
Samit Jain jain.samit -at- gmail.com Unknown
Eric Johnson eric -at- tibco.com Unknown
Christian Kohlschuetter ck -at- newsclub.de Unknown
Ryan Lubke Ryan.Lubke -at- Sun.COM Unknown
Sam Maloney sam.maloney -at- filogix.com Unknown
Rob Di Marco rdimarco -at- hmsonline.com Unknown
Juergen Pill Juergen.Pill -at- softwareag.com Unknown
Mohammad Rezaei mohammad.rezaei -at- gs.com Unknown
Roland Weber rolandw -at- apache.org Unknown
Laura Werner laura -at- lwerner.org Unknown
Mikael Wilstrom mikael.wikstrom -at- it.su.se Unknown

commons-httpclient-3.1/docs/threading.html100644 0 0 22274 10661532631 16150 0ustar 0 0 HttpClient - Threading

Introduction

This document provides an overview of how to use HttpClient safely from within a multi-threaded environment. It is broken down into the following main sections:

Please see the MultiThreadedExample for a concrete example.

MultiThreadedHttpConnectionManager

The main reason for using multiple theads in HttpClient is to allow the execution of multiple methods at once (Simultaniously downloading the latest builds of HttpClient and Tomcat for example). During execution each method uses an instance of an HttpConnection. Since connections can only be safely used from a single thread and method at a time and are a finite resource, we need to ensure that connections are properly allocated to the methods that require them. This job goes to the MultiThreadedHttpConnectionManager.

To get started one must create an instance of the MultiThreadedHttpConnectionManager and give it to an HttpClient. This looks something like:

      	MultiThreadedHttpConnectionManager connectionManager = 
      		new MultiThreadedHttpConnectionManager();
      	HttpClient client = new HttpClient(connectionManager);
      

This instance of HttpClient can now be used to execute multiple methods from multiple threads. Each subsequent call to HttpClient.executeMethod() will go to the connection manager and ask for an instance of HttpConnection. This connection will be checked out to the method and as a result it must also be returned. More on this below in Connection Release.

Options

The MultiThreadedHttpConnectionManager supports the following options:

connectionStaleCheckingEnabled The connectionStaleCheckingEnabled flag to set on all created connections. This value should be left true except in special circumstances. Consult the HttpConnection docs for more detail.
maxConnectionsPerHost The maximum number of connections that will be created for any particular HostConfiguration. Defaults to 2.
maxTotalConnections The maximum number of active connections. Defaults to 20.

In general the connection manager makes an attempt to reuse connections for a particular host while still allowing different connections to be used simultaneously. Connection are reclaimed using a least recently used approach.

Connection Release

One main side effect of connection management is that connections must be manually released when no longer used. This is due to the fact that HttpClient cannot determine when a method is no longer using its connection. This occurs because a method's response body is not read directly by HttpClient, but by the application using HttpClient. When the response is read it must obviously make use of the method's connection. Thus, a connection cannot be released from a method until the method's response body is read which is after HttpClient finishes executing the method. The application therefore must manually release the connection by calling releaseConnection() on the method after the response body has been read. To safely ensure connection release HttpClient should be used in the following manner:


      	MultiThreadedHttpConnectionManager connectionManager = 
      		new MultiThreadedHttpConnectionManager();
      	HttpClient client = new HttpClient(connectionManager);
			...
        // and then from inside some thread executing a method
        GetMethod get = new GetMethod("http://jakarta.apache.org/");
        try {
            client.executeMethod(get);
            // print response to stdout
            System.out.println(get.getResponseBodyAsStream());
        } finally {
            // be sure the connection is released back to the connection 
            // manager
            get.releaseConnection();
        }
    

Particularly, notice that the connection is released regardless of what the result of executing the method was or whether or not an exception was thrown. For every call to HttpClient.executeMethod there must be a matching call to method.releaseConnection().


commons-httpclient-3.1/docs/troubleshooting.html100644 0 0 20020 10661532631 17415 0ustar 0 0 HttpClient - Trouble Shooting HttpClient

Introduction

This document outlines some of the techniques that often help when trying to track down a problem in HttpClient. Please try the suggestions on this page before emailing the user or dev lists with questions. If none of these things help, please provide the information they provide to help the developers track down the problem.

Things To Try

  1. Try connecting with a normal browser and make sure the server gives the right response.
  2. If you're using a proxy server try without it if possible.
  3. Try the same code on a different server (preferably running different server software).
  4. Check that your code matches the general pattern for using HttpClient as described in the tutorial.
  5. Set the User-Agent request header to masquerade HttpClient as a popular browser such as IE or Firefox. Certain web sites are optimized to work with just one or a number of specific browser applications. These sites frequently reject requests originating from user agents they do not recognize. For example, setting the User-Agent request header to Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0) would deceive the target server into believing that the request was issues by Microsoft Internet Explorer 6.0 on Windows 2000.
  6. Set the logging level to debug and check the output for the cause of the problem.
  7. Enable the wire trace and follow the communication between the client and server to determine where the problem is occurring.
  8. Consult the "Known limitations and problems" section of the SSL Guide and the Authentication Guide to see if this is a known problem and follow the instructions given in these resources
  9. Use telnet or netcat to manually send the request to the server. This is particularly useful once you think you know what the problem is and you want to easily test that changing what HttpClient sends will fix it.
  10. Use netcat in listen mode to act as the server and check how HttpClient handles various responses.
  11. Try updating to the latest nightly build of HttpClient. Bugs happen and they are generally fixed pretty quickly so testing against the latest build is often worthwhile.

Asking For Help

If you've tried the things above and still can't work out how to fix the problem, it might be time to contact the mailing list for support. All questions, bug reports etc should be directed to the HttpClient user list.

When you do send off the email, please include as much detail as you can, particularly inlined wire trace logs as there is almost nothing we can do to help without them. If you are seeing exceptions being thrown, the full stack trace is essential to tracking down the problem. Any of the information you gained from the "things to try" section above are probably worth mentioning.

Reporting Bugs

If you're fairly certain that the problem is a bug in HttpClient, log it in JIRA. Make sure you spend some time searching the existing bugs to make sure it hasn't already been logged. If you're unsure about whether or not to log something in JIRA, it's probably worth bringing it up on the developer mailing list to clarify the situation.


commons-httpclient-3.1/docs/tutorial.html100644 0 0 37235 10661532631 16051 0ustar 0 0 HttpClient - HttpClient Tutorial

Overview

This tutorial is designed to provide a basic overview of how to use HttpClient. When you have completed the tutorial you will have written a simple application that downloads a page using HttpClient.

It is assumed that you have an understanding of how to program in Java and are familiar with the development environment you are using.

Getting Ready

The first thing you need to do is get a copy of HttpClient and its dependencies. This tutorial was written for HttpClient 3.0. You will also need JDK 1.3 or above.

Once you've downloaded HttpClient and dependencies you will need to put them on your classpath. There is also an optional dependency on JSSE which is required for HTTPS connections; this is not required for this tutorial.

Concepts

The general process for using HttpClient consists of a number of steps:

  1. Create an instance of HttpClient.
  2. Create an instance of one of the methods (GetMethod in this case). The URL to connect to is passed in to the the method constructor.
  3. Tell HttpClient to execute the method.
  4. Read the response.
  5. Release the connection.
  6. Deal with the response.

We'll cover how to perform each of these steps below. Notice that we go through the entire process regardless of whether the server returned an error or not. This is important because HTTP 1.1 allows multiple requests to use the same connection by simply sending the requests one after the other. Obviously, if we don't read the entire response to the first request, the left over data will get in the way of the second response. HttpClient tries to handle this but to avoid problems it is important to always release the connection.

Upon the connection release HttpClient will do its best to ensure that the connection is reusable.

It is important to always release the connection regardless of whether the server returned an error or not.

Instantiating HttpClient

The no argument constructor for HttpClient provides a good set of defaults for most situations so that is what we'll use.

HttpClient client = new HttpClient();

Creating a Method

The various methods defined by the HTTP specification correspond to the various classes in HttpClient which implement the HttpMethod interface. These classes are all found in the package org.apache.commons.httpclient.methods.

We will be using the Get method which is a simple method that simply takes a URL and gets the document the URL points to.

HttpMethod method = new GetMethod("http://www.apache.org/");

Execute the Method

The actual execution of the method is performed by calling executeMethod on the client and passing in the method to execute. Since networks connections are unreliable, we also need to deal with any errors that occur.

There are two kinds of exceptions that could be thrown by executeMethod, HttpException and IOException.

The other useful piece of information is the status code that is returned by the server. This code is returned by executeMethod as an int and can be used to determine if the request was successful or not and can sometimes indicate that further action is required by the client such as providing authentication credentials.

HttpException

An HttpException represents a logical error and is thrown when the request cannot be sent or the response cannot be processed due to a fatal violation of the HTTP specification. Usually this kind of exceptions cannot be recovered from. For a detailed discussion on protocol exceptions please refer to the HttpClient exception handling guide. Note that HttpException actually extends IOException so you can just ignore it and catch the IOException if your application does not distinguish between protocol and transport errors.

IOException

A plain IOException (which is not a subclass of HttpException) represents a transport error and is thrown when an error occurs that is likely to be a once-off I/O problem. Usually the request has a good chance of succeeding on a second attempt, so per default HttpClient will try to recover the request automatically. For a detailed discussion on transport exceptions please refer to the HttpClient exception handling guide.

Method recovery

Per default HttpClient will automatically attempt to recover from the not-fatal errors, that is, when a plain IOException is thrown. HttpClient will retry the method three times provided that the request has never been fully transmitted to the target server. For a detailed discussion on HTTP method recovery please refer to the HttpClient exception handling guide

// set per default
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
  new DefaultHttpMethodRetryHandler());

Default recovery procedure can be replaced with a custom one. The number of automatic retries can be increased. HttpClient can also be instructed to retry the method even though the request may have already been processed by the server and the I/O exception has occurred while receiving the response. Please exercise caution when enabling auto-retrial. Use it only if the method is known to be idempotent, that is, it is known to be safe to retry multiple times without causing data corruption or data inconsistency.

The rule of thumb is GET methods are usually safe unless known otherwise, entity enclosing methods such as POST and PUT are usually unsafe unless known otherwise.

DefaultMethodRetryHandler retryhandler = new DefaultMethodRetryHandler(10, true);
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);

Read the Response

It is vital that the response body is always read regardless of the status returned by the server. There are three ways to do this:

  • Call method.getResponseBody(). This will return a byte array containing the data in the response body.
  • Call method.getResponseBodyAsString(). This will return a String containing the response body. Be warned though that the conversion from bytes to a String is done using the default encoding so this method may not be portable across all platforms.
  • Call method.getResponseBodyAsStream() and read the entire contents of the stream then call stream.close(). This method is best if it is possible for a lot of data to be received as it can be buffered to a file or processed as it is read. Be sure to always read the entirety of the data and call close on the stream.

For this tutorial we will use getResponseBody() for simplicity.

byte[] responseBody = method.getResponseBody();

Release the Connection

This is a crucial step to keep things flowing. We must tell HttpClient that we are done with the connection and that it can now be reused. Without doing this HttpClient will wait indefinitely for a connection to free up so that it can be reused.

method.releaseConnection();

Deal with the Repsonse

We've now completed our interaction with HttpClient and can just concentrate on doing what we need to do with the data. In our case, we'll just print it out to the console.

It's worth noting that if you were retrieving the response as a stream and processing it as it is read, this step would actually be combined with reading the connection, and when you'd finished processing all the data, you'd then close the input stream and release the connection.

Note: We should pay attention to character encodings here instead of just using the system default.

System.out.println(new String(responseBody));

Final Source Code

When we put all of that together plus a little bit of glue code we get the program below.

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {
  
  private static String url = "http://www.apache.org/";

  public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);
    
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
    		new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}

commons-httpclient-3.1/docs/userguide.html100644 0 0 15631 10661532631 16176 0ustar 0 0 HttpClient - HttpClient User Guide

User Guide

The HttpClient user guide is designed to help developers use HttpClient in their applications. While the concept of a user guide being for developers may seem strange, the term developer guide is already in use for helping people develop HttpClient.

Overview

Document Description
Authentication Guide This document describes the authentication schemes supported by HttpClient and how to use them.
Character Encodings Guidelines for correctly detecting the character encoding to use when sending and receiving data with HttpClient.
Redirects Handling Provide sample code for custom redirects handling.
Exception Handling This document outlines common types of errors that the users may encounter and describes the exception handling framework used by HttpClient.
Logging Guide This document describes the logging mechanism used by HttpClient and how to control what it outputs.
Methods This document describes the various methods that are provided by HttpClient and how to use them.
Optimization Guide This document outlines HttpClient performance optimization techniques.
Preference Architecture This document explains the preference architecture used by HttpClient and enumerates standard HttpClient parameters.
Sample Code This is a link to the sample code for using HttpClient that is stored in the Subversion repository and is available in source releases of HttpClient.
Trouble Shooting This document provides hints and tips for debugging problems with HttpClient.
Tutorial This document provides a simple introductory tutorial for new users of HttpClient.

commons-httpclient-3.1/docs/xref-test/allclasses-frame.html100644 0 0 33134 10661532627 21344 0ustar 0 0 All Classes

All Classes

commons-httpclient-3.1/docs/xref-test/index.html100644 0 0 1243 10661532627 17211 0ustar 0 0 HttpClient 3.1 Reference <h1>Frame Alert</h1> <p> You don't have frames. Go <a href="overview-summary.html">here</a> </p> ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/AccessibleHttpConnectionManager.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/AccessibleHttpConnectionManager.100644 0 0 11713 10661532627 31311 0ustar 0 0 AccessibleHttpConnectionManager xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/AccessibleHttpConnectionManager.java,v 1.1 2004/10/16 22:40:08 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * A simple connection manager that provides access to the connection used.
35   */
36  public class AccessibleHttpConnectionManager extends SimpleHttpConnectionManager {
37  
38      
39      public AccessibleHttpConnectionManager() {
40      }
41      
42      public HttpConnection getConection() {
43          return httpConnection;
44      }
45      
46  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/EchoService.html100644 0 0 15067 10661532627 26173 0ustar 0 0 EchoService xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/EchoService.java,v 1.2 2004/11/20 17:56:39 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient;
31  
32  import java.io.IOException;
33  
34  import org.apache.commons.httpclient.server.HttpService;
35  import org.apache.commons.httpclient.server.SimpleRequest;
36  import org.apache.commons.httpclient.server.SimpleResponse;
37  
38  
39  /**
40   * A service that echos the request body.
41   */
42  public class EchoService implements HttpService {
43  
44      public EchoService() {
45          super();
46      }
47  
48      public boolean process(final SimpleRequest request, final SimpleResponse response)
49          throws IOException
50      {
51          HttpVersion httpversion = request.getRequestLine().getHttpVersion();
52          response.setStatusLine(httpversion, HttpStatus.SC_OK);
53          if (request.containsHeader("Content-Length")) {
54              response.addHeader(request.getFirstHeader("Content-Length"));            
55          }
56          if (request.containsHeader("Content-Type")) {
57              response.addHeader(request.getFirstHeader("Content-Type"));            
58          }
59          response.setBodyString(request.getBodyString());
60          return true;
61      }
62  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/ExecuteMethodThread.html100644 0 0 16011 10661532627 27655 0ustar 0 0 ExecuteMethodThread xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/ExecuteMethodThread.java,v 1.2 2004/02/22 18:08:49 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32  
33  package org.apache.commons.httpclient;
34  
35  /**
36   * Executes a method from a new thread.
37   * 
38   * @author Michael Becke
39   */
40  class ExecuteMethodThread extends Thread {
41      
42      private HttpMethod method;
43      private HttpClient client;
44      
45      private Exception exception;
46      
47      public ExecuteMethodThread(HttpMethod method, HttpClient client) {
48          this.method = method;
49          this.client = client;            
50      }
51  
52      public void run() {
53          try {
54              client.executeMethod(method);
55              method.getResponseBodyAsString();
56          } catch (Exception e) {
57              this.exception = e;
58          } finally {
59              method.releaseConnection();
60          }
61      }
62      
63      /**
64       * @return HttpMethod
65       */
66      public HttpMethod getMethod() {
67          return method;
68      }
69      
70      /**
71       * Gets the exception that occurred when executing the method.
72       * 
73       * @return an Exception or <code>null</code> if no exception occurred
74       */
75      public Exception getException() {
76          return exception;
77      }
78  
79  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/FakeHttpMethod.html100644 0 0 15412 10661532627 26635 0ustar 0 0 FakeHttpMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/FakeHttpMethod.java,v 1.2 2004/10/31 14:04:13 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   * 
28   */
29  
30  
31  package org.apache.commons.httpclient;
32  
33  /** 
34   * For test-nohost testing purposes only.
35   *
36   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
37   */
38  public class FakeHttpMethod extends HttpMethodBase{
39  
40  	public FakeHttpMethod(){
41  		super();
42  	}
43  
44  	public FakeHttpMethod(String path){
45  		super(path);
46  	}
47  
48  	public String getName() {
49  		return "Simple";
50  	}
51      
52      public void addResponseHeader(final Header header) {
53          getResponseHeaderGroup().addHeader(header);
54      }
55  
56      public String generateRequestLine(
57          final HttpConnection connection ,final HttpVersion version) {
58          if (connection == null) {
59              throw new IllegalArgumentException("Connection may not be null");
60          }
61          if (version == null) {
62              throw new IllegalArgumentException("HTTP version may not be null");
63          }
64          return HttpMethodBase.generateRequestLine(connection, 
65            this.getName(), this.getPath(), this.getQueryString(), version.toString());
66      }
67      
68  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/FeedbackService.html100644 0 0 17411 10661532627 26774 0ustar 0 0 FeedbackService xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/FeedbackService.java,v 1.1 2004/11/20 17:56:39 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient;
31  
32  import java.io.IOException;
33  import java.io.StringWriter;
34  
35  import org.apache.commons.httpclient.server.HttpService;
36  import org.apache.commons.httpclient.server.RequestLine;
37  import org.apache.commons.httpclient.server.SimpleRequest;
38  import org.apache.commons.httpclient.server.SimpleResponse;
39  
40  
41  public class FeedbackService implements HttpService {
42  
43      public FeedbackService() {
44          super();
45      }
46  
47      public boolean process(final SimpleRequest request, final SimpleResponse response)
48          throws IOException
49      {
50          RequestLine requestline = request.getRequestLine();
51          HttpVersion httpversion = requestline.getHttpVersion();
52  
53          StringWriter buffer = new StringWriter(100);
54          buffer.write("Method type: ");
55          buffer.write(requestline.getMethod());
56          buffer.write("\r\n");
57          buffer.write("Requested resource: ");
58          buffer.write(requestline.getUri());
59          buffer.write("\r\n");
60          buffer.write("Protocol version: ");
61          buffer.write(httpversion.toString());
62          buffer.write("\r\n");
63          
64          String requestbody = request.getBodyString();
65          if (requestbody != null && !requestbody.equals("")) {
66              buffer.write("\r\n");
67              buffer.write("Request body: ");
68              buffer.write(requestbody);
69              buffer.write("\r\n");
70          }
71          
72          response.setStatusLine(httpversion, HttpStatus.SC_OK);
73          response.setBodyString(buffer.toString());
74          return true;
75      }
76  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/HttpClientTestBase.html100644 0 0 32057 10661532627 27503 0ustar 0 0 HttpClientTestBase xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/HttpClientTestBase.java,v 1.7 2004/11/07 12:31:42 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient;
31  
32  import java.io.IOException;
33  
34  import junit.framework.Test;
35  import junit.framework.TestCase;
36  import junit.framework.TestSuite;
37  
38  import org.apache.commons.httpclient.protocol.Protocol;
39  import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
40  import org.apache.commons.httpclient.server.SimpleHttpServer;
41  import org.apache.commons.httpclient.server.SimplePlainSocketFactory;
42  import org.apache.commons.httpclient.server.SimpleProxy;
43  import org.apache.commons.httpclient.server.SimpleSocketFactory;
44  import org.apache.commons.httpclient.ssl.SimpleSSLSocketFactory;
45  import org.apache.commons.httpclient.ssl.SimpleSSLTestProtocolSocketFactory;
46  
47  /**
48   * Base class for test cases using 
49   * {@link org.apache.commons.httpclient.server.SimpleHttpServer} based 
50   * testing framework.
51   *
52   * @author Oleg Kalnichevski
53   * 
54   * @version $Id: HttpClientTestBase.java 480424 2006-11-29 05:56:49Z bayard $
55   */
56  public class HttpClientTestBase extends TestCase {
57  
58      protected HttpClient client = null;
59      protected SimpleHttpServer server = null;
60  
61      protected SimpleProxy proxy = null;
62      private boolean useProxy = false;
63      private boolean useSSL = false;
64      
65      // ------------------------------------------------------------ Constructor
66      public HttpClientTestBase(final String testName) throws IOException {
67          super(testName);
68      }
69  
70      // ------------------------------------------------------------------- Main
71      public static void main(String args[]) {
72          String[] testCaseName = { HttpClientTestBase.class.getName() };
73          junit.textui.TestRunner.main(testCaseName);
74      }
75  
76      // ------------------------------------------------------- TestCase Methods
77  
78      public static Test suite() {
79          return new TestSuite(HttpClientTestBase.class);
80      }
81  
82      public void setUseProxy(boolean useProxy) {
83          this.useProxy = useProxy;
84      }
85      
86      public void setUseSSL(boolean b) {
87          this.useSSL = b;
88      }
89      
90      public boolean isUseSSL() {
91          return this.useSSL;
92      }
93      
94      // ------------------------------------------------- TestCase setup/shutdown
95  
96      public void setUp() throws IOException {
97          // Configure socket factories
98          SimpleSocketFactory serversocketfactory = null; 
99          Protocol testhttp = null;
100         if (this.useSSL) {
101             serversocketfactory = new SimpleSSLSocketFactory(); 
102             testhttp = new Protocol("https", 
103                     (ProtocolSocketFactory)new SimpleSSLTestProtocolSocketFactory(), 443);
104         } else {
105             serversocketfactory = new SimplePlainSocketFactory(); 
106             testhttp = Protocol.getProtocol("http"); 
107         }
108 
109         this.server = new SimpleHttpServer(serversocketfactory, 0); // use arbitrary port
110         this.server.setTestname(getName());
111 
112         this.client = new HttpClient();
113 
114         this.client.getHostConfiguration().setHost(
115                 this.server.getLocalAddress(), 
116                 this.server.getLocalPort(),
117                 testhttp);
118         
119         if (this.useProxy) {
120             this.proxy = new SimpleProxy();
121             client.getHostConfiguration().setProxy(
122                 proxy.getLocalAddress(), 
123                 proxy.getLocalPort());                
124         }
125     }
126 
127     public void tearDown() throws IOException {
128         this.client = null;
129         this.server.destroy();
130         this.server = null;
131         if (proxy != null) {
132             proxy.destroy();
133             proxy = null;
134         }
135     }    
136 }

././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/NoHostHttpConnectionManager.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/NoHostHttpConnectionManager.html100644 0 0 31755 10661532627 31363 0ustar 0 0 NoHostHttpConnectionManager xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/NoHostHttpConnectionManager.java,v 1.9 2004/10/31 13:53:03 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32   
33  package org.apache.commons.httpclient;
34  
35  import java.io.IOException;
36  import java.io.InputStream;
37  
38  import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
39  
40  /**
41   */
42  public class NoHostHttpConnectionManager implements HttpConnectionManager {
43  
44      private HttpConnection connection;
45      
46      private boolean connectionReleased = false;
47      
48      private HttpConnectionManagerParams params = new HttpConnectionManagerParams(); 
49      
50      public NoHostHttpConnectionManager() { 
51          super();
52      }
53  
54      /**
55       * This method currently does nothing.
56       */
57      public void closeIdleConnections(long idleTimeout) {
58      }
59  
60      /**
61       * @return
62       */
63      public boolean isConnectionReleased() {
64          return connectionReleased;
65      }
66      
67      /**
68       * @param connection
69       */
70      public void setConnection(HttpConnection connection) {
71          this.connection = connection;
72          connection.setHttpConnectionManager(this);
73          connection.getParams().setDefaults(this.params);
74      }
75  
76      public HttpConnection getConnection(HostConfiguration hostConfiguration) {
77          
78          // make sure the host and proxy are correct for this connection
79          // close it and set the values if they are not
80          if (!hostConfiguration.hostEquals(connection)
81              || !hostConfiguration.proxyEquals(connection)) {
82                  
83              if (connection.isOpen()) {
84                  connection.close();
85              }
86  
87              connection.setHost(hostConfiguration.getHost());
88              connection.setPort(hostConfiguration.getPort());
89              connection.setProtocol(hostConfiguration.getProtocol());
90              connection.setLocalAddress(hostConfiguration.getLocalAddress());
91  
92              connection.setProxyHost(hostConfiguration.getProxyHost());
93              connection.setProxyPort(hostConfiguration.getProxyPort());
94          } else {
95              finishLastResponse(connection);
96          }
97          
98          connectionReleased = false;
99          return connection;
100     }
101 
102     /**
103      * @deprecated
104      */
105     public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout)
106         throws HttpException {
107         return getConnection(hostConfiguration);
108     }
109 
110     public HttpConnection getConnectionWithTimeout(
111         HostConfiguration hostConfiguration,
112         long timeout)
113         throws ConnectionPoolTimeoutException {
114         return getConnection(hostConfiguration);
115     }
116 
117     public void releaseConnection(HttpConnection conn) {
118         if (conn != connection) {
119             throw new IllegalStateException("Unexpected close on a different connection.");
120         }
121         
122         connectionReleased = true;
123         finishLastResponse(connection);
124     }
125 
126     /**
127      * Since the same connection is about to be reused, make sure the
128      * previous request was completely processed, and if not
129      * consume it now.
130      * @param conn The connection
131      */
132     static void finishLastResponse(HttpConnection conn) {
133         InputStream lastResponse = conn.getLastResponseInputStream();
134         if (lastResponse != null) {
135             conn.setLastResponseInputStream(null);
136             try {
137                 lastResponse.close();
138             } catch (IOException ioe) {
139                 //FIXME: badness - close to force reconnect.
140                 conn.close();
141             }
142         }
143     }
144 
145     public HttpConnectionManagerParams getParams() {
146         return this.params;
147     }
148 
149     public void setParams(final HttpConnectionManagerParams params) {
150         if (params == null) {
151             throw new IllegalArgumentException("Parameters may not be null");
152         }
153         this.params = params;
154     }
155 
156 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/NoncompliantHeadMethod.html100644 0 0 13227 10661532627 30354 0ustar 0 0 NoncompliantHeadMethod xref

1   /*
2    * ====================================================================
3    *
4    *  Licensed to the Apache Software Foundation (ASF) under one or more
5    *  contributor license agreements.  See the NOTICE file distributed with
6    *  this work for additional information regarding copyright ownership.
7    *  The ASF licenses this file to You under the Apache License, Version 2.0
8    *  (the "License"); you may not use this file except in compliance with
9    *  the License.  You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   *  Unless required by applicable law or agreed to in writing, software
14   *  distributed under the License is distributed on an "AS IS" BASIS,
15   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   *  See the License for the specific language governing permissions and
17   *  limitations under the License.
18   * ====================================================================
19   *
20   * This software consists of voluntary contributions made by many
21   * individuals on behalf of the Apache Software Foundation.  For more
22   * information on the Apache Software Foundation, please see
23   * <http://www.apache.org/>.
24   *
25   * [Additional notices, if required by prior licensing conditions]
26   *
27   */
28  package org.apache.commons.httpclient;
29  
30  import org.apache.commons.httpclient.methods.HeadMethod;
31  
32  /**
33   * HTTP GET methid intended to simulate side-effects of 
34   * interaction with non-compiant HTTP servers or proxies
35   * 
36   * @author Oleg Kalnichevski
37   */
38  
39  public class NoncompliantHeadMethod extends HeadMethod {
40  
41      public NoncompliantHeadMethod(){
42          super();
43      }
44  
45      public NoncompliantHeadMethod(String uri) {
46          super(uri);
47      }
48  
49  	/**
50  	 * Expect HTTP HEAD but perform HTTP GET instead in order to 
51       * simulate the behaviour of a non-compliant HTTP server sending
52       * body content in response to HTTP HEAD request 
53       *  
54  	 */
55  	public String getName() {
56  		return "GET";
57  	}
58  
59  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/NoncompliantPostMethod.html100644 0 0 16243 10661532627 30441 0ustar 0 0 NoncompliantPostMethod xref

1   /*
2    * ====================================================================
3    *
4    *  Licensed to the Apache Software Foundation (ASF) under one or more
5    *  contributor license agreements.  See the NOTICE file distributed with
6    *  this work for additional information regarding copyright ownership.
7    *  The ASF licenses this file to You under the Apache License, Version 2.0
8    *  (the "License"); you may not use this file except in compliance with
9    *  the License.  You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   *  Unless required by applicable law or agreed to in writing, software
14   *  distributed under the License is distributed on an "AS IS" BASIS,
15   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   *  See the License for the specific language governing permissions and
17   *  limitations under the License.
18   * ====================================================================
19   *
20   * This software consists of voluntary contributions made by many
21   * individuals on behalf of the Apache Software Foundation.  For more
22   * information on the Apache Software Foundation, please see
23   * <http://www.apache.org/>.
24   *
25   * [Additional notices, if required by prior licensing conditions]
26   *
27   */
28  package org.apache.commons.httpclient;
29  
30  import java.io.IOException;
31  import org.apache.commons.httpclient.methods.PostMethod;
32  
33  /**
34   * HTTP POST methid intended to simulate side-effects of 
35   * interaction with non-compiant HTTP servers or proxies
36   * 
37   * @author Oleg Kalnichevski
38   */
39  
40  public class NoncompliantPostMethod extends PostMethod {
41  
42      public NoncompliantPostMethod(){
43          super();
44      }
45  
46      public NoncompliantPostMethod(String uri) {
47          super(uri);
48      }
49  
50      /**
51       * NoncompliantPostMethod class skips "Expect: 100-continue"
52       * header when sending request headers to an HTTP server.
53       * 
54       * <p>
55       * That makes the server expect the request body to follow 
56       * immediately after the request head. The HTTP server does not 
57       * send status code 100 expected by the client. The client should 
58       * be able to recover gracefully by sending the request body 
59       * after a defined timeout without having received "continue"
60       * code.
61       * </p>
62       */
63      protected void writeRequestHeaders(HttpState state, HttpConnection conn)
64          throws IOException, HttpException {
65          addRequestHeaders(state, conn);
66          Header[] headers = getRequestHeaders();
67          for (int i = 0; i < headers.length; i++) {
68              Header header = headers[i];
69              // Write all the headers but "Expect"
70              if (!header.getName().equalsIgnoreCase("Expect") ) {
71                  conn.print(header.toExternalForm(), "US-ASCII");
72              }
73          }
74      }
75  
76  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/ProxyTestDecorator.html100644 0 0 16521 10661532627 27614 0ustar 0 0 ProxyTestDecorator xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/ProxyTestDecorator.java,v 1.1 2004/11/01 02:21:15 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient;
31  
32  import java.util.Enumeration;
33  
34  import junit.extensions.TestSetup;
35  import junit.framework.Test;
36  import junit.framework.TestSuite;
37  
38  
39  /**
40   * A TestDecorator that configures instances of HttpClientTestBase to use
41   * a proxy server.
42   */
43  public class ProxyTestDecorator extends TestSetup {
44  
45      /**
46       * Iterates through all test cases included in the suite and adds
47       * copies of them modified to use a proxy server.
48       * @param suite
49       */
50      public static void addTests(TestSuite suite) {
51          TestSuite ts2 = new TestSuite();
52          addTest(ts2, suite);
53          suite.addTest(ts2);        
54      }
55      
56      private static void addTest(TestSuite suite, Test t) {
57          if (t instanceof HttpClientTestBase) {
58              suite.addTest(new ProxyTestDecorator((HttpClientTestBase) t));
59          } else if (t instanceof TestSuite) {
60              Enumeration en = ((TestSuite) t).tests();
61              while (en.hasMoreElements()) {
62                  addTest(suite, (Test) en.nextElement());
63              }
64          }
65      }
66      
67      public ProxyTestDecorator(HttpClientTestBase test) {
68          super(test);
69      }
70              
71      protected void setUp() throws Exception {
72          HttpClientTestBase base = (HttpClientTestBase) fTest;
73          base.setUseProxy(true);
74      }        
75  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestAll.html100644 0 0 24353 10661532627 25342 0ustar 0 0 TestAll xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestAll.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   */
28  
29  package org.apache.commons.httpclient;
30  
31  import org.apache.commons.httpclient.auth.TestAuthAll;
32  import org.apache.commons.httpclient.cookie.TestCookieAll;
33  import org.apache.commons.httpclient.params.TestParamsAll;
34  
35  import junit.framework.*;
36  
37  /**
38   * @author Remy Maucherat
39   * @author Rodney Waldhoff
40   * @version $Id: TestAll.java 480424 2006-11-29 05:56:49Z bayard $
41   */
42  public class TestAll extends TestCase {
43  
44      public TestAll(String testName) {
45          super(testName);
46      }
47  
48      public static Test suite() {
49          TestSuite suite = new TestSuite();
50          // Fundamentals
51          suite.addTest(TestHttpMethodFundamentals.suite());
52          suite.addTest(TestHttpStatus.suite());
53          suite.addTest(TestStatusLine.suite());
54          suite.addTest(TestRequestLine.suite());
55          suite.addTest(TestHeader.suite());
56          suite.addTest(TestHeaderElement.suite());
57          suite.addTest(TestHeaderOps.suite());
58          suite.addTest(TestResponseHeaders.suite());
59          suite.addTest(TestRequestHeaders.suite());
60          suite.addTest(TestStreams.suite());
61          suite.addTest(TestParameterParser.suite());
62          suite.addTest(TestParameterFormatter.suite());
63          suite.addTest(TestNVP.suite());
64          suite.addTest(TestMethodCharEncoding.suite());
65          suite.addTest(TestHttpVersion.suite());
66          suite.addTest(TestEffectiveHttpVersion.suite());
67          suite.addTest(TestHttpParser.suite());
68          suite.addTest(TestBadContentLength.suite());
69          suite.addTest(TestEquals.suite());
70  		suite.addTest(TestQueryParameters.suite());
71          // Exceptions
72          suite.addTest(TestExceptions.suite());        
73          // HTTP state management
74          suite.addTest(TestHttpState.suite());
75          suite.addTest(TestCookieAll.suite());
76          // Authentication 
77          suite.addTest(TestCredentials.suite());
78          suite.addTest(TestAuthAll.suite());
79          // Redirects
80          suite.addTest(TestRedirects.suite());
81          // Connection management
82          suite.addTest(TestHttpConnection.suite());
83          suite.addTest(TestHttpConnectionManager.suite());
84          suite.addTest(TestConnectionPersistence.suite());
85          suite.addTest(TestIdleConnectionTimeout.suite());
86          suite.addTest(TestMethodAbort.suite());
87          // Preferences
88          suite.addTest(TestParamsAll.suite());
89          suite.addTest(TestVirtualHost.suite());        
90          suite.addTest(TestHostConfiguration.suite());        
91          // URIs
92          suite.addTest(TestURI.suite());
93          suite.addTest(TestURIUtil.suite());
94          suite.addTest(TestURIUtil2.suite());
95          // Method specific
96          suite.addTest(TestEntityEnclosingMethod.suite());
97          suite.addTest(TestPostParameterEncoding.suite());
98          suite.addTest(TestPostMethod.suite());
99          suite.addTest(TestPartsNoHost.suite());
100         suite.addTest(TestMultipartPost.suite());
101         // Non compliant behaviour
102         suite.addTest(TestNoncompliant.suite());
103         // Proxy
104         suite.addTest(TestProxy.suite());
105         suite.addTest(TestProxyWithRedirect.suite());
106         return suite;
107     }
108 
109     public static void main(String args[]) {
110         String[] testCaseName = { TestAll.class.getName() };
111         junit.textui.TestRunner.main(testCaseName);
112     }
113 
114 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestBadContentLength.html100644 0 0 44242 10661532627 30014 0ustar 0 0 TestBadContentLength xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestBadContentLength.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  package org.apache.commons.httpclient;
30  
31  import java.io.IOException;
32  import java.io.InputStream;
33  
34  import junit.framework.Test;
35  import junit.framework.TestCase;
36  import junit.framework.TestSuite;
37  
38  import org.apache.commons.httpclient.methods.GetMethod;
39  import org.apache.commons.httpclient.server.HttpRequestHandler;
40  import org.apache.commons.httpclient.server.RequestLine;
41  import org.apache.commons.httpclient.server.ResponseWriter;
42  import org.apache.commons.httpclient.server.SimpleHttpServer;
43  import org.apache.commons.httpclient.server.SimpleHttpServerConnection;
44  import org.apache.commons.httpclient.server.SimpleRequest;
45  
46  /**
47   * Tests HttpClient's behaviour when receiving more response data than expected.
48   * <p>
49   * A very simple HTTP Server will be setup on a free port during testing, which
50   * returns an incorrect response Content-Length, sending surplus response data,
51   * which may contain malicious/fake response headers.
52   * </p> 
53   * 
54   * @author Christian Kohlschuetter
55   * @version $Id: TestBadContentLength.java 480424 2006-11-29 05:56:49Z bayard $
56   */
57  public class TestBadContentLength extends TestCase {
58      private HttpClient client = null;
59      private SimpleHttpServer server = null;
60  
61      // ------------------------------------------------------------ Constructor
62      public TestBadContentLength(String testName) {
63          super(testName);
64      }
65  
66      // ------------------------------------------------------------------- Main
67      public static void main(String args[]) {
68          String[] testCaseName = { TestBadContentLength.class.getName()};
69          junit.textui.TestRunner.main(testCaseName);
70      }
71  
72      // ------------------------------------------------------- TestCase Methods
73  
74      public static Test suite() {
75          return new TestSuite(TestBadContentLength.class);
76      }
77  
78      // ----------------------------------------------------------- Test Methods
79  
80      public void setUp() throws IOException {
81          client = new HttpClient();
82          server = new SimpleHttpServer(); // use arbitrary port
83          server.setTestname(getName());
84          server.setRequestHandler(new MyHttpRequestHandler());
85      }
86  
87      public void tearDown() throws IOException {
88          client = null;
89  
90          server.destroy();
91      }
92  
93      /**
94       * HttpClient connects to the test server and performs two subsequent
95       * requests to the same URI in <u>lenient</u> mode.
96       * 
97       * Expected behavior:
98       * For both requests, status code 200 and a response body of "12345"
99       * should be returned.
100      *
101      * @throws IOException
102      */
103     public void test1Lenient() throws IOException {
104     	client.getParams().makeLenient();
105     	
106         GetMethod m =
107             new GetMethod("http://localhost:" + server.getLocalPort() + "/");
108 
109         client.executeMethod(m);
110         assertEquals(200, m.getStatusCode());
111         assertEquals("12345", m.getResponseBodyAsString());
112 
113         m = new GetMethod("http://localhost:" + server.getLocalPort() + "/");
114 
115         client.executeMethod(m);
116         assertEquals(200, m.getStatusCode());
117         assertEquals("12345", m.getResponseBodyAsString());
118         m.releaseConnection();
119     }
120 
121     /**
122      * HttpClient connects to the test server and performs two subsequent
123      * requests to the same URI in <u>strict</u> mode.
124      * <p>
125      * The first response body will be read with getResponseBodyAsString(),
126      * which returns null if an error occured.
127      * </p>
128      * <p>
129      * The second response body will be read using an InputStream, which
130      * throws an IOException if something went wrong.
131      * </p>
132      * Expected behavior:
133      * For both requests, status code 200 should be returned.<br />
134      * For request 1, a <code>null</code> response body should be returned.<br />
135      * For request 2, a {@link ProtocolException} is expected.
136      *
137      * @throws IOException
138      */
139     public void test1Strict() throws IOException {
140         client.getParams().makeStrict();
141 
142         GetMethod m =
143             new GetMethod("http://localhost:" + server.getLocalPort() + "/");
144 
145         client.executeMethod(m);
146         assertEquals(200, m.getStatusCode());
147         assertEquals("12345", m.getResponseBodyAsString());
148 
149         m = new GetMethod("http://localhost:" + server.getLocalPort() + "/");
150 
151         client.executeMethod(m);
152         assertEquals(200, m.getStatusCode());
153 
154         InputStream in = m.getResponseBodyAsStream();
155         while (in.read() != -1) {
156         }
157 
158         m.releaseConnection();
159     }
160 
161     public void enableThisTestForDebuggingOnly()
162         throws InterruptedException {
163         while (server.isRunning()) {
164             Thread.sleep(100);
165         }
166     }
167 
168     private class MyHttpRequestHandler implements HttpRequestHandler {
169         private int requestNo = 0;
170 
171         public boolean processRequest(
172             final SimpleHttpServerConnection conn,
173             final SimpleRequest request) throws IOException
174         {
175         	RequestLine requestLine = request.getRequestLine();
176         	ResponseWriter out = conn.getWriter();
177             if ("GET".equals(requestLine.getMethod())
178                 && "/".equals(requestLine.getUri())) {
179 
180                 requestNo++;
181 
182                 out.println("HTTP/1.1 200 OK");
183                 out.println("Content-Type: text/html");
184                 out.println("Content-Length: 5");
185                 out.println("Connection: keep-alive");
186                 out.println();
187                 out.println("12345"); // send exactly 5 bytes
188 
189                 // and some more garbage!
190                 out.println("AND SOME MORE\r\nGARBAGE!");
191                 out.println("HTTP/1.0 404 Not Found");
192                 out.println("Content-Type: text/plain");
193                 out.println("");
194                 out.println("THIS-IS-A-FAKE-RESPONSE!");
195 
196                 out.flush();
197                 // process max. 2 subsequents requests per connection
198                 if (requestNo < 2) {
199                     conn.setKeepAlive(true);
200                 }
201             }
202             return true;
203         }
204     }
205 
206 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestConnectionPersistence.html100644 0 0 61267 10661532627 31143 0ustar 0 0 TestConnectionPersistence xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestConnectionPersistence.java,v 1.2 2004/12/20 11:42:30 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   */
28  
29  package org.apache.commons.httpclient;
30  
31  import java.io.IOException;
32  
33  import org.apache.commons.httpclient.methods.GetMethod;
34  import org.apache.commons.httpclient.methods.PostMethod;
35  import org.apache.commons.httpclient.methods.StringRequestEntity;
36  import org.apache.commons.httpclient.server.HttpRequestHandler;
37  import org.apache.commons.httpclient.server.SimpleHttpServerConnection;
38  import org.apache.commons.httpclient.server.SimpleProxy;
39  import org.apache.commons.httpclient.server.SimpleRequest;
40  import org.apache.commons.httpclient.server.SimpleResponse;
41  
42  import junit.framework.Test;
43  import junit.framework.TestSuite;
44  
45  /**
46   * Connection persistence tests
47   * 
48   * @author Oleg Kalnichevski
49   *
50   * @version $Id: TestConnectionPersistence.java 480424 2006-11-29 05:56:49Z bayard $
51   */
52  public class TestConnectionPersistence extends HttpClientTestBase {
53      
54      // ------------------------------------------------------------ Constructor
55      public TestConnectionPersistence(final String testName) throws IOException {
56          super(testName);
57      }
58  
59      // ------------------------------------------------------------------- Main
60      public static void main(String args[]) {
61          String[] testCaseName = { TestConnectionPersistence.class.getName() };
62          junit.textui.TestRunner.main(testCaseName);
63      }
64  
65      // ------------------------------------------------------- TestCase Methods
66  
67      public static Test suite() {
68          return new TestSuite(TestConnectionPersistence.class);
69      }
70  
71      // ----------------------------------------------------------- Test Methods
72  
73      public void testConnPersisenceHTTP10() throws Exception {
74          this.server.setHttpService(new EchoService());
75  
76          AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager();
77          
78          this.client.getParams().setVersion(HttpVersion.HTTP_1_0);
79          this.client.setHttpConnectionManager(connman);
80          
81          PostMethod httppost = new PostMethod("/test/");
82          httppost.setRequestEntity(new StringRequestEntity("stuff", null, null));
83          try {
84              this.client.executeMethod(httppost);
85          } finally {
86              httppost.releaseConnection();
87          }
88          assertFalse(connman.getConection().isOpen());
89  
90          httppost = new PostMethod("/test/");
91          httppost.setRequestEntity(new StringRequestEntity("more stuff", null, null));
92          try {
93              this.client.executeMethod(httppost);
94          } finally {
95              httppost.releaseConnection();
96          }
97          assertFalse(connman.getConection().isOpen());
98      }
99  
100     public void testConnPersisenceHTTP11() throws Exception {
101         this.server.setHttpService(new EchoService());
102 
103         AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager();
104         
105         this.client.getParams().setVersion(HttpVersion.HTTP_1_1);
106         this.client.setHttpConnectionManager(connman);
107         
108         PostMethod httppost = new PostMethod("/test/");
109         httppost.setRequestEntity(new StringRequestEntity("stuff", null, null));
110         try {
111             this.client.executeMethod(httppost);
112         } finally {
113             httppost.releaseConnection();
114         }
115         assertTrue(connman.getConection().isOpen());
116 
117         httppost = new PostMethod("/test/");
118         httppost.setRequestEntity(new StringRequestEntity("more stuff", null, null));
119         try {
120             this.client.executeMethod(httppost);
121         } finally {
122             httppost.releaseConnection();
123         }
124         assertTrue(connman.getConection().isOpen());
125     }
126 
127     public void testConnClose() throws Exception {
128         this.server.setHttpService(new EchoService());
129 
130         AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager();
131         
132         this.client.getParams().setVersion(HttpVersion.HTTP_1_1);
133         this.client.setHttpConnectionManager(connman);
134         
135         PostMethod httppost = new PostMethod("/test/");
136         httppost.setRequestEntity(new StringRequestEntity("stuff", null, null));
137         try {
138             this.client.executeMethod(httppost);
139         } finally {
140             httppost.releaseConnection();
141         }
142         assertTrue(connman.getConection().isOpen());
143 
144         httppost = new PostMethod("/test/");
145         httppost.setRequestHeader("Connection", "close");
146         httppost.setRequestEntity(new StringRequestEntity("more stuff", null, null));
147         try {
148             this.client.executeMethod(httppost);
149         } finally {
150             httppost.releaseConnection();
151         }
152         assertFalse(connman.getConection().isOpen());
153     }
154 
155     public void testConnKeepAlive() throws Exception {
156         this.server.setHttpService(new EchoService());
157 
158         AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager();
159         
160         this.client.getParams().setVersion(HttpVersion.HTTP_1_0);
161         this.client.setHttpConnectionManager(connman);
162         
163         PostMethod httppost = new PostMethod("/test/");
164         httppost.setRequestEntity(new StringRequestEntity("stuff", null, null));
165         try {
166             this.client.executeMethod(httppost);
167         } finally {
168             httppost.releaseConnection();
169         }
170         assertFalse(connman.getConection().isOpen());
171 
172         httppost = new PostMethod("/test/");
173         httppost.setRequestHeader("Connection", "keep-alive");
174         httppost.setRequestEntity(new StringRequestEntity("more stuff", null, null));
175         try {
176             this.client.executeMethod(httppost);
177         } finally {
178             httppost.releaseConnection();
179         }
180         assertTrue(connman.getConection().isOpen());
181     }
182 
183     public void testRequestConnClose() throws Exception {
184         this.server.setRequestHandler(new HttpRequestHandler() {
185            
186             public boolean processRequest(
187                     final SimpleHttpServerConnection conn,
188                     final SimpleRequest request) throws IOException {
189 
190                 // Make sure the request if fully consumed
191                 request.getBodyBytes();
192                 
193                 SimpleResponse response = new SimpleResponse();
194                 response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK);
195                 response.setBodyString("stuff back");
196 
197                 conn.setKeepAlive(true);
198                 conn.writeResponse(response);
199                 
200                 return true;
201             }
202             
203         });
204 
205         AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager();
206         
207         this.client.getParams().setVersion(HttpVersion.HTTP_1_0);
208         this.client.setHttpConnectionManager(connman);
209         
210         PostMethod httppost = new PostMethod("/test/");
211         httppost.setRequestHeader("Connection", "close");
212         httppost.setRequestEntity(new StringRequestEntity("stuff", null, null));
213         try {
214             this.client.executeMethod(httppost);
215         } finally {
216             httppost.releaseConnection();
217         }
218         assertFalse(connman.getConection().isOpen());
219     }
220 
221     public void testProxyConnClose() throws Exception {
222         this.server.setHttpService(new EchoService());
223         this.proxy = new SimpleProxy();
224         this.client.getHostConfiguration().setProxy(
225             proxy.getLocalAddress(), 
226             proxy.getLocalPort());                
227 
228         AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager();
229         
230         this.client.setHttpConnectionManager(connman);
231         
232         GetMethod httpget = new GetMethod("/test/");
233         try {
234             this.client.executeMethod(httpget);
235         } finally {
236         	httpget.releaseConnection();
237         }
238         assertTrue(connman.getConection().isOpen());
239 
240         httpget = new GetMethod("/test/");
241         httpget.setRequestHeader("Proxy-Connection", "Close");
242         try {
243             this.client.executeMethod(httpget);
244         } finally {
245         	httpget.releaseConnection();
246         }
247         assertFalse(connman.getConection().isOpen());
248         assertEquals("Close", httpget.getRequestHeader("Proxy-Connection").getValue());
249     }
250 
251     
252 }
253 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestCredentials.html100644 0 0 30404 10661532627 27061 0ustar 0 0 TestCredentials xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestCredentials.java,v 1.1 2004/10/31 13:46:54 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import junit.framework.Test;
35  import junit.framework.TestCase;
36  import junit.framework.TestSuite;
37  
38  /**
39   * Unit tests for {@link Credentials}.
40   *
41   * @author Rodney Waldhoff
42   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
43   * @version $Id: TestCredentials.java 480424 2006-11-29 05:56:49Z bayard $
44   */
45  public class TestCredentials extends TestCase {
46  
47      // ------------------------------------------------------------ Constructor
48      public TestCredentials(String testName) {
49          super(testName);
50      }
51  
52      // ------------------------------------------------------------------- Main
53      public static void main(String args[]) {
54          String[] testCaseName = { TestCredentials.class.getName() };
55          junit.textui.TestRunner.main(testCaseName);
56      }
57  
58      // ------------------------------------------------------- TestCase Methods
59  
60      public static Test suite() {
61          return new TestSuite(TestCredentials.class);
62      }
63  
64      public void testCredentialConstructors() {
65          try {
66              new UsernamePasswordCredentials(null, null);
67              fail("IllegalArgumentException should have been thrown");
68          } catch (IllegalArgumentException e) {
69              // expected
70          }
71          try {
72              new NTCredentials("user", "password", null, null);
73              fail("IllegalArgumentException should have been thrown");
74          } catch (IllegalArgumentException e) {
75              // expected
76          }
77          try {
78              new NTCredentials("user", "password", "host", null);
79              fail("IllegalArgumentException should have been thrown");
80          } catch (IllegalArgumentException e) {
81              // expected
82          }
83          NTCredentials creds = new NTCredentials("user", null, "host", "domain");
84          assertNotNull(creds.getUserName());
85          assertNull(creds.getPassword());
86          assertNotNull(creds.getDomain());
87          assertNotNull(creds.getHost());
88      }
89  
90      /**
91       * Verifies that credentials report equal when they should.
92       */
93      public void testCredentialEquals() {
94  
95          Credentials creds1 = new UsernamePasswordCredentials("user1", "password1");
96          Credentials creds1Again = new UsernamePasswordCredentials("user1", "password1");
97          Credentials creds2 = new UsernamePasswordCredentials("user2", "password2");
98          Credentials creds3 = new UsernamePasswordCredentials("user3", null);
99          Credentials creds3Again = new UsernamePasswordCredentials("user3", null);
100 
101         assertEquals(creds1, creds1Again);
102         assertNotSame(creds1, creds2);
103         assertEquals(creds3, creds3Again);
104 
105         Credentials ntCreds1 = new NTCredentials("user1", "password1", "host1", "domain1");
106         Credentials ntCreds1Again = new NTCredentials("user1", "password1", "host1", "domain1");
107         Credentials ntCreds2 = new NTCredentials("user1", "password2", "host1", "domain1");
108         Credentials ntCreds3 = new NTCredentials("user1", "password1", "host2", "domain1");
109         Credentials ntCreds4 = new NTCredentials("user1", "password1", "host1", "domain2");
110 
111         assertEquals(ntCreds1, ntCreds1Again);
112         assertNotSame(ntCreds1, creds1);
113         assertNotSame(creds1, ntCreds1);
114         assertNotSame(ntCreds1, ntCreds2);
115         assertNotSame(ntCreds1, ntCreds3);
116         assertNotSame(ntCreds1, ntCreds4);
117     }
118 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestEffectiveHttpVersion.html100644 0 0 33034 10661532627 30734 0ustar 0 0 TestEffectiveHttpVersion xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestEffectiveHttpVersion.java,v 1.4 2004/10/31 14:42:59 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  import java.io.IOException;
34  
35  import junit.framework.Test;
36  import junit.framework.TestSuite;
37  
38  import org.apache.commons.httpclient.methods.GetMethod;
39  import org.apache.commons.httpclient.params.HttpMethodParams;
40  
41  /**
42   * HTTP protocol versioning tests.
43   *
44   * @author Oleg Kalnichevski
45   * 
46   * @version $Revision: 480424 $
47   */
48  public class TestEffectiveHttpVersion extends HttpClientTestBase {
49  
50      // ------------------------------------------------------------ Constructor
51      public TestEffectiveHttpVersion(final String testName) throws IOException {
52          super(testName);
53      }
54  
55      // ------------------------------------------------------------------- Main
56      public static void main(String args[]) {
57          String[] testCaseName = { TestEffectiveHttpVersion.class.getName() };
58          junit.textui.TestRunner.main(testCaseName);
59      }
60  
61      // ------------------------------------------------------- TestCase Methods
62  
63      public static Test suite() {
64          return new TestSuite(TestEffectiveHttpVersion.class);
65      }
66  
67      public void testClientLevelHttpVersion() throws IOException {
68          this.server.setHttpService(new EchoService());
69  
70          HttpVersion testver = new HttpVersion(1, 10);
71  
72          this.client.getParams().setVersion(testver);
73          GetMethod httpget = new GetMethod("/test/");
74          try {
75              this.client.executeMethod(httpget);
76          } finally {
77              httpget.releaseConnection();
78          }
79          assertEquals(testver, httpget.getEffectiveVersion());
80      }
81  
82      public void testMethodLevelHttpVersion() throws IOException {
83          this.server.setHttpService(new EchoService());
84  
85          HttpVersion globalver = new HttpVersion(1, 10);
86          HttpVersion testver1 = new HttpVersion(1, 11);
87          HttpVersion testver2 = new HttpVersion(1, 12);
88  
89          this.client.getParams().setVersion(globalver);
90          
91          GetMethod httpget1 = new GetMethod("/test/");
92          httpget1.getParams().setVersion(testver1);
93          try {
94              this.client.executeMethod(httpget1);
95          } finally {
96              httpget1.releaseConnection();
97          }
98          assertEquals(testver1, httpget1.getEffectiveVersion());
99  
100         GetMethod httpget2 = new GetMethod("/test/");
101         httpget2.getParams().setVersion(testver2);
102         try {
103             this.client.executeMethod(httpget2);
104         } finally {
105             httpget2.releaseConnection();
106         }
107         assertEquals(testver2, httpget2.getEffectiveVersion());
108 
109         GetMethod httpget3 = new GetMethod("/test/");
110         try {
111             this.client.executeMethod(httpget3);
112         } finally {
113             httpget3.releaseConnection();
114         }
115         assertEquals(globalver, httpget3.getEffectiveVersion());
116     }
117 
118     public void testHostLevelHttpVersion() throws IOException {
119         this.server.setHttpService(new EchoService());
120 
121         HttpVersion testver = new HttpVersion(1, 11);
122         HttpVersion hostver = new HttpVersion(1, 12);
123 
124         this.client.getParams().setVersion(testver);
125         
126         GetMethod httpget1 = new GetMethod("/test/");
127         httpget1.getParams().setVersion(testver);
128         
129         HostConfiguration hostconf = new HostConfiguration();
130         hostconf.setHost(this.server.getLocalAddress(), this.server.getLocalPort(), "http"); 
131         try {
132             this.client.executeMethod(hostconf, httpget1);
133         } finally {
134             httpget1.releaseConnection();
135         }
136         assertEquals(testver, httpget1.getEffectiveVersion());
137 
138         GetMethod httpget2 = new GetMethod("/test/");
139         hostconf.setHost(this.server.getLocalAddress(), this.server.getLocalPort(), "http");
140         hostconf.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, hostver); 
141         try {
142             this.client.executeMethod(hostconf, httpget2);
143         } finally {
144             httpget2.releaseConnection();
145         }
146         assertEquals(hostver, httpget2.getEffectiveVersion());
147     }
148 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestEntityEnclosingMethod.html100644 0 0 105172 10661532627 31130 0ustar 0 0 TestEntityEnclosingMethod xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestEntityEnclosingMethod.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.ByteArrayInputStream;
34  import java.io.IOException;
35  import java.io.InputStream;
36  
37  import junit.framework.Test;
38  import junit.framework.TestSuite;
39  
40  import org.apache.commons.httpclient.auth.AuthScope;
41  import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
42  import org.apache.commons.httpclient.methods.PostMethod;
43  import org.apache.commons.httpclient.methods.RequestEntity;
44  import org.apache.commons.httpclient.methods.StringRequestEntity;
45  import org.apache.commons.httpclient.server.AuthRequestHandler;
46  import org.apache.commons.httpclient.server.HttpRequestHandlerChain;
47  import org.apache.commons.httpclient.server.HttpService;
48  import org.apache.commons.httpclient.server.HttpServiceHandler;
49  import org.apache.commons.httpclient.server.SimpleRequest;
50  import org.apache.commons.httpclient.server.SimpleResponse;
51  
52  /**
53   * Tests specific to entity enclosing methods.
54   *
55   * @author Oleg Kalnichevski
56   * @version $Id: TestEntityEnclosingMethod.java 480424 2006-11-29 05:56:49Z bayard $
57   */
58  public class TestEntityEnclosingMethod extends HttpClientTestBase {
59  
60      public TestEntityEnclosingMethod(String testName) throws IOException {
61          super(testName);
62      }
63  
64      public static Test suite() {
65          TestSuite suite = new TestSuite(TestEntityEnclosingMethod.class);
66          return suite;
67      }
68  
69      public static void main(String args[]) {
70          String[] testCaseName = { TestEntityEnclosingMethod.class.getName() };
71          junit.textui.TestRunner.main(testCaseName);
72      }
73  
74      // ------------------------------------------------------------------ Tests
75      
76      public void testEnclosedEntityAutoLength() throws Exception {
77          String inputstr = "This is a test message";
78          byte[] input = inputstr.getBytes("US-ASCII");
79          InputStream instream = new ByteArrayInputStream(input);
80          
81          RequestEntity requestentity = new InputStreamRequestEntity(
82                  instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); 
83          PostMethod method = new PostMethod("/");
84          method.setRequestEntity(requestentity);
85          this.server.setHttpService(new EchoService());
86          try {
87              this.client.executeMethod(method);
88              assertEquals(200, method.getStatusCode());
89              String body = method.getResponseBodyAsString();
90              assertEquals(inputstr, body);
91              assertNull(method.getRequestHeader("Transfer-Encoding"));
92              assertNotNull(method.getRequestHeader("Content-Length"));
93              assertEquals(input.length, Integer.parseInt(
94                      method.getRequestHeader("Content-Length").getValue()));
95          } finally {
96              method.releaseConnection();
97          }
98      }
99  
100     public void testEnclosedEntityExplicitLength() throws Exception {
101         String inputstr = "This is a test message";
102         byte[] input = inputstr.getBytes("US-ASCII");
103         InputStream instream = new ByteArrayInputStream(input);
104         
105         RequestEntity requestentity = new InputStreamRequestEntity(
106                 instream, 14); 
107         PostMethod method = new PostMethod("/");
108         method.setRequestEntity(requestentity);
109         this.server.setHttpService(new EchoService());
110         try {
111             this.client.executeMethod(method);
112             assertEquals(200, method.getStatusCode());
113             String body = method.getResponseBodyAsString();
114             assertEquals("This is a test", body);
115             assertNull(method.getRequestHeader("Transfer-Encoding"));
116             assertNotNull(method.getRequestHeader("Content-Length"));
117             assertEquals(14, Integer.parseInt(
118                     method.getRequestHeader("Content-Length").getValue()));
119         } finally {
120             method.releaseConnection();
121         }
122     }
123 
124     public void testEnclosedEntityChunked() throws Exception {
125         String inputstr = "This is a test message";
126         byte[] input = inputstr.getBytes("US-ASCII");
127         InputStream instream = new ByteArrayInputStream(input);
128         
129         RequestEntity requestentity = new InputStreamRequestEntity(
130                 instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); 
131         PostMethod method = new PostMethod("/");
132         method.setRequestEntity(requestentity);
133         method.setContentChunked(true);
134         this.server.setHttpService(new EchoService());
135         try {
136             this.client.executeMethod(method);
137             assertEquals(200, method.getStatusCode());
138             String body = method.getResponseBodyAsString();
139             assertEquals(inputstr, body);
140             assertNotNull(method.getRequestHeader("Transfer-Encoding"));
141             assertNull(method.getRequestHeader("Content-Length"));
142         } finally {
143             method.releaseConnection();
144         }
145     }
146     
147     public void testEnclosedEntityChunkedHTTP1_0() throws Exception {
148         String inputstr = "This is a test message";
149         byte[] input = inputstr.getBytes("US-ASCII");
150         InputStream instream = new ByteArrayInputStream(input);
151         
152         RequestEntity requestentity = new InputStreamRequestEntity(
153                 instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); 
154         PostMethod method = new PostMethod("/");
155         method.setRequestEntity(requestentity);
156         method.setContentChunked(true);
157         method.getParams().setVersion(HttpVersion.HTTP_1_0);
158         this.server.setHttpService(new EchoService());
159         try {
160             this.client.executeMethod(method);
161             fail("ProtocolException should have been thrown");
162         } catch (ProtocolException ex) {
163             // expected
164         } finally {
165             method.releaseConnection();
166         }
167     }
168 
169     public void testEnclosedEntityRepeatable() throws Exception {
170         String inputstr = "This is a test message";
171         byte[] input = inputstr.getBytes("US-ASCII");
172         InputStream instream = new ByteArrayInputStream(input);
173         
174         RequestEntity requestentity = new InputStreamRequestEntity(
175                 instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); 
176         PostMethod method = new PostMethod("/");
177         method.setRequestEntity(requestentity);
178 
179         UsernamePasswordCredentials creds = 
180             new UsernamePasswordCredentials("testuser", "testpass");
181         
182         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
183         handlerchain.appendHandler(new AuthRequestHandler(creds));
184         handlerchain.appendHandler(new HttpServiceHandler(new EchoService()));
185         this.server.setRequestHandler(handlerchain);
186         this.client.getState().setCredentials(AuthScope.ANY, creds);
187         try {
188             this.client.executeMethod(method);
189             assertEquals(200, method.getStatusCode());
190             String body = method.getResponseBodyAsString();
191             assertEquals(inputstr, body);
192             assertNull(method.getRequestHeader("Transfer-Encoding"));
193             assertNotNull(method.getRequestHeader("Content-Length"));
194             assertEquals(input.length, Integer.parseInt(
195                     method.getRequestHeader("Content-Length").getValue()));
196         } finally {
197             method.releaseConnection();
198         }
199     }
200 
201     public void testEnclosedEntityNonRepeatable() throws Exception {
202         String inputstr = "This is a test message";
203         byte[] input = inputstr.getBytes("US-ASCII");
204         InputStream instream = new ByteArrayInputStream(input);
205         
206         RequestEntity requestentity = new InputStreamRequestEntity(
207                 instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); 
208         PostMethod method = new PostMethod("/");
209         method.setRequestEntity(requestentity);
210         method.setContentChunked(true);
211 
212         UsernamePasswordCredentials creds = 
213             new UsernamePasswordCredentials("testuser", "testpass");
214         
215         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
216         handlerchain.appendHandler(new AuthRequestHandler(creds));
217         handlerchain.appendHandler(new HttpServiceHandler(new EchoService()));
218         this.server.setRequestHandler(handlerchain);
219         this.client.getState().setCredentials(AuthScope.ANY, creds);
220         try {
221             this.client.executeMethod(method);
222             fail("ProtocolException should have been thrown");
223         } catch (ProtocolException ex) {
224             // expected
225         } finally {
226             method.releaseConnection();
227         }
228     }
229     
230     public void testEnclosedEntityNegativeLength() throws Exception {
231         
232         String inputstr = "This is a test message";
233         byte[] input = inputstr.getBytes("US-ASCII");
234         InputStream instream = new ByteArrayInputStream(input);
235         
236         RequestEntity requestentity = new InputStreamRequestEntity(
237                 instream, -14); 
238         PostMethod method = new PostMethod("/");
239         method.setRequestEntity(requestentity);
240         method.setContentChunked(false);
241         this.server.setHttpService(new EchoService());
242         try {
243             this.client.executeMethod(method);
244             assertEquals(200, method.getStatusCode());
245             String body = method.getResponseBodyAsString();
246             assertEquals(inputstr, body);
247             assertNotNull(method.getRequestHeader("Transfer-Encoding"));
248             assertNull(method.getRequestHeader("Content-Length"));
249         } finally {
250             method.releaseConnection();
251         }
252     }
253 
254     public void testEnclosedEntityNegativeLengthHTTP1_0() throws Exception {
255         
256         String inputstr = "This is a test message";
257         byte[] input = inputstr.getBytes("US-ASCII");
258         InputStream instream = new ByteArrayInputStream(input);
259         
260         RequestEntity requestentity = new InputStreamRequestEntity(
261                 instream, -14); 
262         PostMethod method = new PostMethod("/");
263         method.setRequestEntity(requestentity);
264         method.setContentChunked(false);
265         method.getParams().setVersion(HttpVersion.HTTP_1_0);
266         this.server.setHttpService(new EchoService());
267         try {
268             this.client.executeMethod(method);
269             fail("ProtocolException should have been thrown");
270         } catch (ProtocolException ex) {
271             // expected
272         } finally {
273             method.releaseConnection();
274         }
275     }
276     
277     class RequestBodyStatsService implements HttpService {
278 
279         public RequestBodyStatsService() {
280             super();
281         }
282 
283         public boolean process(final SimpleRequest request, final SimpleResponse response)
284             throws IOException
285         {
286             HttpVersion httpversion = request.getRequestLine().getHttpVersion();
287             response.setStatusLine(httpversion, HttpStatus.SC_OK);
288             response.addHeader(new Header("Content-Type", "text/plain"));            
289 
290             StringBuffer buffer = new StringBuffer();
291             buffer.append("Request bosy stats:\r\n");
292             buffer.append("===================\r\n");
293             long l = request.getContentLength();
294             if (l >= 0) {
295                 buffer.append("Content-Length: ");
296                 buffer.append(l);
297                 buffer.append("\r\n");
298             }
299             Header te = request.getFirstHeader("Transfer-Encoding");
300             if (te != null) {
301                 buffer.append("Content-Length: ");
302                 buffer.append(te.getValue());
303                 buffer.append("\r\n");
304             }
305             byte[] b = request.getBodyBytes();
306             if (b.length <= 0) {
307                 buffer.append("No body submitted\r\n");
308             }
309             response.setBodyString(buffer.toString());
310             return true;
311         }
312     }
313 	
314     public void testEmptyPostMethod() throws Exception {
315         this.server.setHttpService(new RequestBodyStatsService());
316 
317         PostMethod method = new PostMethod("/");
318         method.setRequestHeader("Content-Type", "text/plain");
319         this.client.executeMethod(method);
320         assertEquals(200,method.getStatusLine().getStatusCode());
321         String response = method.getResponseBodyAsString();
322         assertNotNull(method.getRequestHeader("Content-Length"));
323         assertTrue(response.indexOf("No body submitted") >= 0);
324 
325         method = new PostMethod("/");
326         method.setRequestHeader("Content-Type", "text/plain");
327         method.setRequestEntity(new StringRequestEntity("", null, null));
328 		this.client.executeMethod(method);
329         assertEquals(200,method.getStatusLine().getStatusCode());
330         assertNotNull(method.getRequestHeader("Content-Length"));
331         response = method.getResponseBodyAsString();
332         assertTrue(response.indexOf("No body submitted") >= 0);
333 
334         method = new PostMethod("/");
335         method.setRequestHeader("Content-Type", "text/plain");
336         method.setContentChunked(true);
337 		this.client.executeMethod(method);
338         assertEquals(200,method.getStatusLine().getStatusCode());
339         assertNotNull(method.getRequestHeader("Content-Length"));
340         response = method.getResponseBodyAsString();
341         assertTrue(response.indexOf("No body submitted") >= 0);
342 
343         method = new PostMethod("/");
344         method.setRequestHeader("Content-Type", "text/plain");
345         method.setRequestEntity(new StringRequestEntity("", null, null));
346         method.setContentChunked(true);
347 		this.client.executeMethod(method);
348         assertNull(method.getRequestHeader("Content-Length"));
349         assertNotNull(method.getRequestHeader("Transfer-Encoding"));
350         assertEquals(200,method.getStatusLine().getStatusCode());
351         response = method.getResponseBodyAsString();
352         assertTrue(response.indexOf("No body submitted") >= 0);
353     }
354     
355 }
356 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestEquals.html100644 0 0 24467 10661532627 26072 0ustar 0 0 TestEquals xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestEquals.java,v 1.2 2004/02/22 18:08:49 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32   package org.apache.commons.httpclient;
33  
34  import org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory;
35  import org.apache.commons.httpclient.protocol.Protocol;
36  import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
37  import org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory;
38  
39  import junit.framework.Test;
40  import junit.framework.TestCase;
41  import junit.framework.TestSuite;
42  
43  /**
44   */
45  public class TestEquals extends TestCase {
46      
47      public static Test suite() {
48          return new TestSuite(TestEquals.class);
49      }
50      
51      /**
52       * 
53       */
54      public TestEquals() {
55          super();
56      }
57  
58      /**
59       * @param arg0
60       */
61      public TestEquals(String arg0) {
62          super(arg0);
63      }
64  
65      public void testProtocol() {
66          
67          Protocol p1 = new Protocol("test", new DefaultProtocolSocketFactory(), 123);
68          Protocol p2 = new Protocol("test", new DefaultProtocolSocketFactory(), 123);
69          
70          assertTrue(p1.equals(p2));
71          assertTrue(p2.equals(p1));
72      }
73      
74      public void testProtocolSocketFactory() {
75          
76          ProtocolSocketFactory p1 = new DefaultProtocolSocketFactory();
77          ProtocolSocketFactory p2 = new DefaultProtocolSocketFactory();
78  
79          assertTrue(p1.equals(p2));
80          assertTrue(p2.equals(p1));
81  
82          p1 = new SSLProtocolSocketFactory();
83          p2 = new SSLProtocolSocketFactory();
84  
85          assertTrue(p1.equals(p2));
86          assertTrue(p2.equals(p1));
87          
88      }
89      
90      public void testProtocolSocketFactorySublass() {
91          ProtocolSocketFactory factory1 = new DefaultProtocolSocketFactory();
92          ProtocolSocketFactory factory2 = new DefaultProtocolSocketFactory() {};
93  
94          Protocol protocolA = new Protocol("http", factory1, 80);
95          Protocol protocolB = new Protocol("http", factory2, 80);
96          Protocol protocolC = new Protocol("http", factory2, 80);
97  
98          assertTrue(protocolB.equals(protocolC));
99          assertFalse(protocolA.equals(protocolB));
100         assertFalse(protocolB.equals(protocolA));
101         assertFalse(protocolA.equals(protocolB) != protocolB.equals(protocolA));
102         assertTrue(protocolB.equals(protocolB));
103     }
104     
105     public void testHostConfiguration() {
106         
107         HostConfiguration hc1 = new HostConfiguration();
108         hc1.setHost("http", 80, "http");
109 
110         HostConfiguration hc2 = new HostConfiguration();
111         hc2.setHost("http", 80, "http");
112 
113         assertTrue(hc1.equals(hc2));
114         assertTrue(hc2.equals(hc1));
115     }
116     
117 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestExceptions.html100644 0 0 30341 10661532627 26745 0ustar 0 0 TestExceptions xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestExceptions.java,v 1.4 2004/03/25 20:37:20 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient;
31  
32  import java.io.ByteArrayOutputStream;
33  import java.io.IOException;
34  import java.io.PrintStream;
35  import java.io.PrintWriter;
36  import java.io.StringWriter;
37  
38  import junit.framework.Test;
39  import junit.framework.TestCase;
40  import junit.framework.TestSuite;
41  
42  /**
43   * 
44   * @author <a href="mailto:laura@lwerner.org">Laura Werner</a>
45   */
46  public class TestExceptions extends TestCase
47  {
48  
49      // ------------------------------------------------------------ Constructor
50      public TestExceptions(String testName) {
51          super(testName);
52      }
53  
54      // ------------------------------------------------------------------- Main
55      public static void main(String args[]) {
56          String[] testCaseName = { TestExceptions.class.getName() };
57          junit.textui.TestRunner.main(testCaseName);
58      }
59  
60      // ------------------------------------------------------- TestCase Methods
61  
62      public static Test suite() {
63          return new TestSuite(TestExceptions.class);
64      }
65  
66      /** Make sure that you can retrieve the "cause" from an HttpException */
67      public void testGetCause() {
68          
69          Exception aCause = new IOException("the cause");
70          
71          try {
72              throw new HttpException("http exception", aCause);
73          }
74          catch (HttpException e) {
75              assertEquals("Retrieve cause from caught exception", e.getCause(), aCause);
76          }
77      }
78      
79      /** Make sure HttpConnection prints its stack trace to a PrintWriter properly */
80      public void testStackTraceWriter() {
81          
82          Exception aCause = new IOException("initial exception");
83          try {
84              throw new HttpException("http exception", aCause);
85          }
86          catch (HttpException e) {
87              // Get the stack trace printed into a string
88              StringWriter stringWriter = new StringWriter();
89              PrintWriter  writer = new PrintWriter(stringWriter);
90              e.printStackTrace(writer);
91              writer.flush();
92              String stackTrace = stringWriter.toString();
93              
94              // Do some validation on what got printed
95              validateStackTrace(e, stackTrace);
96          }
97      }
98      
99      /** Make sure HttpConnection prints its stack trace to a PrintStream properly */
100     public void testStackTraceStream() {
101         
102         Exception aCause = new IOException("initial exception");
103         try {
104             throw new HttpException("http exception", aCause);
105         }
106         catch (HttpException e) {
107             // Get the stack trace printed into a string
108             ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
109             PrintStream  stream = new PrintStream(byteStream);
110             e.printStackTrace(stream);
111             stream.flush();
112             String stackTrace = byteStream.toString();  // Assume default charset
113             
114             // Do some validation on what got printed
115             validateStackTrace(e, stackTrace);
116         }
117     }
118     
119     /**
120      * Make sure an HttpException stack trace has the right info in it.
121      * This doesn't bother parsing the whole thing, just does some sanity checks.
122      */
123     private void validateStackTrace(HttpException exception, String stackTrace) {
124         assertTrue("Starts with exception string", stackTrace.startsWith(exception.toString()));
125         
126         Throwable cause = exception.getCause();
127         if (cause != null) {
128             assertTrue("Contains 'cause'", stackTrace.toLowerCase().indexOf("cause") != -1);
129             assertTrue("Contains cause.toString()", stackTrace.indexOf(cause.toString()) != -1);
130         }
131     }
132 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHeader.html100644 0 0 22504 10661532627 26016 0ustar 0 0 TestHeader xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHeader.java,v 1.6 2004/02/22 18:08:49 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import junit.framework.*;
35  
36  /**
37   * Simple tests for {@link NameValuePair}.
38   *
39   * @author Rodney Waldhoff
40   * @version $Id: TestHeader.java 480424 2006-11-29 05:56:49Z bayard $
41   */
42  public class TestHeader extends TestNVP {
43  
44      // ------------------------------------------------------------ Constructor
45      public TestHeader(String testName) {
46          super(testName);
47      }
48  
49      // ------------------------------------------------------------------- Main
50      public static void main(String args[]) {
51          String[] testCaseName = { TestHeader.class.getName() };
52          junit.textui.TestRunner.main(testCaseName);
53      }
54  
55      // ------------------------------------------------------- TestCase Methods
56  
57      public static Test suite() {
58          return new TestSuite(TestHeader.class);
59      }
60  
61      // ------------------------------------------------------ Protected Methods
62  
63      protected NameValuePair makePair() {
64          return new Header();
65      }
66  
67      protected NameValuePair makePair(String name, String value) {
68          return new Header(name,value);
69      }
70  
71  
72      // ----------------------------------------------------------- Test Methods
73  
74      public void testToExternalFormNull() {
75          Header header = (Header)makePair();
76          assertEquals(": \r\n",header.toExternalForm());
77      }
78  
79      public void testToExternalFormNullName() {
80          Header header = (Header)makePair(null,"value");
81          assertEquals(": value\r\n",header.toExternalForm());
82      }
83  
84      public void testToExternalFormNullValue() {
85          Header header = (Header)makePair("name",null);
86          assertEquals("name: \r\n",header.toExternalForm());
87      }
88  
89      public void testToExternalForm() {
90          Header header = (Header)makePair("a","b");
91          assertEquals("a: b\r\n",header.toExternalForm());
92      }
93  
94      public void testEqualToNVP() {
95          NameValuePair header = makePair("a","b");
96          NameValuePair pair = new NameValuePair("a","b");
97          assertTrue(header.equals(pair));
98          assertTrue(pair.equals(header));
99      }
100 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHeaderElement.html100644 0 0 31713 10661532627 27332 0ustar 0 0 TestHeaderElement xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHeaderElement.java,v 1.7 2004/02/22 18:08:49 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import junit.framework.*;
35  
36  /**
37   * Simple tests for {@link HeaderElement}.
38   *
39   * @author Rodney Waldhoff
40   * @author <a href="mailto:bcholmes@interlog.com">B.C. Holmes</a>
41   * @author <a href="mailto:jericho@thinkfree.com">Park, Sung-Gu</a>
42   * @author <a href="mailto:oleg@ural.ru">oleg Kalnichevski</a>
43   * @version $Id: TestHeaderElement.java 480424 2006-11-29 05:56:49Z bayard $
44   */
45  public class TestHeaderElement extends TestNVP {
46  
47      // ------------------------------------------------------------ Constructor
48      public TestHeaderElement(String testName) {
49          super(testName);
50      }
51  
52      // ------------------------------------------------------------------- Main
53      public static void main(String args[]) {
54          String[] testCaseName = { TestHeaderElement.class.getName() };
55          junit.textui.TestRunner.main(testCaseName);
56      }
57  
58      // ------------------------------------------------------- TestCase Methods
59  
60      public static Test suite() {
61          return new TestSuite(TestHeaderElement.class);
62      }
63  
64      // ------------------------------------------------------ Protected Methods
65  
66      protected NameValuePair makePair() {
67          return new HeaderElement();
68      }
69  
70      protected NameValuePair makePair(String name, String value) {
71          return new HeaderElement(name,value);
72      }
73  
74  
75      // ----------------------------------------------------------- Test Methods
76  
77      public void testOldMain() throws Exception {
78          // this is derived from the old main method in HeaderElement
79          String headerValue = "name1 = value1; name2; name3=\"value3\" , name4=value4; " +
80              "name5=value5, name6= ; name7 = value7; name8 = \" value8\"";
81          HeaderElement[] elements = HeaderElement.parseElements(headerValue);
82          // there are 3 elements
83          assertEquals(3,elements.length);
84          // 1st element
85          assertEquals("name1",elements[0].getName());
86          assertEquals("value1",elements[0].getValue());
87          // 1st element has 2 getParameters()
88          assertEquals(2,elements[0].getParameters().length);
89          assertEquals("name2",elements[0].getParameters()[0].getName());
90          assertEquals(null, elements[0].getParameters()[0].getValue());
91          assertEquals("name3",elements[0].getParameters()[1].getName());
92          assertEquals("value3",elements[0].getParameters()[1].getValue());
93          // 2nd element
94          assertEquals("name4",elements[1].getName());
95          assertEquals("value4",elements[1].getValue());
96          // 2nd element has 1 parameter
97          assertEquals(1,elements[1].getParameters().length);
98          assertEquals("name5",elements[1].getParameters()[0].getName());
99          assertEquals("value5",elements[1].getParameters()[0].getValue());
100         // 3rd element
101         assertEquals("name6",elements[2].getName());
102         assertEquals("",elements[2].getValue());
103         // 3rd element has 2 getParameters()
104         assertEquals(2,elements[2].getParameters().length);
105         assertEquals("name7",elements[2].getParameters()[0].getName());
106         assertEquals("value7",elements[2].getParameters()[0].getValue());
107         assertEquals("name8",elements[2].getParameters()[1].getName());
108         assertEquals(" value8",elements[2].getParameters()[1].getValue());
109     }
110 
111     public void testFringeCase1() throws Exception {
112         String headerValue = "name1 = value1,";
113         HeaderElement[] elements = HeaderElement.parseElements(headerValue);
114         assertEquals("Number of elements", 1, elements.length);
115     }
116 
117 
118     public void testFringeCase2() throws Exception {
119         String headerValue = "name1 = value1, ";
120         HeaderElement[] elements = HeaderElement.parseElements(headerValue);
121         assertEquals("Number of elements", 1, elements.length);
122     }
123 
124 
125     public void testFringeCase3() throws Exception {
126         String headerValue = ",, ,, ,";
127         HeaderElement[] elements = HeaderElement.parseElements(headerValue);
128         assertEquals("Number of elements", 0, elements.length);
129     }
130 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHeaderOps.html100644 0 0 51151 10661532627 26500 0ustar 0 0 TestHeaderOps xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestHeaderOps.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient;
31  
32  import java.io.IOException;
33  import java.net.InetAddress;
34  import java.util.Iterator;
35  
36  import junit.framework.Test;
37  import junit.framework.TestSuite;
38  
39  import org.apache.commons.httpclient.methods.GetMethod;
40  import org.apache.commons.httpclient.protocol.Protocol;
41  import org.apache.commons.httpclient.server.HttpService;
42  import org.apache.commons.httpclient.server.SimpleRequest;
43  import org.apache.commons.httpclient.server.SimpleResponse;
44  
45  /**
46   * @author Rodney Waldhoff
47   * @version $Id: TestHeaderOps.java 480424 2006-11-29 05:56:49Z bayard $
48   */
49  public class TestHeaderOps extends HttpClientTestBase {
50  
51      public TestHeaderOps(String testName) throws Exception {
52          super(testName);
53      }
54  
55      public static Test suite() {
56          TestSuite suite = new TestSuite(TestHeaderOps.class);
57          return suite;
58      }
59  
60      public static void main(String args[]) {
61          String[] testCaseName = { TestHeaderOps.class.getName() };
62          junit.textui.TestRunner.main(testCaseName);
63      }
64  
65      // ------------------------------------------------------------------ Tests
66  
67      class HeaderDumpService implements HttpService {
68  
69          public HeaderDumpService() {
70              super();
71          }
72  
73          public boolean process(final SimpleRequest request, final SimpleResponse response)
74              throws IOException
75          {
76              HttpVersion httpversion = request.getRequestLine().getHttpVersion();
77              response.setStatusLine(httpversion, HttpStatus.SC_OK);
78              response.addHeader(new Header("Content-Type", "text/plain"));            
79              response.addHeader(new Header("HeaderSetByServlet", "Yes"));            
80  
81              StringBuffer buffer = new StringBuffer(); 
82              buffer.append("Request headers: \r\n");
83              for (Iterator i = request.getHeaderIterator(); i.hasNext(); ) {
84                  Header header = (Header) i.next();
85                  buffer.append("name=\"");
86                  buffer.append(header.getName().toLowerCase());
87                  buffer.append("\";value=\"");
88                  buffer.append(header.getValue());
89                  buffer.append("\"\r\n");
90              }
91              response.setBodyString(buffer.toString());
92              return true;
93          }
94      }
95  
96      /**
97       * Test {@link HttpMethod#addRequestHeader}.
98       */
99      public void testAddRequestHeader() throws Exception {
100         this.server.setHttpService(new HeaderDumpService());
101         
102         GetMethod method = new GetMethod("/");
103         method.setRequestHeader(new Header("addRequestHeader(Header)","True"));
104         method.setRequestHeader("addRequestHeader(String,String)","Also True");
105         try {
106             this.client.executeMethod(method);
107             String s = method.getResponseBodyAsString();
108             assertTrue(s.indexOf("name=\"addrequestheader(header)\";value=\"True\"") >= 0);
109             assertTrue(s.indexOf("name=\"addrequestheader(string,string)\";value=\"Also True\"") >= 0);
110         } finally {
111             method.releaseConnection();
112         }
113     }
114 
115     /**
116      * Test {@link HttpMethod#removeRequestHeader}.
117      */
118     public void testRemoveRequestHeader() throws Exception {
119         this.server.setHttpService(new HeaderDumpService());
120         
121         GetMethod method = new GetMethod("/");
122         method.setRequestHeader(new Header("XXX-A-HEADER","true"));
123         method.removeRequestHeader("XXX-A-HEADER");
124         
125         try {
126             this.client.executeMethod(method);
127             String s = method.getResponseBodyAsString();
128             assertTrue(!(s.indexOf("xxx-a-header") >= 0));
129         } finally {
130             method.releaseConnection();
131         }
132     }
133 
134     /**
135      * Test {@link HttpMethod#setRequestHeader}.
136      */
137     public void testOverwriteRequestHeader() throws Exception {
138         this.server.setHttpService(new HeaderDumpService());
139         
140         GetMethod method = new GetMethod("/");
141         method.setRequestHeader(new Header("xxx-a-header","one"));
142         method.setRequestHeader("XXX-A-HEADER","two");
143         
144         try {
145             this.client.executeMethod(method);
146             String s = method.getResponseBodyAsString();
147             assertTrue(s.indexOf("name=\"xxx-a-header\";value=\"two\"") >= 0);
148         } finally {
149             method.releaseConnection();
150         }
151     }
152 
153     /**
154      * Test {@link HttpMethod#getResponseHeader}.
155      */
156     public void testGetResponseHeader() throws Exception {
157         this.server.setHttpService(new HeaderDumpService());
158         
159         GetMethod method = new GetMethod("/");
160         try {
161             this.client.executeMethod(method);
162             Header h = new Header("HeaderSetByServlet","Yes");
163             assertEquals(h, method.getResponseHeader("headersetbyservlet"));
164         } finally {
165             method.releaseConnection();
166         }
167     }
168 
169     /**
170      * Test {@link HttpMethodBase.addHostRequestHeader}.
171      */
172     public void testHostRequestHeader() throws Exception {
173         this.server.setHttpService(new HeaderDumpService());
174 
175         String hostname = this.server.getLocalAddress();
176         int port = this.server.getLocalPort();
177         
178         InetAddress addr = InetAddress.getByName(hostname);
179         String ip = addr.getHostAddress();
180 
181         GetMethod get = new GetMethod("/");
182 
183         // Open connection using IP.  Host header should be sent
184         // Note: RFC 2616 is somewhat unclear on whether a host should
185         // be sent in this context - however, both Mozilla and IE send
186         // the header for an IP address, instead of sending blank.
187         this.client.getHostConfiguration().setHost(ip, port);
188         try {
189             this.client.executeMethod(get);
190             Header hostHeader = get.getRequestHeader("Host");
191             assertTrue(hostHeader != null);
192             if (port == Protocol.getProtocol("http").getDefaultPort()) {
193                 // no port information should be in the value
194                 assertTrue(hostHeader.getValue().equals(ip));
195             } else {
196                 assertTrue(hostHeader.getValue().equals(ip + ":" + port));
197             }
198         } finally {
199             get.releaseConnection();
200         }
201 
202         get = new GetMethod("/");
203         // Open connection using Host.  Host header should
204         // contain this value (this test will fail if DNS
205         // is not available. Additionally, if the port is
206         // something other that 80, then the port value
207         // should also be present in the header.
208         this.client.getHostConfiguration().setHost(hostname, port);
209         try {
210             this.client.executeMethod(get);
211             Header hostHeader = get.getRequestHeader("Host");
212             assertTrue(hostHeader != null);
213             if (port == Protocol.getProtocol("http").getDefaultPort()) {
214                 // no port information should be in the value
215                 assertTrue(hostHeader.getValue().equals(hostname));
216             } else {
217                 assertTrue(hostHeader.getValue().equals(hostname + ":" + port));
218             }
219         } finally {
220             get.releaseConnection();
221         }
222     }
223 }
224 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHostConfiguration.html100644 0 0 52354 10661532627 30301 0ustar 0 0 TestHostConfiguration xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestHostConfiguration.java $
3    * $Revision: 509577 $
4    * $Date: 2007-02-20 15:28:18 +0100 (Tue, 20 Feb 2007) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   */
28  
29  package org.apache.commons.httpclient;
30  
31  import java.io.IOException;
32  import java.net.UnknownHostException;
33  
34  import junit.framework.Test;
35  import junit.framework.TestSuite;
36  
37  import org.apache.commons.httpclient.methods.GetMethod;
38  import org.apache.commons.httpclient.protocol.Protocol;
39  import org.apache.commons.httpclient.server.SimpleProxy;
40  
41  /**
42   * Tests basic HostConfiguration functionality.
43   *
44   * @author Oleg Kalnichevski
45   * 
46   * @version $Id: TestHostConfiguration.java 509577 2007-02-20 14:28:18Z rolandw $
47   */
48  public class TestHostConfiguration extends HttpClientTestBase {
49  
50      public TestHostConfiguration(final String testName) throws IOException {
51          super(testName);
52      }
53  
54      public static Test suite() {
55          return new TestSuite(TestHostConfiguration.class);
56      }
57  
58      public static void main(String args[]) {
59          String[] testCaseName = { TestHostConfiguration.class.getName() };
60          junit.textui.TestRunner.main(testCaseName);
61      }
62      
63      public void testRelativeURLHitWithDefaultHost() throws IOException {
64          this.server.setHttpService(new EchoService());
65          // Set default host
66          this.client.getHostConfiguration().setHost(
67                  this.server.getLocalAddress(), 
68                  this.server.getLocalPort(),
69                  Protocol.getProtocol("http"));
70          
71          GetMethod httpget = new GetMethod("/test/");
72          try {
73              this.client.executeMethod(httpget);
74              assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
75          } finally {
76              httpget.releaseConnection();
77          }
78      }
79  
80      public void testRelativeURLHitWithoutDefaultHost() throws IOException {
81          this.server.setHttpService(new EchoService());
82          // reset default host configuration
83          this.client.setHostConfiguration(new HostConfiguration());
84          
85          GetMethod httpget = new GetMethod("/test/");
86          try {
87              this.client.executeMethod(httpget);
88              fail("IllegalArgumentException should have been thrown");
89          } catch (IllegalArgumentException expected) { 
90          } finally {
91              httpget.releaseConnection();
92          }
93      }
94  
95      public void testAbsoluteURLHitWithoutDefaultHost() throws IOException {
96          this.server.setHttpService(new EchoService());
97          // reset default host configuration
98          this.client.setHostConfiguration(new HostConfiguration());
99          
100         GetMethod httpget = new GetMethod("http://" + 
101                 this.server.getLocalAddress() + ":" + this.server.getLocalPort() + "/test/");
102         try {
103             this.client.executeMethod(httpget);
104             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
105         } finally {
106             httpget.releaseConnection();
107         }
108     }
109 
110     public void testAbsoluteURLOverridesClientDefaultHost() throws IOException {
111         this.server.setHttpService(new EchoService());
112         // Somewhere out there in pampa
113         this.client.getHostConfiguration().setHost("somewhere.outthere.in.pampa", 9999);
114         
115         GetMethod httpget = new GetMethod("http://" + 
116                 this.server.getLocalAddress() + ":" + this.server.getLocalPort() + "/test/");
117         try {
118             this.client.executeMethod(httpget);
119             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
120         } finally {
121             httpget.releaseConnection();
122         }
123         httpget = new GetMethod("/test/");
124         try {
125             this.client.executeMethod(httpget);
126             fail("UnknownHostException should have been thrown");
127         } catch (UnknownHostException expected) { 
128         } finally {
129             httpget.releaseConnection();
130         }
131     }
132 
133     public void testAbsoluteURLOverridesDefaultHostParam() throws IOException {
134 
135         this.proxy = new SimpleProxy();
136         
137         this.server.setHttpService(new EchoService());
138         // reset default host configuration
139         HostConfiguration hostconfig = new HostConfiguration();
140         hostconfig.setHost("somehwere.outthere.in.pampa", 9999);
141         hostconfig.setProxy(
142                 this.proxy.getLocalAddress(), 
143                 this.proxy.getLocalPort());                
144         
145         GetMethod httpget = new GetMethod("http://" + 
146                 this.server.getLocalAddress() + ":" + this.server.getLocalPort() + "/test/");
147         try {
148             this.client.executeMethod(hostconfig, httpget);
149             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
150             assertNotNull(httpget.getResponseHeader("Via"));
151         } finally {
152             httpget.releaseConnection();
153         }
154         httpget = new GetMethod("/test/");
155         try {
156             this.client.executeMethod(hostconfig, httpget);
157             assertEquals(HttpStatus.SC_NOT_FOUND, httpget.getStatusCode());
158         } finally {
159             httpget.releaseConnection();
160         }
161     }
162 
163     /**
164      * Test that HttpClient uses HostConfiguration.clone (not the copy
165      * constructor) to copy its default HostConfiguration when preparing to
166      * execute a method. This behavior is required to support specialized
167      * Protocols; for example, HostConfigurationWithStickyProtocol.
168      * 
169      * @see org.apache.commons.httpclient.contrib.ssl.HostConfigurationWithStickyProtocol
170      */
171     public void testClientClonesHostConfiguration() throws IOException {
172         this.server.setHttpService(new EchoService());
173         SpecialHostConfiguration configuration = new SpecialHostConfiguration(this.client
174                 .getHostConfiguration());
175         configuration.setHost(this.server.getLocalAddress(), this.server.getLocalPort(),
176                 new String(HttpURL.DEFAULT_SCHEME));
177         this.client.setHostConfiguration(configuration);
178 
179         HttpMethod method = new GetMethod(configuration.getHostURL() + "/test/");
180         try {
181             this.client.executeMethod(method);
182             fail("HostConfiguration wasn't cloned");
183         } catch (ExpectedError e) {
184             assertNotSame("ExpectedError.configuration", configuration, e.configuration);
185         } finally {
186             method.releaseConnection();
187         }
188 
189         method = new GetMethod("/test/");
190         try {
191             this.client.executeMethod(method);
192             fail("HostConfiguration wasn't cloned");
193         } catch (ExpectedError e) {
194             assertNotSame("ExpectedError.configuration", configuration, e.configuration);
195         } finally {
196             method.releaseConnection();
197         }
198     }
199 
200     /** A HostConfiguration that refuses to provide a protocol. */
201     private class SpecialHostConfiguration extends HostConfiguration
202     {
203         SpecialHostConfiguration(HostConfiguration hostConfiguration)
204         {
205             super(hostConfiguration);
206         }
207 
208         public Object clone()
209         {
210             return new SpecialHostConfiguration(this);
211         }
212 
213         public synchronized Protocol getProtocol()
214         {
215             throw new ExpectedError(this);
216         }
217     }
218 
219     private class ExpectedError extends Error
220     {
221         ExpectedError(SpecialHostConfiguration c)
222         {
223             configuration = c;
224         }
225 
226         SpecialHostConfiguration configuration;
227 
228         private static final long serialVersionUID = 1L;
229 
230     }
231 
232 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHttpConnection.html100644 0 0 53354 10661532627 27574 0ustar 0 0 TestHttpConnection xref

1   /*
2    * $Header$
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import java.io.IOException;
35  import java.io.InputStream;
36  import java.io.OutputStream;
37  import java.net.InetAddress;
38  import java.net.Socket;
39  import java.net.UnknownHostException;
40  
41  import junit.framework.Test;
42  import junit.framework.TestSuite;
43  
44  import org.apache.commons.httpclient.methods.GetMethod;
45  import org.apache.commons.httpclient.params.HttpConnectionParams;
46  import org.apache.commons.httpclient.protocol.Protocol;
47  import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
48  import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;
49  
50  /**
51   *
52   * Unit tests for {@link HttpConnection}.
53   *
54   * @author Sean C. Sullivan
55   *
56   * @version $Id: TestHttpConnection.java 480424 2006-11-29 05:56:49Z bayard $
57   *
58   */
59  public class TestHttpConnection extends HttpClientTestBase {
60      
61      // ------------------------------------------------------------ Constructor
62      public TestHttpConnection(String testName) throws Exception {
63          super(testName);
64      }
65  
66      // ------------------------------------------------------------------- Main
67      public static void main(String args[]) {
68          String[] testCaseName = { TestHttpConnection.class.getName() };
69          junit.textui.TestRunner.main(testCaseName);
70      }
71  
72      // ------------------------------------------------------- TestCase Methods
73  
74      public static Test suite() {
75          return new TestSuite(TestHttpConnection.class);
76      }
77  
78  
79      // ----------------------------------------------------------- Test Methods
80  
81      public void testConstructThenClose() {
82  		this.server.setHttpService(new EchoService());
83          HttpConnection conn = new HttpConnection(
84  				this.server.getLocalAddress(), this.server.getLocalPort());
85          conn.close();
86          assertTrue(!conn.isOpen());
87      }
88  
89      public void testConnTimeoutRelease() {
90  		this.server.setHttpService(new EchoService());
91          // create a custom protocol that will delay for 500 milliseconds
92          Protocol testProtocol = new Protocol(
93              "timeout",
94              new DelayedProtocolSocketFactory(
95                  500, 
96                  Protocol.getProtocol("http").getSocketFactory()
97              ),
98  			this.server.getLocalPort()
99          );
100 
101         NoHostHttpConnectionManager connectionManager = new NoHostHttpConnectionManager();
102         connectionManager.setConnection(
103 				new HttpConnection(
104 						this.server.getLocalAddress(), this.server.getLocalPort(), testProtocol));
105         this.client.setHttpConnectionManager(connectionManager);
106         client.getHostConfiguration().setHost(
107 				this.server.getLocalAddress(), this.server.getLocalPort(), testProtocol);
108         client.getHttpConnectionManager().getParams().setConnectionTimeout(1);
109         
110         try {
111             GetMethod get = new GetMethod();
112             client.executeMethod(get);
113             fail("Should have timed out");
114         } catch(IOException e) {
115             /* should fail */
116             assertTrue(e instanceof ConnectTimeoutException);
117             assertTrue(connectionManager.isConnectionReleased());
118         }
119     }
120 
121 
122     public void testConnTimeout() {
123 
124         // create a custom protocol that will delay for 500 milliseconds
125         Protocol testProtocol = new Protocol(
126             "timeout",
127             new DelayedProtocolSocketFactory(
128                 500, 
129                 Protocol.getProtocol("http").getSocketFactory()
130             ),
131 			this.server.getLocalPort()
132         );
133 
134         HttpConnection conn = new HttpConnection(
135 				this.server.getLocalAddress(), this.server.getLocalPort(), testProtocol);
136         // 1 ms is short enough to make this fail
137         conn.getParams().setConnectionTimeout(1);
138         try {
139             conn.open();
140             fail("Should have timed out");
141         } catch(IOException e) {
142             assertTrue(e instanceof ConnectTimeoutException);
143             /* should fail */
144         }
145     }
146 
147     public void testForIllegalStateExceptions() {
148         HttpConnection conn = new HttpConnection(
149 				this.server.getLocalAddress(), this.server.getLocalPort());
150         try {
151             OutputStream out = conn.getRequestOutputStream();
152             fail("getRequestOutputStream did not throw the expected exception");
153         }
154         catch (IllegalStateException expected) {
155             // this exception is expected
156         }
157         catch (IOException ex) {
158             fail("getRequestOutputStream did not throw the expected exception");
159         }
160 
161         try {
162             OutputStream out = new ChunkedOutputStream(conn.getRequestOutputStream());
163             fail("getRequestOutputStream(true) did not throw the expected exception");
164         }
165         catch (IllegalStateException expected) {
166             // this exception is expected
167         }
168         catch (IOException ex) {
169             fail("getRequestOutputStream(true) did not throw the expected exception");
170         }
171 
172         try {
173             InputStream in = conn.getResponseInputStream();
174             fail("getResponseInputStream() did not throw the expected exception");
175         }
176         catch (IllegalStateException expected) {
177             // this exception is expected
178         }
179         catch (IOException ex) {
180             fail("getResponseInputStream() did not throw the expected exception");
181         }
182 
183     }
184     
185     /**
186      * A ProtocolSocketFactory that delays before creating a socket.
187      */
188     class DelayedProtocolSocketFactory implements ProtocolSocketFactory {
189         
190         private int delay;
191         private ProtocolSocketFactory realFactory;
192             
193         public DelayedProtocolSocketFactory(int delay, ProtocolSocketFactory realFactory) {
194             this.delay = delay;
195             this.realFactory = realFactory;            
196         }
197                 
198         public Socket createSocket(
199             String host,
200             int port,
201             InetAddress localAddress,
202             int localPort
203         ) throws IOException, UnknownHostException {
204             
205             synchronized (this) {
206                 try {
207                     this.wait(delay);
208                 } catch (InterruptedException e) {}
209             }
210             return realFactory.createSocket(host, port, localAddress, localPort);
211         }
212 
213         public Socket createSocket(
214             final String host,
215             final int port,
216             final InetAddress localAddress,
217             final int localPort,
218             final HttpConnectionParams params
219         ) throws IOException, UnknownHostException {
220             
221             if (params == null) {
222                 throw new IllegalArgumentException("Parameters may not be null");
223             }
224             int timeout = params.getConnectionTimeout();
225             ControllerThreadSocketFactory.SocketTask task = new ControllerThreadSocketFactory.SocketTask() {
226                 public void doit() throws IOException {
227                     synchronized (this) {
228                         try {
229                             this.wait(delay);
230                         } catch (InterruptedException e) {}
231                     }
232                     setSocket(realFactory.createSocket(host, port, localAddress, localPort));
233                 }
234             };
235             return ControllerThreadSocketFactory.createSocket(task, timeout);
236         }
237 
238         public Socket createSocket(String host, int port)
239             throws IOException, UnknownHostException {
240             synchronized (this) {
241                 try {
242                     this.wait(delay);
243                 } catch (InterruptedException e) {}
244             }
245             return realFactory.createSocket(host, port);
246         }
247 
248     }
249 
250 }
251 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHttpConnectionManager.html100644 0 0 224173 10661532627 31106 0ustar 0 0 TestHttpConnectionManager xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttpConnectionManager.java,v 1.23 2004/07/17 18:58:33 mbecke Exp $
3    * $Revision: 509320 $
4    * $Date: 2007-02-19 20:52:43 +0100 (Mon, 19 Feb 2007) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   */
28  
29  package org.apache.commons.httpclient;
30  
31  import java.io.IOException;
32  import java.lang.ref.WeakReference;
33  import java.net.InetAddress;
34  import java.net.Socket;
35  import java.net.UnknownHostException;
36  
37  import junit.framework.Test;
38  import junit.framework.TestSuite;
39  
40  import org.apache.commons.httpclient.methods.GetMethod;
41  import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
42  import org.apache.commons.httpclient.params.HttpConnectionParams;
43  import org.apache.commons.httpclient.protocol.Protocol;
44  import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
45  import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
46  import org.apache.commons.httpclient.server.SimpleRequest;
47  import org.apache.commons.httpclient.server.SimpleResponse;
48  
49  /**
50   * Unit tests for {@link HttpConnectionManager}.
51   *
52   * @author Marc A. Saegesser
53   * @version $Id: TestHttpConnectionManager.java 509320 2007-02-19 19:52:43Z mbecke $
54   */
55  public class TestHttpConnectionManager extends HttpClientTestBase {
56  
57      // ------------------------------------------------------------ Constructor
58      public TestHttpConnectionManager(String testName) throws IOException {
59          super(testName);
60      }
61  
62      // ------------------------------------------------------------------- Main
63      public static void main(String args[]) {
64          String[] testCaseName = { TestHttpConnectionManager.class.getName() };
65          junit.textui.TestRunner.main(testCaseName);
66      }
67  
68      // ------------------------------------------------------- TestCase Methods
69  
70      public static Test suite() {
71          return new TestSuite(TestHttpConnectionManager.class);
72      }
73  
74  
75      // ----------------------------------------------------------- Test Methods
76  
77      /**
78       * Test that the ConnectMethod correctly releases connections when
79       * CONNECT fails.
80       */
81      public void testConnectMethodFailureRelease() throws Exception {
82          
83          MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
84          mgr.getParams().setIntParameter(
85              HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 1);
86          client.setHttpConnectionManager(mgr);
87          this.server.setHttpService(new RejectConnectService());
88          
89          // we're going to execute a connect method against the localhost, assuming
90          // that CONNECT is not supported.  This should test the fakeResponse()
91          // code on HttpMethodBase.
92          client.getHostConfiguration().setProxy(server.getLocalAddress(), server.getLocalPort());
93          // we must set the host to a secure destination or the CONNECT method
94          // will not be used
95          client.getHostConfiguration().setHost(
96              "notARealHost", 
97              1234, 
98              new Protocol(
99                  "https", 
100                 (ProtocolSocketFactory)new FakeSecureProtocolSocketFactory(), 
101                 443)
102         );
103         
104         GetMethod get = new GetMethod("/");
105         try {
106             assertTrue(client.executeMethod(get) != 200);
107         } catch (IOException e) {
108             e.printStackTrace();
109             fail("Error executing connect: " + e);
110         }
111 
112         // this should calling releaseConnection() releases the connection
113         try {
114             get.releaseConnection();
115             mgr.getConnectionWithTimeout(client.getHostConfiguration(), 1).releaseConnection();
116         } catch (ConnectTimeoutException e1) {
117             fail("Connection should have been available.");
118         }
119         
120         get = new GetMethod("/");
121         
122         try {
123             assertTrue(client.executeMethod(get) != 200);
124         } catch (IOException e) {
125             e.printStackTrace();
126             fail("Error executing connect: " + e);
127         }
128 
129         // make sure reading the response fully releases the connection        
130         try {
131             get.getResponseBodyAsString();
132             mgr.getConnectionWithTimeout(client.getHostConfiguration(), 1).releaseConnection();
133         } catch (ConnectTimeoutException e1) {
134             fail("Connection should have been available.");
135         }     
136         
137         get = new GetMethod("/");
138         
139         try {
140             assertTrue(client.executeMethod(get) != 200);
141         } catch (IOException e) {
142             e.printStackTrace();
143             fail("Error executing connect: " + e);
144         }
145 
146         // make sure closing the output stream releases the connection        
147         try {
148             get.getResponseBodyAsStream().close();
149             mgr.getConnectionWithTimeout(client.getHostConfiguration(), 1).releaseConnection();
150         } catch (ConnectTimeoutException e) {
151             fail("Connection should have been available.");
152         } catch (IOException e) {
153             e.printStackTrace();
154             fail("Close connection failed: " + e);   
155         }
156     }
157 
158     public void testGetConnection() {
159         MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
160 
161         HostConfiguration hostConfiguration = new HostConfiguration();
162         hostConfiguration.setHost("www.nosuchserver.com", 80, "http");
163 
164         // Create a new connection
165         HttpConnection conn = mgr.getConnection(hostConfiguration);
166         // Validate the connection properties
167         assertEquals("Host", "www.nosuchserver.com", conn.getHost());
168         assertEquals("Port", 80, conn.getPort());
169         // Release the connection
170         mgr.releaseConnection(conn);
171 
172         // Create a new connection
173         hostConfiguration.setHost("www.nosuchserver.com", -1, "https");
174         conn = mgr.getConnection(hostConfiguration);
175         // Validate the connection properties
176         assertEquals("Host", "www.nosuchserver.com", conn.getHost());
177         assertEquals("Port", 443, conn.getPort());
178         // Release the connection
179         mgr.releaseConnection(conn);
180 
181         // Create a new connection
182         hostConfiguration.setHost("www.nowhere.org", 8080, "http");
183         conn = mgr.getConnection(hostConfiguration);
184         // Validate the connection properties
185         assertEquals("Host", "www.nowhere.org", conn.getHost());
186         assertEquals("Port", 8080, conn.getPort());
187         // Release the connection
188         mgr.releaseConnection(conn);
189 
190     }
191 
192     public void testDroppedThread() throws Exception {
193 
194         this.server.setHttpService(new EchoService());
195 
196         MultiThreadedHttpConnectionManager mthcm = new MultiThreadedHttpConnectionManager();
197         client.setHttpConnectionManager(mthcm);
198         WeakReference wr = new WeakReference(mthcm);
199 
200         GetMethod method = new GetMethod("/");
201         client.executeMethod(method);
202         method.releaseConnection();
203 
204         mthcm = null;
205         client = null;
206         method = null;
207         
208         System.gc();
209 
210         // this sleep appears to be necessary in order to give the JVM
211         // time to clean up the miscellaneous pointers to the connection manager
212         try {
213             Thread.sleep(1000);
214         } catch (InterruptedException e) {
215             fail("shouldn't be interrupted.");
216         }
217 
218         Object connectionManager = wr.get();
219         assertNull("connectionManager should be null", connectionManager);
220     }    
221     
222     public void testWriteRequestReleaseConnection() {
223 
224         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
225         connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);
226 
227         client.setHttpConnectionManager(connectionManager);
228         
229         GetMethod get = new GetMethod("/") {
230             protected boolean writeRequestBody(HttpState state, HttpConnection conn)
231                 throws IOException, HttpException {
232                 throw new IOException("Oh no!!");
233             }
234         };
235         
236         try {
237             client.executeMethod(get);
238             fail("An exception should have occurred.");
239         } catch (HttpException e) {
240             e.printStackTrace();
241             fail("HttpException should not have occurred: " + e);
242         } catch (IOException e) {
243             // expected
244         }
245         
246         try {
247             connectionManager.getConnectionWithTimeout(client.getHostConfiguration(), 1);
248         } catch (ConnectTimeoutException e) {
249             e.printStackTrace();
250             fail("Connection was not released: " + e);
251         }
252         
253     }
254     
255     public void testReleaseConnection() {
256 
257         this.server.setHttpService(new EchoService());
258 
259         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
260         connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);
261 
262         client.setHttpConnectionManager(connectionManager);
263         // we shouldn't have to wait if a connection is available
264         client.getParams().setConnectionManagerTimeout(1);
265 
266         GetMethod getMethod = new GetMethod("/");
267 
268         try {
269             client.executeMethod(getMethod);
270         } catch (Exception e) {
271             fail("error reading from server: " + e);
272         }
273 
274         try {
275             // this should fail quickly since the connection has not been released
276             client.executeMethod(getMethod);
277             fail("a httpConnection should not be available");
278         } catch (ConnectTimeoutException e) {            
279         } catch (HttpException e) {
280             fail("error reading from server; " + e);
281         } catch (IOException e) {
282             e.printStackTrace();
283             fail("error reading from server; " + e);
284         }
285 
286         // this should release the connection
287         getMethod.releaseConnection();
288 
289         getMethod = new GetMethod("/");
290 
291         try {
292             // this should fail quickly if the connection has not been released
293             client.executeMethod(getMethod);
294         } catch (HttpException e) {
295             fail("httpConnection does not appear to have been released: " + e);
296         } catch (IOException e) {
297             fail("error reading from server; " + e);
298         }
299 
300     }
301 
302     /**
303      * Makes sure that a connection gets released after the content of the body
304      * is read.
305      */
306     public void testResponseAutoRelease() throws Exception  {
307 
308         this.server.setHttpService(new EchoService());
309 
310         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
311         connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);
312 
313         client.setHttpConnectionManager(connectionManager);
314         // we shouldn't have to wait if a connection is available
315         client.getParams().setConnectionManagerTimeout( 1 );
316 
317         GetMethod getMethod = new GetMethod("/");
318 
319         try {
320             client.executeMethod(getMethod);
321         } catch (Exception e) {
322             fail("error reading from server: " + e);
323         }
324         
325         // this should release the connection
326         getMethod.getResponseBody();
327 
328         getMethod = new GetMethod("/");
329 
330         try {
331             // this should fail quickly if the connection has not been released
332             client.executeMethod(getMethod);
333         } catch (HttpException e) {
334             fail("httpConnection does not appear to have been released: " + e);
335         } catch (IOException e) {
336             fail("error reading from server; " + e);
337         }
338 
339     }
340     
341     /**
342      * Tests the MultiThreadedHttpConnectionManager's ability to reclaim unused 
343      * connections.
344      */
345     public void testConnectionReclaiming() {
346         
347         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
348         connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);
349         connectionManager.getParams().setMaxTotalConnections(1);
350 
351         HostConfiguration host1 = new HostConfiguration();
352         host1.setHost("host1", -1, "http");
353 
354         HostConfiguration host2 = new HostConfiguration();
355         host2.setHost("host2", -1, "http");
356 
357         HttpConnection connection = connectionManager.getConnection(host1);
358         // now release this connection
359         connection.releaseConnection();
360         connection = null;
361         
362         try {
363             // the connection from host1 should be reclaimed
364             connection = connectionManager.getConnectionWithTimeout(host2, 100);
365         } catch (ConnectTimeoutException e) {
366             e.printStackTrace();
367             fail("a httpConnection should have been available: " + e);
368         }        
369     }
370     
371     /**
372      * Tests that {@link MultiThreadedHttpConnectionManager#shutdownAll()} closes all resources
373      * and makes all connection mangers unusable.
374      */
375     public void testShutdownAll() {
376 
377         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
378         connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);
379         connectionManager.getParams().setMaxTotalConnections(1);
380 
381         HostConfiguration host1 = new HostConfiguration();
382         host1.setHost("host1", -1, "http");
383 
384         // hold on to the only connection
385         HttpConnection connection = connectionManager.getConnection(host1);
386 
387         // wait for a connection on another thread
388         GetConnectionThread getConn = new GetConnectionThread(host1, connectionManager, 0);
389         getConn.start();
390         
391         MultiThreadedHttpConnectionManager.shutdownAll();
392         
393         // now release this connection, this should close the connection, but have no other effect
394         connection.releaseConnection();
395         connection = null;
396         
397         try {
398             getConn.join();
399         } catch (InterruptedException e) {
400             e.printStackTrace();
401         }
402         
403         // this thread should have caught an exception without getting a connection
404         assertNull("Not connection should have been checked out", getConn.getConnection());
405         assertNotNull("There should have been an exception", getConn.getException());
406         
407         try {
408             connectionManager.getConnection(host1);
409             fail("An exception should have occurred");
410         } catch (Exception e) {
411             // this is expected
412         }
413     }
414         
415     /**
416      * Tests that {@link MultiThreadedHttpConnectionManager#shutdown()} closes all resources
417      * and makes the connection manger unusable.
418      */
419     public void testShutdown() {
420 
421         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
422         connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);
423         connectionManager.getParams().setMaxTotalConnections(1);
424 
425         HostConfiguration host1 = new HostConfiguration();
426         host1.setHost("host1", -1, "http");
427 
428         // hold on to the only connection
429         HttpConnection connection = connectionManager.getConnection(host1);
430 
431         // wait for a connection on another thread
432         GetConnectionThread getConn = new GetConnectionThread(host1, connectionManager, 0);
433         getConn.start();
434         
435         connectionManager.shutdown();
436         
437         // now release this connection, this should close the connection, but have no other effect
438         connection.releaseConnection();
439         connection = null;
440         
441         try {
442             getConn.join();
443         } catch (InterruptedException e) {
444             e.printStackTrace();
445         }
446         
447         // this thread should have caught an exception without getting a connection
448         assertNull("Not connection should have been checked out", getConn.getConnection());
449         assertNotNull("There should have been an exception", getConn.getException());
450         
451         try {
452             connectionManager.getConnection(host1);
453             fail("An exception should have occurred");
454         } catch (Exception e) {
455             // this is expected
456         }
457     }
458     
459     /**
460      * Tests the MultiThreadedHttpConnectionManager's ability to restrict the maximum number 
461      * of connections.
462      */    
463     public void testMaxConnections() {
464         
465         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
466         connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);
467         connectionManager.getParams().setMaxTotalConnections(2);
468 
469         HostConfiguration host1 = new HostConfiguration();
470         host1.setHost("host1", -1, "http");
471 
472         HostConfiguration host2 = new HostConfiguration();
473         host2.setHost("host2", -1, "http");
474 
475         HttpConnection connection1 = connectionManager.getConnection(host1);
476         HttpConnection connection2 = connectionManager.getConnection(host2);
477     
478         try {
479             // this should fail quickly since the connection has not been released
480             connectionManager.getConnectionWithTimeout(host2, 100);
481             fail("ConnectionPoolTimeoutException should not be available");
482         } catch (ConnectionPoolTimeoutException e) {
483             // this should throw an exception
484         }
485         
486         // release one of the connections
487         connection2.releaseConnection();
488         connection2 = null;
489         
490         try {
491             // there should be a connection available now
492             connection2 = connectionManager.getConnectionWithTimeout(host2, 100);
493         } catch (ConnectionPoolTimeoutException e) {
494             e.printStackTrace();
495             fail("a httpConnection should have been available: " + e);
496         }
497     }    
498 
499     /**
500      * Tests the MultiThreadedHttpConnectionManager's ability to restrict the maximum number 
501      * of connections per host.
502      */    
503     public void testMaxConnectionsPerHost() throws Exception {
504         
505         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
506         connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);
507         connectionManager.getParams().setMaxTotalConnections(100);
508 
509         HostConfiguration host1 = new HostConfiguration();
510         host1.setHost("host1", -1, "http");
511 
512         HostConfiguration host2 = new HostConfiguration();
513         host2.setHost("host2", -1, "http");
514 
515         HostConfiguration host3 = new HostConfiguration();
516         host3.setHost("host3", -1, "http");
517 
518         connectionManager.getParams().setMaxConnectionsPerHost(host1, 3);
519         connectionManager.getParams().setMaxConnectionsPerHost(host2, 2);
520 
521         // Host1
522         HttpConnection connection1 = connectionManager.getConnectionWithTimeout(host1, 1000);
523         HttpConnection connection2 = connectionManager.getConnectionWithTimeout(host1, 1000);
524         HttpConnection connection3 = connectionManager.getConnectionWithTimeout(host1, 1000);
525         try {
526             // this should fail quickly since the connection has not been released
527             connectionManager.getConnectionWithTimeout(host1, 100);
528             fail("ConnectionPoolTimeoutException should not be available");
529         } catch (ConnectionPoolTimeoutException e) {
530             // expected
531         }
532         
533         // Host2
534         connection1 = connectionManager.getConnectionWithTimeout(host2, 1000);
535         connection2 = connectionManager.getConnectionWithTimeout(host2, 1000);
536         try {
537             // this should fail quickly since the connection has not been released
538             connectionManager.getConnectionWithTimeout(host2, 100);
539             fail("ConnectionPoolTimeoutException should not be available");
540         } catch (ConnectionPoolTimeoutException e) {
541             // expected
542         }
543 
544         // Host3 (should use the default per host value)
545         connection1 = connectionManager.getConnectionWithTimeout(host3, 1000);
546         try {
547             // this should fail quickly since the connection has not been released
548             connectionManager.getConnectionWithTimeout(host3, 100);
549             fail("ConnectionPoolTimeoutException should not be available");
550         } catch (ConnectionPoolTimeoutException e) {
551             // expected
552         }
553     }    
554 
555     public void testHostReusePreference() {
556         
557         final MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
558         connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);
559         connectionManager.getParams().setMaxTotalConnections(1);
560 
561         final HostConfiguration host1 = new HostConfiguration();
562         host1.setHost("host1", -1, "http");
563 
564         final HostConfiguration host2 = new HostConfiguration();
565         host2.setHost("host2", -1, "http");
566 
567         HttpConnection connection = connectionManager.getConnection(host1);
568 
569         GetConnectionThread getHost1 = new GetConnectionThread(host1, connectionManager, 200);
570         GetConnectionThread getHost2 = new GetConnectionThread(host2, connectionManager, 200);
571         
572         getHost2.start();
573         getHost1.start();
574         
575         // give the threads some time to startup
576         try {
577             Thread.sleep(100);
578         } catch (InterruptedException e1) {
579             e1.printStackTrace();
580         }
581             
582         // after the connection to host1 is released it should be given to getHost1
583         connection.releaseConnection();
584         connection = null;
585 
586         try {
587             getHost1.join();
588             getHost2.join();
589         } catch (InterruptedException e) {
590             e.printStackTrace();
591         }
592 
593         assertNotSame(
594             "Connection should have been given to someone", 
595             getHost1.getConnection(),
596             getHost2.getConnection()
597         );        
598         assertNotNull("Connection should have been given to host1", getHost1.getConnection());
599         assertNull("Connection should NOT have been given to host2", getHost2.getConnection());
600         
601     } 
602     
603     public void testMaxConnectionsPerServer() {
604      
605         this.server.setHttpService(new EchoService());
606 
607         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
608         connectionManager.getParams().setDefaultMaxConnectionsPerHost(1);
609 
610         client.setHttpConnectionManager(connectionManager);
611         // we shouldn't have to wait if a connection is available
612         client.getParams().setConnectionManagerTimeout( 1 );
613 
614         GetMethod getMethod = new GetMethod("/");
615 
616         try {
617             client.executeMethod(getMethod);
618         } catch (Exception e) {
619             fail("error reading from server: " + e);
620         }
621 
622         GetMethod getMethod2 = new GetMethod("/");
623 
624         try {
625             // this should fail quickly since the connection has not been released
626             client.executeMethod(getMethod2);
627             fail("a httpConnection should not be available");
628         } catch (ConnectTimeoutException e) {
629         } catch (HttpException e) {
630             fail("error reading from server; " + e);
631         } catch (IOException e) {
632             fail("error reading from server; " + e);
633         }
634                 
635     }
636     
637     public void testDeleteClosedConnections() {
638         
639         MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
640         
641         HttpConnection conn = manager.getConnection(client.getHostConfiguration());
642         
643         assertEquals("connectionsInPool", manager.getConnectionsInPool(), 1);
644         assertEquals("connectionsInPool(host)", manager.getConnectionsInPool(client.getHostConfiguration()), 1);
645         
646         conn.close();
647         conn.releaseConnection();
648 
649         assertEquals("connectionsInPool", manager.getConnectionsInPool(), 1);
650         assertEquals("connectionsInPool(host)", manager.getConnectionsInPool(client.getHostConfiguration()), 1);
651 
652         manager.deleteClosedConnections();
653         
654         assertEquals("connectionsInPool", manager.getConnectionsInPool(), 0);
655         assertEquals("connectionsInPool(host)", manager.getConnectionsInPool(client.getHostConfiguration()), 0);
656     }
657     
658     /**
659      * Tests that thread waiting in the MultiThreadedHttpConnectionManager can be 
660      * interrupted.
661      */
662     public void testWaitingThreadInterrupted() {
663 
664         this.server.setHttpService(new EchoService());
665 
666         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
667         connectionManager.getParams().setIntParameter(
668             HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 1);
669 
670         HostConfiguration host1 = new HostConfiguration();
671         host1.setHost("host1", -1, "http");
672 
673         // hold on to the only connection
674         HttpConnection connection = connectionManager.getConnection(host1);
675 
676         // wait for a connection on another thread
677         GetConnectionThread getConn = new GetConnectionThread(host1, connectionManager, 1000);
678         getConn.start();
679         
680         // give the thread a chance to block
681         synchronized (this) {
682             try {
683                 this.wait(500);
684             } catch (InterruptedException e) {
685                 e.printStackTrace();
686             }
687         }
688         
689         // interrupt the thread, this should cancel waiting with a RuntimeException
690         getConn.interrupt();
691         
692         try {
693             getConn.join();
694         } catch (InterruptedException e) {
695             e.printStackTrace();
696         }
697         
698         // make sure the correct exception was thrown
699         assertTrue(getConn.exception != null);
700         assertEquals(getConn.exception.getClass(), IllegalThreadStateException.class);
701         
702         // make sure the connection manager is still working
703         connection.releaseConnection();
704         try {
705             connectionManager.getConnectionWithTimeout(host1, 10);
706         } catch (ConnectionPoolTimeoutException e) {
707             fail("Connection not available");
708         }
709     }
710     
711     public void testReclaimUnusedConnection() {
712 
713         this.server.setHttpService(new EchoService());
714 
715         MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
716         connectionManager.getParams().setIntParameter(
717             HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 1);
718 
719         client.setHttpConnectionManager(connectionManager);
720         // we shouldn't have to wait if a connection is available
721         client.getParams().setConnectionManagerTimeout( 30000 );
722 
723         GetMethod getMethod = new GetMethod("/");
724 
725         try {
726             client.executeMethod(getMethod);
727         } catch (Exception e) {
728             fail("error reading from server: " + e);
729         }
730 
731         getMethod = new GetMethod("/");
732         
733         Runtime.getRuntime().gc();
734 
735         try {
736             // we didn't explicitly release the connection, but it should be 
737             // reclaimed by the garbage collector, we hope:)
738             client.executeMethod(getMethod);
739         } catch (HttpException e) {
740             fail("httpConnection does not appear to have been reclaimed by the GC: " + e);
741         } catch (IOException e) {
742             fail("error reading from server; " + e);
743         }
744 
745     }
746     
747     public void testGetFromMultipleThreads() {
748         
749         this.server.setHttpService(new EchoService());
750 
751         client.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
752         ExecuteMethodThread[] threads = new ExecuteMethodThread[10];
753         
754         for (int i = 0; i < threads.length; i++) {
755             GetMethod method = new GetMethod("/");
756             method.setFollowRedirects(true);
757             
758             threads[i] = new ExecuteMethodThread(method, client);
759             threads[i].start();
760         }
761         
762         for (int i = 0; i < threads.length; i++) {
763             try {
764                 // wait until this thread finishes. we'll give it 10 seconds,
765                 // but it shouldn't take that long
766                 threads[i].join(10000);
767             } catch (InterruptedException e) {
768             }
769             // make sure an exception did not occur
770             Exception e = threads[i].getException();
771             if (e != null) {
772                 fail("An error occured in the get: " + e);
773             }
774             // we should have a 200 status
775             assertEquals(threads[i].getMethod().getStatusCode(), HttpStatus.SC_OK);
776         }
777     }
778 
779     public void testTimeout() {
780         MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
781         mgr.getParams().setDefaultMaxConnectionsPerHost(2);
782         
783         try{
784             HostConfiguration hostConfig = new HostConfiguration();
785             hostConfig.setHost("www.nosuchserver.com", 80, "http");
786             
787             HttpConnection conn1 = mgr.getConnection(hostConfig);
788             HttpConnection conn2 = mgr.getConnection(hostConfig);
789             
790             HttpConnection conn3 = mgr.getConnectionWithTimeout(hostConfig, 1000);
791             fail("Expected an HttpException.");
792             
793         }catch(ConnectTimeoutException e){
794             //Expected result
795         }
796     }
797     
798     static class FakeSecureProtocolSocketFactory implements SecureProtocolSocketFactory {
799         
800         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
801             throws IOException, UnknownHostException {
802             throw new IllegalStateException("createSocket() should never have been called.");
803         }
804         
805         public Socket createSocket(String host, int port)
806             throws IOException, UnknownHostException {
807             throw new IllegalStateException("createSocket() should never have been called.");
808         }
809         
810         public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
811             throws IOException, UnknownHostException {
812             throw new IllegalStateException("createSocket() should never have been called.");
813         }
814         
815         public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort, 
816             HttpConnectionParams params)
817             throws IOException, UnknownHostException {
818             throw new IllegalStateException("createSocket() should never have been called.");
819         }
820     }
821     
822     static class RejectConnectService extends EchoService {
823 		public boolean process(SimpleRequest request, SimpleResponse response)
824 				throws IOException {
825             if (request.getRequestLine().getMethod().equalsIgnoreCase("CONNECT")) {
826                 response.setStatusLine(request.getRequestLine().getHttpVersion(), HttpStatus.SC_METHOD_NOT_ALLOWED);
827                 response.setHeader(new Header("Connection", "close"));
828                 return true;
829             } else {
830                 return super.process(request, response);
831             }
832 		}
833     }
834     
835     static class GetConnectionThread extends Thread {
836         
837         private HostConfiguration hostConfiguration;
838         private MultiThreadedHttpConnectionManager connectionManager;
839         private HttpConnection connection;
840         private long timeout;
841         private Exception exception;
842         
843         public GetConnectionThread(
844             HostConfiguration hostConfiguration, 
845             MultiThreadedHttpConnectionManager connectionManager,
846             long timeout
847         ) {
848             this.hostConfiguration = hostConfiguration;
849             this.connectionManager = connectionManager; 
850             this.timeout = timeout;
851         }
852         
853         public void run() {
854             try {
855                 connection = connectionManager.getConnectionWithTimeout(hostConfiguration, timeout);
856             } catch (Exception e) {
857                 this.exception = e;
858             }            
859         }
860         
861         public Exception getException() {
862             return exception;
863         }
864         
865         public HttpConnection getConnection() {
866             return connection;
867         }
868 
869     }
870     
871 }
872 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHttpMethodFundamentals.html100644 0 0 101163 10661532627 31267 0ustar 0 0 TestHttpMethodFundamentals xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttpMethodFundamentals.java,v 1.6 2004/11/06 23:47:58 olegk Exp $
3    * $Revision: 481225 $
4    * $Date: 2006-12-01 12:26:28 +0100 (Fri, 01 Dec 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   */
28  
29  package org.apache.commons.httpclient;
30  
31  import java.io.IOException;
32  import java.io.InputStreamReader;
33  import java.io.Reader;
34  
35  import org.apache.commons.httpclient.methods.GetMethod;
36  import org.apache.commons.httpclient.server.HttpService;
37  import org.apache.commons.httpclient.server.SimpleRequest;
38  import org.apache.commons.httpclient.server.SimpleResponse;
39  
40  import junit.framework.Test;
41  import junit.framework.TestSuite;
42  
43  /**
44   * Tests basic method functionality.
45   *
46   * @author Remy Maucherat
47   * @author Rodney Waldhoff
48   * @author Oleg Kalnichevski
49   * 
50   * @version $Id: TestHttpMethodFundamentals.java 481225 2006-12-01 11:26:28Z oglueck $
51   */
52  public class TestHttpMethodFundamentals extends HttpClientTestBase {
53  
54      public TestHttpMethodFundamentals(final String testName) throws IOException {
55          super(testName);
56      }
57  
58      public static Test suite() {
59          TestSuite suite = new TestSuite(TestHttpMethodFundamentals.class);
60          ProxyTestDecorator.addTests(suite);
61          return suite;
62      }
63  
64      public static void main(String args[]) {
65          String[] testCaseName = { TestHttpMethodFundamentals.class.getName() };
66          junit.textui.TestRunner.main(testCaseName);
67      }
68      
69      class ManyAService implements HttpService {
70  
71          public ManyAService() {
72              super();
73          }
74  
75          public boolean process(final SimpleRequest request, final SimpleResponse response)
76              throws IOException
77          {
78              HttpVersion httpversion = request.getRequestLine().getHttpVersion();
79              response.setStatusLine(httpversion, HttpStatus.SC_OK);
80              response.addHeader(new Header("Content-Type", "text/plain"));            
81              response.addHeader(new Header("Connection", "close"));            
82              StringBuffer buffer = new StringBuffer(1024);
83              for (int i = 0; i < 1024; i++) {
84                  buffer.append('A');
85              }
86              response.setBodyString(buffer.toString());
87              return true;
88          }
89      }
90  
91      class SimpleChunkedService implements HttpService {
92  
93          public SimpleChunkedService() {
94              super();
95          }
96  
97          public boolean process(final SimpleRequest request, final SimpleResponse response)
98              throws IOException
99          {
100             HttpVersion httpversion = request.getRequestLine().getHttpVersion();
101             response.setStatusLine(httpversion, HttpStatus.SC_OK);
102             response.addHeader(new Header("Content-Type", "text/plain"));            
103             response.addHeader(new Header("Content-Length", "garbage")); 
104             response.addHeader(new Header("Transfer-Encoding", "chunked")); 
105             response.addHeader(new Header("Connection", "close"));            
106             response.setBodyString("1234567890123");
107             return true;
108         }
109     }
110 
111     class EmptyResponseService implements HttpService {
112 
113         public EmptyResponseService() {
114             super();
115         }
116 
117         public boolean process(final SimpleRequest request, final SimpleResponse response)
118             throws IOException
119         {
120             HttpVersion httpversion = request.getRequestLine().getHttpVersion();
121             response.setStatusLine(httpversion, HttpStatus.SC_OK);
122             response.addHeader(new Header("Content-Type", "text/plain"));            
123             response.addHeader(new Header("Transfer-Encoding", "chunked")); 
124             response.addHeader(new Header("Connection", "close"));            
125             return true;
126         }
127     }
128 
129     public void testHttpMethodBasePaths() throws Exception {
130         HttpMethod simple = new FakeHttpMethod();
131         String[] paths = {
132            "/some/absolute/path",
133            "../some/relative/path",
134            "/",
135            "/some/path/with?query=string"
136        };
137     
138         for (int i=0; i<paths.length; i++){
139             simple.setPath(paths[i]);
140             assertEquals(paths[i], simple.getPath());
141         }
142     }
143 
144     public void testHttpMethodBaseDefaultPath() throws Exception {
145         HttpMethod simple = new FakeHttpMethod();
146         assertEquals("/", simple.getPath());
147 
148         simple.setPath("");
149         assertEquals("/", simple.getPath());
150 
151         simple.setPath(null);
152         assertEquals("/", simple.getPath());
153     }
154 
155     public void testHttpMethodBasePathConstructor() throws Exception {
156         HttpMethod simple = new FakeHttpMethod();
157         assertEquals("/", simple.getPath());
158 
159         simple = new FakeHttpMethod("");
160         assertEquals("/", simple.getPath());
161 
162         simple = new FakeHttpMethod("/some/path/");
163         assertEquals("/some/path/", simple.getPath());
164     }
165 
166     /** 
167      * Tests response with a Trasfer-Encoding and Content-Length 
168      */
169     public void testHttpMethodBaseTEandCL() throws Exception {
170         this.server.setHttpService(new SimpleChunkedService());
171         
172         GetMethod httpget = new GetMethod("/test/");
173         try {
174             this.client.executeMethod(httpget);
175             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
176             assertEquals("1234567890123", httpget.getResponseBodyAsString());
177             assertTrue(this.client.getHttpConnectionManager() instanceof SimpleHttpConnectionManager);
178             HttpConnection conn = this.client.getHttpConnectionManager().
179                 getConnection(this.client.getHostConfiguration());
180             assertNotNull(conn);
181             conn.assertNotOpen();
182         } finally {
183             httpget.releaseConnection();
184         }
185     }
186 
187     public void testConnectionAutoClose() throws Exception {
188         this.server.setHttpService(new ManyAService());
189         
190         GetMethod httpget = new GetMethod("/test/");
191         try {
192             this.client.executeMethod(httpget);
193             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
194             Reader response = new InputStreamReader(httpget.getResponseBodyAsStream());
195             int c;
196             while ((c = response.read()) != -1) {
197                assertEquals((int) 'A', c);
198             }
199             assertTrue(this.client.getHttpConnectionManager() instanceof SimpleHttpConnectionManager);
200             HttpConnection conn = this.client.getHttpConnectionManager().
201                 getConnection(this.client.getHostConfiguration());
202             assertNotNull(conn);
203             conn.assertNotOpen();
204         } finally {
205             httpget.releaseConnection();
206         }
207     }
208 
209     public void testSetGetQueryString1() {
210         HttpMethod method = new GetMethod();
211         String qs1 = "name1=value1&name2=value2";
212         method.setQueryString(qs1);
213         assertEquals(qs1, method.getQueryString());
214     }
215 
216     public void testQueryURIEncoding() {
217         HttpMethod method = new GetMethod("http://server/servlet?foo=bar&baz=schmoo");
218         assertEquals("foo=bar&baz=schmoo", method.getQueryString());
219     }
220 
221     public void testSetGetQueryString2() {
222         HttpMethod method = new GetMethod();
223         NameValuePair[] q1 = new NameValuePair[] {
224             new NameValuePair("name1", "value1"),
225             new NameValuePair("name2", "value2")
226         };
227         method.setQueryString(q1);
228         String qs1 = "name1=value1&name2=value2";
229         assertEquals(qs1, method.getQueryString());
230     }
231 
232     /**
233      * Make sure that its OK to call releaseConnection if the connection has not been.
234      */
235     public void testReleaseConnection() {
236         HttpMethod method = new GetMethod("http://bogus.url/path/");
237         method.releaseConnection();
238     }
239 
240     /** 
241      * Tests empty body response
242      */
243     public void testEmptyBodyAsString() throws Exception {
244         this.server.setHttpService(new EmptyResponseService());
245         
246         GetMethod httpget = new GetMethod("/test/");
247         try {
248             this.client.executeMethod(httpget);
249             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
250             String response = httpget.getResponseBodyAsString();
251             assertNull(response);
252 
253             this.client.executeMethod(httpget);
254             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
255             response = httpget.getResponseBodyAsString(1);
256             assertNull(response);
257         } finally {
258             httpget.releaseConnection();
259         }
260     }
261 
262 
263     public void testEmptyBodyAsByteArray() throws Exception {
264         this.server.setHttpService(new EmptyResponseService());
265         
266         GetMethod httpget = new GetMethod("/test/");
267         try {
268             this.client.executeMethod(httpget);
269             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
270             byte[] response = httpget.getResponseBody();
271             assertNull(response);
272         } finally {
273             httpget.releaseConnection();
274         }
275     }
276     
277     public void testLongBodyAsString() throws Exception {
278         this.server.setHttpService(new SimpleChunkedService());
279         
280         GetMethod httpget = new GetMethod("/test/");
281         try {
282             this.client.executeMethod(httpget);
283             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
284             try {
285                 httpget.getResponseBodyAsString(5); // too small
286             } catch(HttpContentTooLargeException e) {
287                 /* expected */
288                 assertEquals(5, e.getMaxLength());
289             }
290             
291             this.client.executeMethod(httpget);
292             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
293             String response = httpget.getResponseBodyAsString(13); // exact size
294             assertEquals("1234567890123", response);
295 
296             this.client.executeMethod(httpget);
297             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
298             response = httpget.getResponseBodyAsString(128); // plenty
299             assertEquals("1234567890123", response);
300         } finally {
301             httpget.releaseConnection();
302         }
303     }
304     
305     public void testUrlGetMethodWithPathQuery() {
306         GetMethod method = new GetMethod("http://www.fubar.com/path1/path2?query=string");
307         try {
308             assertEquals(
309                 "Get URL",
310                 "http://www.fubar.com/path1/path2?query=string",
311                 method.getURI().toString()
312             );
313         } catch ( URIException e ) {
314             fail( "trouble getting URI: " + e );
315         }
316         assertEquals("Get Path", "/path1/path2", method.getPath());
317         assertEquals("Get query string", "query=string", method.getQueryString());
318      
319     }
320 
321     public void testUrlGetMethodWithPath() {
322         GetMethod method = new GetMethod("http://www.fubar.com/path1/path2");
323         try {
324             assertEquals(
325                 "Get URL",
326                 "http://www.fubar.com/path1/path2",
327                 method.getURI().toString()
328             );
329         } catch ( URIException e ) {
330             fail( "trouble getting URI: " + e );
331         }
332         assertEquals("Get Path", "/path1/path2", method.getPath());
333         assertEquals("Get query string", null, method.getQueryString());
334     }
335 
336     public void testUrlGetMethod() {
337         GetMethod method = new GetMethod("http://www.fubar.com/");
338         try {
339             assertEquals(
340                 "Get URL",
341                 "http://www.fubar.com/",
342                 method.getURI().toString()
343             );
344         } catch ( URIException e ) {
345             fail( "trouble getting URI: " + e );
346         }
347         assertEquals("Get Path", "/", method.getPath());
348         assertEquals("Get query string", null, method.getQueryString());
349 
350     }
351     
352 
353     public void testUrlGetMethodWithInvalidProtocol() {
354         try {
355             GetMethod method = new GetMethod("crap://www.fubar.com/");
356             fail("The use of invalid protocol must have resulted in an IllegalStateException");
357         }
358         catch(IllegalStateException expected) {
359         }
360     }
361 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHttpParser.html100644 0 0 30650 10661532627 26723 0ustar 0 0 TestHttpParser xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttpParser.java,v 1.3 2004/02/22 18:08:49 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import java.io.ByteArrayInputStream;
35  import java.io.InputStream;
36  
37  import junit.framework.*;
38  
39  /**
40   * Simple tests for {@link HttpParser}.
41   *
42   * @author Oleg Kalnichevski
43   * @version $Id: TestHttpParser.java 480424 2006-11-29 05:56:49Z bayard $
44   */
45  public class TestHttpParser extends TestCase {
46  
47      private static final String HTTP_ELEMENT_CHARSET = "US-ASCII";
48  
49      // ------------------------------------------------------------ Constructor
50      public TestHttpParser(String testName) {
51          super(testName);
52      }
53  
54      // ------------------------------------------------------------------- Main
55      public static void main(String args[]) {
56          String[] testCaseName = { TestHeader.class.getName() };
57          junit.textui.TestRunner.main(testCaseName);
58      }
59  
60      // ------------------------------------------------------- TestCase Methods
61  
62      public static Test suite() {
63          return new TestSuite(TestHttpParser.class);
64      }
65  
66      public void testReadHttpLine() throws Exception {
67          InputStream instream = new ByteArrayInputStream(
68              "\r\r\nstuff\r\n".getBytes(HTTP_ELEMENT_CHARSET)); 
69          assertEquals("\r", HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET));
70          assertEquals("stuff", HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET));
71          assertEquals(null, HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET));
72  
73          instream = new ByteArrayInputStream(
74              "\n\r\nstuff\r\n".getBytes("US-ASCII")); 
75          assertEquals("", HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET));
76          assertEquals("", HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET));
77          assertEquals("stuff", HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET));
78          assertEquals(null, HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET));
79      }
80  
81      public void testReadWellFormedHttpHeaders() throws Exception {
82          InputStream instream = new ByteArrayInputStream(
83              "a: a\r\nb: b\r\n\r\nwhatever".getBytes(HTTP_ELEMENT_CHARSET));
84          Header[] headers = HttpParser.parseHeaders(instream, HTTP_ELEMENT_CHARSET);
85          assertNotNull(headers);
86          assertEquals(2, headers.length);
87          assertEquals("a", headers[0].getName());
88          assertEquals("a", headers[0].getValue());
89          assertEquals("b", headers[1].getName());
90          assertEquals("b", headers[1].getValue());
91      }
92      
93      public void testReadMalformedHttpHeaders() throws Exception {
94          InputStream instream = new ByteArrayInputStream(
95              "a: a\r\nb b\r\n\r\nwhatever".getBytes(HTTP_ELEMENT_CHARSET));
96          try {
97              Header[] headers = HttpParser.parseHeaders(instream, HTTP_ELEMENT_CHARSET);
98              fail("HttpException should have been thrown");
99          } catch (HttpException expected) {
100         }
101     }
102     
103     public void testHeadersTerminatorLeniency1() throws Exception {
104         InputStream instream = new ByteArrayInputStream(
105             "a: a\r\nb: b\r\n\r\r\nwhatever".getBytes(HTTP_ELEMENT_CHARSET));
106         Header[] headers = HttpParser.parseHeaders(instream, HTTP_ELEMENT_CHARSET);
107         assertNotNull(headers);
108         assertEquals(2, headers.length);
109         assertEquals("a", headers[0].getName());
110         assertEquals("a", headers[0].getValue());
111         assertEquals("b", headers[1].getName());
112         assertEquals("b", headers[1].getValue());
113     }
114     
115     public void testHeadersTerminatorLeniency2() throws Exception {
116         InputStream instream = new ByteArrayInputStream(
117             "a: a\r\nb: b\r\n    \r\nwhatever".getBytes(HTTP_ELEMENT_CHARSET));
118         Header[] headers = HttpParser.parseHeaders(instream, HTTP_ELEMENT_CHARSET);
119         assertNotNull(headers);
120         assertEquals(2, headers.length);
121         assertEquals("a", headers[0].getName());
122         assertEquals("a", headers[0].getValue());
123         assertEquals("b", headers[1].getName());
124         assertEquals("b", headers[1].getValue());
125     }
126 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHttpState.html100644 0 0 60335 10661532627 26552 0ustar 0 0 TestHttpState xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttpState.java,v 1.7 2004/06/23 06:50:25 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import org.apache.commons.httpclient.auth.AuthScope;
35  
36  import junit.framework.*;
37  
38  /**
39   * 
40   * Simple tests for {@link HttpState}.
41   *
42   * @author Rodney Waldhoff
43   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
44   * @author Sean C. Sullivan
45   * @author Oleg Kalnichevski
46   * 
47   * @version $Id: TestHttpState.java 480424 2006-11-29 05:56:49Z bayard $
48   * 
49   */
50  public class TestHttpState extends TestCase {
51  
52      public final static Credentials CREDS1 = 
53          new UsernamePasswordCredentials("user1", "pass1");
54      public final static Credentials CREDS2 = 
55          new UsernamePasswordCredentials("user2", "pass2");
56  
57      public final static AuthScope SCOPE1 = 
58          new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "realm1");
59      public final static AuthScope SCOPE2 = 
60          new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "realm2");
61      public final static AuthScope BOGUS = 
62          new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "bogus");
63      public final static AuthScope DEFSCOPE = 
64          new AuthScope("host", AuthScope.ANY_PORT, "realm");
65  
66  
67      // ------------------------------------------------------------ Constructor
68      public TestHttpState(String testName) {
69          super(testName);
70      }
71  
72      // ------------------------------------------------------------------- Main
73      public static void main(String args[]) {
74          String[] testCaseName = { TestHttpState.class.getName() };
75          junit.textui.TestRunner.main(testCaseName);
76      }
77  
78      // ------------------------------------------------------- TestCase Methods
79  
80      public static Test suite() {
81          return new TestSuite(TestHttpState.class);
82      }
83  
84  
85      // ----------------------------------------------------------- Test Methods
86  
87      public void testHttpStateCredentials() {
88          HttpState state = new HttpState();
89          state.setCredentials(SCOPE1, CREDS1);
90          state.setCredentials(SCOPE2, CREDS2);
91          assertEquals(CREDS1, state.getCredentials(SCOPE1));
92          assertEquals(CREDS2, state.getCredentials(SCOPE2));
93      }
94  
95  	public void testToString()
96  	{
97          HttpState state = new HttpState();
98          assertNotNull(state.toString());
99          
100         state.addCookie(new Cookie("foo", "bar", "yeah"));
101         assertNotNull(state.toString());
102 
103         state.addCookie(new Cookie("flub", "duck", "yuck"));
104         assertNotNull(state.toString());
105 
106 		state.setCredentials(SCOPE1, CREDS1);
107         assertNotNull(state.toString());
108         
109 		state.setProxyCredentials(SCOPE2, CREDS2);
110         assertNotNull(state.toString());
111 	}
112 
113     public void testHttpStateNoCredentials() {
114         HttpState state = new HttpState();
115         assertEquals(null, state.getCredentials(BOGUS));
116     }
117 
118     public void testHttpStateDefaultCredentials() {
119         HttpState state = new HttpState();
120 	    state.setCredentials(AuthScope.ANY, CREDS1);
121 	    state.setCredentials(SCOPE2, CREDS2);
122         assertEquals(CREDS1, state.getCredentials(BOGUS));
123     }
124 
125     public void testHttpStateProxyCredentials() {
126         HttpState state = new HttpState();
127         state.setProxyCredentials(SCOPE1, CREDS1);
128         state.setProxyCredentials(SCOPE2, CREDS2);
129         assertEquals(CREDS1, state.getProxyCredentials(SCOPE1));
130         assertEquals(CREDS2, state.getProxyCredentials(SCOPE2));
131     }
132 
133     public void testHttpStateProxyNoCredentials() {
134         HttpState state = new HttpState();
135         assertEquals(null, state.getProxyCredentials(BOGUS));
136     }
137 
138     public void testHttpStateProxyDefaultCredentials() {
139         HttpState state = new HttpState();
140 	    state.setProxyCredentials(AuthScope.ANY, CREDS1);
141 	    state.setProxyCredentials(SCOPE2, CREDS2);
142         assertEquals(CREDS1, state.getProxyCredentials(BOGUS));
143     }
144 
145     // --------------------------------- Test Methods for Selecting Credentials
146     
147     public void testDefaultCredentials() throws Exception {
148         HttpState state = new HttpState();
149         Credentials expected = new UsernamePasswordCredentials("name", "pass");
150         state.setCredentials(AuthScope.ANY, expected);
151         Credentials got = state.getCredentials(DEFSCOPE);
152         assertEquals(got, expected);
153     }
154     
155     public void testRealmCredentials() throws Exception {
156         HttpState state = new HttpState();
157         Credentials expected = new UsernamePasswordCredentials("name", "pass");
158         state.setCredentials(DEFSCOPE, expected);
159         Credentials got = state.getCredentials(DEFSCOPE);
160         assertEquals(expected, got);
161     }
162     
163     public void testHostCredentials() throws Exception {
164         HttpState state = new HttpState();
165         Credentials expected = new UsernamePasswordCredentials("name", "pass");
166         state.setCredentials(
167             new AuthScope("host", AuthScope.ANY_PORT, AuthScope.ANY_REALM), expected);
168         Credentials got = state.getCredentials(DEFSCOPE);
169         assertEquals(expected, got);
170     }
171     
172     public void testWrongHostCredentials() throws Exception {
173         HttpState state = new HttpState();
174         Credentials expected = new UsernamePasswordCredentials("name", "pass");
175         state.setCredentials(
176             new AuthScope("host1", AuthScope.ANY_PORT, "realm"), expected);
177         Credentials got = state.getCredentials(
178             new AuthScope("host2", AuthScope.ANY_PORT, "realm"));
179         assertNotSame(expected, got);
180     }
181     
182     public void testWrongRealmCredentials() throws Exception {
183         HttpState state = new HttpState();
184         Credentials cred = new UsernamePasswordCredentials("name", "pass");
185         state.setCredentials(
186             new AuthScope("host", AuthScope.ANY_PORT, "realm1"), cred);
187         Credentials got = state.getCredentials(
188             new AuthScope("host", AuthScope.ANY_PORT, "realm2"));
189         assertNotSame(cred, got);
190     }
191 
192     // ------------------------------- Test Methods for matching Credentials
193     
194     public void testScopeMatching() {
195         AuthScope authscope1 = new AuthScope("somehost", 80, "somerealm", "somescheme");
196         AuthScope authscope2 = new AuthScope("someotherhost", 80, "somerealm", "somescheme");
197         assertTrue(authscope1.match(authscope2) < 0);
198 
199         int m1 = authscope1.match(
200             new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "somescheme"));
201         int m2 = authscope1.match(
202             new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "somerealm", AuthScope.ANY_SCHEME));
203         assertTrue(m2 > m1);
204 
205         m1 = authscope1.match(
206             new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "somescheme"));
207         m2 = authscope1.match(
208             new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "somerealm", AuthScope.ANY_SCHEME));
209         assertTrue(m2 > m1);
210 
211         m1 = authscope1.match(
212             new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "somerealm", "somescheme"));
213         m2 = authscope1.match(
214             new AuthScope(AuthScope.ANY_HOST, 80, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME));
215         assertTrue(m2 > m1);
216 
217         m1 = authscope1.match(
218             new AuthScope(AuthScope.ANY_HOST, 80, "somerealm", "somescheme"));
219         m2 = authscope1.match(
220             new AuthScope("somehost", AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME));
221         assertTrue(m2 > m1);
222 
223         m1 = authscope1.match(AuthScope.ANY);
224         m2 = authscope1.match(
225             new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "somescheme"));
226         assertTrue(m2 > m1);
227     }
228     
229     public void testCredentialsMatching() {
230         Credentials creds1 = new UsernamePasswordCredentials("name1", "pass1");
231         Credentials creds2 = new UsernamePasswordCredentials("name2", "pass2");
232         Credentials creds3 = new UsernamePasswordCredentials("name3", "pass3");
233         
234         AuthScope scope1 = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
235         AuthScope scope2 = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "somerealm");
236         AuthScope scope3 = new AuthScope("somehost", AuthScope.ANY_PORT, AuthScope.ANY_REALM);
237         
238         HttpState state = new HttpState();
239         state.setCredentials(scope1, creds1);
240         state.setCredentials(scope2, creds2);
241         state.setCredentials(scope3, creds3);
242 
243         Credentials got = state.getCredentials(
244             new AuthScope("someotherhost", 80, "someotherrealm", "basic"));
245         Credentials expected = creds1;
246         assertEquals(expected, got);
247 
248         got = state.getCredentials(
249             new AuthScope("someotherhost", 80, "somerealm", "basic"));
250         expected = creds2;
251         assertEquals(expected, got);
252 
253         got = state.getCredentials(
254             new AuthScope("somehost", 80, "someotherrealm", "basic"));
255         expected = creds3;
256         assertEquals(expected, got);
257     }
258 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHttpStatus.html100644 0 0 22672 10661532627 26757 0ustar 0 0 TestHttpStatus xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttpStatus.java,v 1.4 2004/05/02 11:21:13 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import junit.framework.*;
35  import java.lang.reflect.*;
36  
37  /**
38   *
39   * Unit tests for {@link HttpStatus}
40   *
41   * @author Sean C. Sullivan
42   * @version $Id: TestHttpStatus.java 480424 2006-11-29 05:56:49Z bayard $
43   */
44  public class TestHttpStatus extends TestCase {
45  
46      // ------------------------------------------------------------ Constructor
47      public TestHttpStatus(String testName) {
48          super(testName);
49      }
50  
51      // ------------------------------------------------------------------- Main
52      public static void main(String args[]) {
53          String[] testCaseName = { TestHttpStatus.class.getName() };
54          junit.textui.TestRunner.main(testCaseName);
55      }
56  
57      // ------------------------------------------------------- TestCase Methods
58  
59      public static Test suite() {
60          return new TestSuite(TestHttpStatus.class);
61      }
62  
63  
64      // ----------------------------------------------------------- Test Methods
65  
66      public void testStatusText() throws IllegalAccessException {
67  	Field[] publicFields = HttpStatus.class.getFields();
68  
69  	assertTrue( publicFields != null );
70  
71  	assertTrue( publicFields.length > 0 );
72  
73  	for (int i = 0; i < publicFields.length; i++)
74  	{
75  		final Field f = publicFields[i];
76  
77  		final int modifiers = f.getModifiers();
78  
79  		if ( (f.getType() == int.class)
80  			&& Modifier.isPublic(modifiers)
81  			&& Modifier.isFinal(modifiers)
82  			&& Modifier.isStatic(modifiers) )
83  		{
84  			final int iValue = f.getInt(null);
85  			final String text = HttpStatus.getStatusText(iValue);
86  
87  			assertTrue( "text is null for HttpStatus." + f.getName(), 
88  				(text != null) );
89  
90  			assertTrue( text.length() > 0 );
91  		}
92  	}
93  
94      }
95  
96      public void testStatusTextNegative() throws Exception {
97          try {
98              HttpStatus.getStatusText(-1);
99              fail("IllegalArgumentException must have been thrown");
100         } catch (IllegalArgumentException expected) {
101         }
102     }
103 
104     public void testStatusTextAll() throws Exception {
105         for (int i = 0; i < 600; i++) {
106             HttpStatus.getStatusText(i);
107         }
108     }
109 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHttpVersion.html100644 0 0 40351 10661532627 27113 0ustar 0 0 TestHttpVersion xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttpVersion.java,v 1.3 2004/05/09 12:16:12 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import junit.framework.Test;
35  import junit.framework.TestCase;
36  import junit.framework.TestSuite;
37  
38  /**
39   * Test cases for HTTP version class
40   *
41   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
42   * 
43   * @version $Revision: 480424 $
44   */
45  public class TestHttpVersion extends TestCase {
46  
47      // ------------------------------------------------------------ Constructor
48  
49      public TestHttpVersion(String name) {
50          super(name);
51      }
52  
53      // ------------------------------------------------------- TestCase Methods
54  
55      public static Test suite() {
56          return new TestSuite(TestHttpVersion.class);
57      }
58  
59      // ------------------------------------------------------------------ Tests
60      
61      public void testHttpVersionInvalidConstructorInput() throws Exception {
62          try {
63              HttpVersion ver = new HttpVersion(-1, -1); 
64              fail("IllegalArgumentException should have been thrown");
65          } catch (IllegalArgumentException e) {
66              // expected
67          }
68          try {
69              HttpVersion ver = new HttpVersion(0, -1); 
70              fail("IllegalArgumentException should have been thrown");
71          } catch (IllegalArgumentException e) {
72              // expected
73          }
74      }
75  
76      public void testHttpVersionParsing() throws Exception {
77          String s = "HTTP/1.1";
78          HttpVersion version = HttpVersion.parse(s);
79          assertEquals("HTTP major version number", 1, version.getMajor());
80          assertEquals("HTTP minor version number", 1, version.getMinor());
81          assertEquals("HTTP version number", s, version.toString());
82  
83          s = "HTTP/123.4567";
84          version = HttpVersion.parse(s);
85          assertEquals("HTTP major version number", 123, version.getMajor());
86          assertEquals("HTTP minor version number", 4567, version.getMinor());
87          assertEquals("HTTP version number", s, version.toString());
88      }
89  
90      public void testInvalidHttpVersionParsing() throws Exception {
91          try {
92              HttpVersion.parse(null);
93              fail("IllegalArgumentException should have been thrown");
94          } catch (IllegalArgumentException e) {
95              //expected
96          }
97          try {
98              HttpVersion.parse("crap");
99              fail("ProtocolException should have been thrown");
100         } catch (ProtocolException e) {
101             //expected
102         }
103         try {
104             HttpVersion.parse("HTTP/crap");
105             fail("ProtocolException should have been thrown");
106         } catch (ProtocolException e) {
107             //expected
108         }
109         try {
110             HttpVersion.parse("HTTP/1");
111             fail("ProtocolException should have been thrown");
112         } catch (ProtocolException e) {
113             //expected
114         }
115         try {
116             HttpVersion.parse("HTTP/1234   ");
117             fail("ProtocolException should have been thrown");
118         } catch (ProtocolException e) {
119             //expected
120         }
121         try {
122             HttpVersion.parse("HTTP/1.");
123             fail("ProtocolException should have been thrown");
124         } catch (ProtocolException e) {
125             //expected
126         }
127         try {
128             HttpVersion.parse("HTTP/1.1 crap");
129             fail("ProtocolException should have been thrown");
130         } catch (ProtocolException e) {
131             //expected
132         }
133         try {
134             HttpVersion.parse("HTTP/whatever.whatever whatever");
135             fail("ProtocolException should have been thrown");
136         } catch (ProtocolException e) {
137             //expected
138         }
139         try {
140             HttpVersion.parse("HTTP/1.whatever whatever");
141             fail("ProtocolException should have been thrown");
142         } catch (ProtocolException e) {
143             //expected
144         }
145     }
146 
147     public void testHttpVersionEquality() throws Exception {
148         HttpVersion ver1 = new HttpVersion(1, 1); 
149         HttpVersion ver2 = new HttpVersion(1, 1); 
150         
151         assertEquals(ver1.hashCode(), ver2.hashCode());
152         assertTrue(ver1.equals(ver1));
153         assertTrue(ver1.equals(ver2));
154         assertTrue(ver1.equals((Object)ver1));
155         assertTrue(ver1.equals((Object)ver2));
156 
157         assertFalse(ver1.equals(new Float(1.1)));
158         
159         try {
160             ver1.equals(null);
161             fail("IllegalArgumentException should have been thrown");
162         } catch (IllegalArgumentException e) {
163         }
164 
165         assertTrue((new HttpVersion(0, 9)).equals(HttpVersion.HTTP_0_9));
166         assertTrue((new HttpVersion(1, 0)).equals(HttpVersion.HTTP_1_0));
167         assertTrue((new HttpVersion(1, 1)).equals(HttpVersion.HTTP_1_1));
168         assertFalse((new HttpVersion(1, 1)).equals(HttpVersion.HTTP_1_0));
169     }
170 
171     public void testHttpVersionComparison() {
172         assertTrue(HttpVersion.HTTP_0_9.lessEquals(HttpVersion.HTTP_1_1));
173         assertTrue(HttpVersion.HTTP_0_9.greaterEquals(HttpVersion.HTTP_0_9));
174         assertFalse(HttpVersion.HTTP_0_9.greaterEquals(HttpVersion.HTTP_1_0));
175         
176         assertTrue(HttpVersion.HTTP_1_0.compareTo((Object)HttpVersion.HTTP_1_1) < 0);
177         assertTrue(HttpVersion.HTTP_1_0.compareTo((Object)HttpVersion.HTTP_0_9) > 0);
178         assertTrue(HttpVersion.HTTP_1_0.compareTo((Object)HttpVersion.HTTP_1_0) == 0);
179    }
180 }
181 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestHttps.html100644 0 0 32340 10661532627 25727 0ustar 0 0 TestHttps xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttps.java,v 1.12 2004/06/13 12:13:08 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import junit.framework.Test;
35  import junit.framework.TestCase;
36  import junit.framework.TestSuite;
37  
38  import org.apache.commons.httpclient.auth.AuthScope;
39  import org.apache.commons.httpclient.methods.GetMethod;
40  
41  /**
42   * Simple tests for HTTPS support in HttpClient.
43   *
44   * To run this test you'll need:
45   *  + a JSSE implementation installed (see README.txt)
46   *  + the java.protocol.handler.pkgs system property set
47   *    for your provider.  e.g.:
48   *     -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol
49   *    (see build.xml)
50   *
51   * @author Rodney Waldhoff
52   * @author Ortwin Gl?ck
53   * @version $Id: TestHttps.java 480424 2006-11-29 05:56:49Z bayard $
54   */
55  public class TestHttps extends TestCase {
56  
57      // ---------------------------------------------------------------- Members
58      private String _urlWithPort = null;
59      private String _urlWithoutPort = null;
60      private final String PROXY_HOST = System.getProperty("httpclient.test.proxyHost");
61      private final String PROXY_PORT = System.getProperty("httpclient.test.proxyPort");
62      private final String PROXY_USER = System.getProperty("httpclient.test.proxyUser");
63      private final String PROXY_PASS = System.getProperty("httpclient.test.proxyPass");
64  
65      // ------------------------------------------------------------ Constructor
66      public TestHttps(String testName) {
67          super(testName);
68      }
69  
70      // ------------------------------------------------------------------- Main
71      public static void main(String args[]) {
72          String[] testCaseName = { TestHttps.class.getName() };
73          junit.textui.TestRunner.main(testCaseName);
74      }
75  
76      // ------------------------------------------------------- TestCase Methods
77      public static Test suite() {
78          return new TestSuite(TestHttps.class);
79      }
80  
81      public void setUp() throws Exception {
82          _urlWithPort = "https://www.verisign.com:443/";
83          _urlWithoutPort = "https://www.verisign.com/";
84      }
85  
86      public void testHttpsGet() {
87          HttpClient client = new HttpClient();
88          if (PROXY_HOST != null) {
89              if (PROXY_USER != null) {
90                  HttpState state = client.getState();
91                  state.setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
92                      PROXY_USER, PROXY_PASS));
93              }
94              client.getHostConfiguration().setProxy(PROXY_HOST, Integer.parseInt(PROXY_PORT));
95          }
96          GetMethod method = new GetMethod(_urlWithPort);
97          
98          try {
99              client.executeMethod(method);
100         } catch (Throwable t) {
101             t.printStackTrace();
102             fail("Exception thrown during HTTPS GET: " + t.toString());
103         }
104 
105         try {
106             String data = method.getResponseBodyAsString();
107             // This enumeration musn't be empty
108             assertTrue("No data returned.", (data.length() > 0));
109         } catch (Throwable t) {
110             t.printStackTrace();
111             fail("Exception thrown while retrieving data : " + t.toString());
112         }
113     }
114 
115     public void testHttpsGetNoPort() {
116         HttpClient client = new HttpClient();
117         if (PROXY_HOST != null) {
118             if (PROXY_USER != null) {
119                 HttpState state = client.getState();
120                 state.setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
121                     PROXY_USER, PROXY_PASS));
122             }
123             client.getHostConfiguration().setProxy(PROXY_HOST, Integer.parseInt(PROXY_PORT));
124         }
125         GetMethod method = new GetMethod(_urlWithoutPort);
126         
127         try {
128             client.executeMethod(method);
129         } catch (Throwable t) {
130             t.printStackTrace();
131             fail("Exception thrown during HTTPS GET: " + t.toString());
132         }
133 
134         try {
135             String data = method.getResponseBodyAsString();
136             // This enumeration musn't be empty
137             assertTrue("No data returned.", (data.length() > 0));
138         } catch (Throwable t) {
139             t.printStackTrace();
140             fail("Exception thrown while retrieving data : " + t.toString());
141         }
142     }
143 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestIdleConnectionTimeout.html100644 0 0 40457 10661532627 31101 0ustar 0 0 TestIdleConnectionTimeout xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestIdleConnectionTimeout.java,v 1.5 2004/11/07 12:31:42 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient;
31  
32  import junit.framework.Test;
33  import junit.framework.TestCase;
34  import junit.framework.TestSuite;
35  
36  import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
37  import org.apache.commons.httpclient.util.IdleConnectionHandler;
38  import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread;
39  
40  /**
41   */
42  public class TestIdleConnectionTimeout extends TestCase {
43      /**
44       * 
45       */
46      public TestIdleConnectionTimeout() {
47          super();
48      }
49      /**
50       * @param arg0
51       */
52      public TestIdleConnectionTimeout(String arg0) {
53          super(arg0);
54      }
55      
56      // ------------------------------------------------------- TestCase Methods
57  
58      public static Test suite() {
59          return new TestSuite(TestIdleConnectionTimeout.class);
60      }
61  
62      /**
63       * Tests that the IdleConnectionHandler correctly closes connections.
64       */
65      public void testHandler() {
66          
67          TimeoutHttpConnection connection = new TimeoutHttpConnection();
68          
69          IdleConnectionHandler handler = new IdleConnectionHandler();
70          
71          handler.add(connection);
72          
73          synchronized(this) {
74              try {
75                  this.wait(250);
76              } catch (InterruptedException e) {
77                  e.printStackTrace();
78              }
79          }
80          
81          handler.closeIdleConnections(100);
82          
83          assertTrue("Connection not closed", connection.isClosed());
84  
85          connection.setClosed(false);
86          
87          handler.remove(connection);
88          
89          synchronized(this) {
90              try {
91                  this.wait(250);
92              } catch (InterruptedException e) {
93                  e.printStackTrace();
94              }
95          }
96  
97          handler.closeIdleConnections(100);
98          
99          assertFalse("Connection closed", connection.isClosed());
100     }
101 
102     /**
103      * Tests that the IdleConnectionTimeoutThread works correctly.
104      */
105     public void testTimeoutThread() {
106         
107         TimeoutHttpConnectionManager cm = new TimeoutHttpConnectionManager();        
108         
109         IdleConnectionTimeoutThread timeoutThread = new IdleConnectionTimeoutThread();
110         timeoutThread.addConnectionManager(cm);
111         timeoutThread.setTimeoutInterval(100);
112         timeoutThread.start();
113         
114         synchronized(this) {
115             try {
116                 this.wait(250);
117             } catch (InterruptedException e) {
118                 e.printStackTrace();
119             }
120         }
121         
122         assertTrue("closeIdleConnections() not called", cm.closed);
123 
124         timeoutThread.removeConnectionManager(cm);
125         cm.closed = false;
126         
127         synchronized(this) {
128             try {
129                 this.wait(250);
130             } catch (InterruptedException e) {
131                 e.printStackTrace();
132             }
133         }
134 
135         assertFalse("closeIdleConnections() called", cm.closed);
136         
137         timeoutThread.shutdown();
138     }    
139     
140     private static class TimeoutHttpConnectionManager implements HttpConnectionManager {
141         
142         public boolean closed = false;
143         
144         public void closeIdleConnections(long idleTimeout) {
145             this.closed = true;
146         }
147 
148         /**
149          * @deprecated
150          */
151         public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout)
152             throws HttpException {
153             return null;
154         }
155 
156         public HttpConnection getConnection(HostConfiguration hostConfiguration) {
157             return null;
158         }
159 
160         public HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration,
161             long timeout) throws ConnectionPoolTimeoutException {
162             return null;
163         }
164 
165         public HttpConnectionManagerParams getParams() {
166             return null;
167         }
168 
169         public void releaseConnection(HttpConnection conn) {
170         }
171 
172         public void setParams(HttpConnectionManagerParams params) {
173         }
174 }
175     
176     private static class TimeoutHttpConnection extends HttpConnection {
177         
178         private boolean closed = false;;
179         
180         public TimeoutHttpConnection() {
181             super("fake-host", 80);
182         }
183         
184         /**
185          * @return Returns the closed.
186          */
187         public boolean isClosed() {
188             return closed;
189         }
190         /**
191          * @param closed The closed to set.
192          */
193         public void setClosed(boolean closed) {
194             this.closed = closed;
195         }
196         
197         /* (non-Javadoc)
198          * @see org.apache.commons.httpclient.HttpConnection#close()
199          */
200         public void close() {
201             closed = true;
202         }
203     }
204     
205 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestMethodAbort.html100644 0 0 32771 10661532627 27045 0ustar 0 0 TestMethodAbort xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestMethodAbort.java,v 1.3 2004/10/31 14:42:59 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  import java.io.BufferedReader;
34  import java.io.IOException;
35  import java.io.InputStreamReader;
36  
37  import junit.framework.Test;
38  import junit.framework.TestSuite;
39  
40  import org.apache.commons.httpclient.methods.GetMethod;
41  import org.apache.commons.httpclient.server.HttpRequestHandler;
42  import org.apache.commons.httpclient.server.ResponseWriter;
43  import org.apache.commons.httpclient.server.SimpleHttpServerConnection;
44  import org.apache.commons.httpclient.server.SimpleRequest;
45  
46  /**
47   * Tests ability to abort method execution.
48   *
49   * @author Oleg Kalnichevski
50   * 
51   * @version $Revision: 480424 $
52   */
53  public class TestMethodAbort extends HttpClientTestBase {
54  
55      // ------------------------------------------------------------ Constructor
56      public TestMethodAbort(final String testName) throws IOException {
57          super(testName);
58      }
59  
60      // ------------------------------------------------------------------- Main
61      public static void main(String args[]) {
62          String[] testCaseName = { TestMethodAbort.class.getName() };
63          junit.textui.TestRunner.main(testCaseName);
64      }
65  
66      // ------------------------------------------------------- TestCase Methods
67  
68      public static Test suite() {
69          return new TestSuite(TestMethodAbort.class);
70      }
71  
72      private class ProduceGarbageHandler implements HttpRequestHandler {
73  
74          public ProduceGarbageHandler() {
75              super();
76          }
77  
78          public boolean processRequest(
79              final SimpleHttpServerConnection conn,
80              final SimpleRequest request) throws IOException
81          {
82  
83              final String garbage = "garbage!\r\n";  
84              final long count = 1000000000;  
85  
86              HttpVersion httpversion = request.getRequestLine().getHttpVersion();
87              ResponseWriter out = conn.getWriter();
88              out.println(httpversion + " 200 OK");
89              out.println("Content-Type: text/plain");
90              out.println("Content-Length: " + count * garbage.length()) ;
91              out.println("Connection: close");
92              out.println();
93              for (int i = 0; i < count; i++) {
94                  out.print(garbage);
95              }
96              return true;
97          }
98      }
99  
100     public void testAbortMethod() throws IOException {
101         this.server.setRequestHandler(new ProduceGarbageHandler());
102         final GetMethod httpget = new GetMethod("/test/");
103         
104         Thread thread = new Thread(new Runnable() {
105             public void run() {            
106                 try {
107                     Thread.sleep(500);
108                 } catch (InterruptedException e) {
109                 }
110                 httpget.abort();
111             }
112             
113         });
114         thread.setDaemon(true); 
115         thread.start();
116         
117         try {
118             this.client.executeMethod(httpget);
119             BufferedReader in = new BufferedReader(new InputStreamReader(
120                 httpget.getResponseBodyAsStream()));
121             String line = null;
122             while ((line = in.readLine()) != null) {  
123             }
124             fail("IOException must have been thrown");
125         } catch (IOException e) {
126             // expected
127         } finally {
128             httpget.releaseConnection();
129         }
130         assertTrue(httpget.isAborted());
131     }
132 
133     public void testAbortedMethodExecute() throws IOException {
134         final GetMethod httpget = new GetMethod("/test/");
135         
136         try {
137             httpget.abort();
138             try {
139                 this.client.executeMethod(httpget);
140                 fail("IllegalStateException must have been thrown");
141             } catch (IllegalStateException e) {
142             }
143         } finally {
144             httpget.releaseConnection();
145         }
146         assertTrue(httpget.isAborted());
147     }
148 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestMethodCharEncoding.html100644 0 0 62303 10661532627 30314 0ustar 0 0 TestMethodCharEncoding xref

1   /*
2    * ====================================================================
3    *
4    *  Licensed to the Apache Software Foundation (ASF) under one or more
5    *  contributor license agreements.  See the NOTICE file distributed with
6    *  this work for additional information regarding copyright ownership.
7    *  The ASF licenses this file to You under the Apache License, Version 2.0
8    *  (the "License"); you may not use this file except in compliance with
9    *  the License.  You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   *  Unless required by applicable law or agreed to in writing, software
14   *  distributed under the License is distributed on an "AS IS" BASIS,
15   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   *  See the License for the specific language governing permissions and
17   *  limitations under the License.
18   * ====================================================================
19   *
20   * This software consists of voluntary contributions made by many
21   * individuals on behalf of the Apache Software Foundation.  For more
22   * information on the Apache Software Foundation, please see
23   * <http://www.apache.org/>.
24   *
25   * [Additional notices, if required by prior licensing conditions]
26   *
27   */
28  
29  package org.apache.commons.httpclient;
30  
31  import junit.framework.Test;
32  import junit.framework.TestSuite;
33  
34  import java.io.ByteArrayInputStream;
35  import java.io.ByteArrayOutputStream;
36  import java.io.IOException;
37  import java.io.InputStream;
38  import java.util.HashMap;
39  import java.util.Map;
40  import java.util.StringTokenizer;
41  
42  import org.apache.commons.httpclient.methods.GetMethod;
43  import org.apache.commons.httpclient.methods.PostMethod;
44  import org.apache.commons.httpclient.methods.RequestEntity;
45  import org.apache.commons.httpclient.methods.StringRequestEntity;
46  import org.apache.commons.httpclient.util.URIUtil;
47  
48  /**
49   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
50   * @author <a href="mailto:ajmas@bigfoot.com">Andre John Mas</a>
51   * @author <a href="mailto:laura@lwerner.org">Laura Werner</a>
52   */
53  
54  public class TestMethodCharEncoding extends HttpClientTestBase {
55  
56      static final String CHARSET_DEFAULT = "ISO-8859-1";
57      static final String CHARSET_ASCII = "US-ASCII";
58      static final String CHARSET_UTF8 = "UTF-8";
59      static final String CHARSET_KOI8_R = "KOI8_R";
60      static final String CHARSET_WIN1251 = "Cp1251";
61  
62      static final int SWISS_GERMAN_STUFF_UNICODE [] = {
63          0x47, 0x72, 0xFC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xE4, 0x6D, 0xE4
64      };
65      
66      static final int SWISS_GERMAN_STUFF_ISO8859_1 [] = {
67          0x47, 0x72, 0xFC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xE4, 0x6D, 0xE4
68      };
69      
70      static final int SWISS_GERMAN_STUFF_UTF8 [] = {
71          0x47, 0x72, 0xC3, 0xBC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xC3, 0xA4,
72          0x6D, 0xC3, 0xA4
73      };
74  
75      static final int RUSSIAN_STUFF_UNICODE [] = {
76          0x412, 0x441, 0x435, 0x43C, 0x5F, 0x43F, 0x440, 0x438, 
77          0x432, 0x435, 0x442 
78      }; 
79  
80      static final int RUSSIAN_STUFF_UTF8 [] = {
81          0xD0, 0x92, 0xD1, 0x81, 0xD0, 0xB5, 0xD0, 0xBC, 0x5F, 
82          0xD0, 0xBF, 0xD1, 0x80, 0xD0, 0xB8, 0xD0, 0xB2, 0xD0, 
83          0xB5, 0xD1, 0x82
84      };
85  
86      static final int RUSSIAN_STUFF_KOI8R [] = {
87          0xF7, 0xD3, 0xC5, 0xCD, 0x5F, 0xD0, 0xD2, 0xC9, 0xD7, 
88          0xC5, 0xD4
89      };
90  
91      static final int RUSSIAN_STUFF_WIN1251 [] = {
92          0xC2, 0xF1, 0xE5, 0xEC, 0x5F, 0xEF, 0xF0, 0xE8, 0xE2, 
93          0xE5, 0xF2
94      };
95  
96      // ------------------------------------------------------------ Constructor
97  
98      public TestMethodCharEncoding(final String testName) throws IOException {
99          super(testName);
100     }
101 
102     // ------------------------------------------------------- TestCase Methods
103 
104     public static Test suite() {
105         return new TestSuite(TestMethodCharEncoding.class);
106     }
107 
108     // ----------------------------------------------------------------- Tests
109 
110 
111     public void testRequestCharEncoding() throws IOException {
112         
113         GetMethod httpget = new GetMethod("/");
114         assertEquals(CHARSET_DEFAULT, httpget.getRequestCharSet());
115         httpget.setRequestHeader("Content-Type", "text/plain; charset=" + CHARSET_ASCII); 
116         assertEquals(CHARSET_ASCII, httpget.getRequestCharSet());
117         httpget.setRequestHeader("Content-Type", "text/plain; charset=" + CHARSET_UTF8); 
118         assertEquals(CHARSET_UTF8, httpget.getRequestCharSet());
119         
120     }
121 
122     public void testNoExplicitCharEncoding() throws Exception {
123         this.server.setHttpService(new EchoService());
124         
125         GetMethod httpget = new GetMethod("/test/");
126         httpget.setRequestHeader("Content-Type", "text/plain"); 
127         try {
128             this.client.executeMethod(httpget);
129             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
130             assertEquals(CHARSET_DEFAULT, httpget.getResponseCharSet());
131         } finally {
132             httpget.releaseConnection();
133         }
134     }
135 
136     public void testExplicitCharEncoding() throws Exception {
137         this.server.setHttpService(new EchoService());
138         
139         GetMethod httpget = new GetMethod("/test/");
140         httpget.setRequestHeader("Content-Type", "text/plain; charset=" + CHARSET_UTF8); 
141         try {
142             this.client.executeMethod(httpget);
143             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
144             assertEquals(CHARSET_UTF8, httpget.getResponseCharSet());
145         } finally {
146             httpget.releaseConnection();
147         }
148     }
149 
150     private String constructString(int [] unicodeChars) {
151         StringBuffer buffer = new StringBuffer();
152         if (unicodeChars != null) {
153             for (int i = 0; i < unicodeChars.length; i++) {
154                 buffer.append((char)unicodeChars[i]); 
155             }
156         }
157         return buffer.toString();
158     }
159 
160 
161     private void verifyEncoding(RequestEntity entity, int[] sample)
162      throws IOException  {
163         
164         assertNotNull("Request body", entity);
165 
166         ByteArrayOutputStream bos = new ByteArrayOutputStream();
167         entity.writeRequest(bos);
168         
169         InputStream instream = new ByteArrayInputStream(bos.toByteArray());
170         for (int i = 0; i < sample.length; i++) {
171             int b = instream.read();
172             assertTrue("Unexpected end of stream", b != -1);
173             if (sample[i] != b) {
174                 fail("Invalid request body encoding");
175             }
176         }
177         assertTrue("End of stream expected", instream.read() == -1);
178     }
179     
180     public void testLatinAccentInRequestBody() throws IOException {
181         PostMethod httppost = new PostMethod("/");
182         String s = constructString(SWISS_GERMAN_STUFF_UNICODE);
183         // Test default encoding ISO-8859-1
184         httppost.setRequestEntity(
185             new StringRequestEntity(s, "text/plain", CHARSET_DEFAULT));
186         verifyEncoding(httppost.getRequestEntity(), SWISS_GERMAN_STUFF_ISO8859_1);
187         // Test UTF-8 encoding
188         httppost.setRequestEntity(
189             new StringRequestEntity(s, "text/plain", CHARSET_UTF8));
190         verifyEncoding(httppost.getRequestEntity(), SWISS_GERMAN_STUFF_UTF8);
191 
192     }
193     
194     public void testRussianInRequestBody() throws IOException {
195         PostMethod httppost = new PostMethod("/");
196         String s = constructString(RUSSIAN_STUFF_UNICODE);
197         // Test UTF-8 encoding
198         httppost.setRequestEntity(
199             new StringRequestEntity(s, "text/plain", CHARSET_UTF8));
200         verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_UTF8);
201         // Test KOI8-R
202         httppost.setRequestEntity(
203             new StringRequestEntity(s, "text/plain", CHARSET_KOI8_R));
204         verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_KOI8R);
205         // Test WIN1251
206         httppost.setRequestEntity(
207             new StringRequestEntity(s, "text/plain", CHARSET_WIN1251));
208         verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_WIN1251);
209     }
210 
211     public void testQueryParams() throws Exception {
212 
213         GetMethod get = new GetMethod("/");
214 
215         String ru_msg = constructString(RUSSIAN_STUFF_UNICODE); 
216         String ch_msg = constructString(SWISS_GERMAN_STUFF_UNICODE); 
217 
218         get.setQueryString(new NameValuePair[] {
219             new NameValuePair("ru", ru_msg),
220             new NameValuePair("ch", ch_msg) 
221         });            
222 
223         Map params = new HashMap();
224         StringTokenizer tokenizer = new StringTokenizer(
225             get.getQueryString(), "&");
226         while (tokenizer.hasMoreTokens()) {
227             String s = tokenizer.nextToken();
228             int i = s.indexOf('=');
229             assertTrue("Invalid url-encoded parameters", i != -1);
230             String name = s.substring(0, i).trim(); 
231             String value = s.substring(i + 1, s.length()).trim(); 
232             value = URIUtil.decode(value, CHARSET_UTF8);
233             params.put(name, value);
234         }
235         assertEquals(ru_msg, params.get("ru"));
236         assertEquals(ch_msg, params.get("ch"));
237     }
238 
239     public void testUrlEncodedRequestBody() throws Exception {
240 
241         PostMethod httppost = new PostMethod("/");
242 
243         String ru_msg = constructString(RUSSIAN_STUFF_UNICODE); 
244         String ch_msg = constructString(SWISS_GERMAN_STUFF_UNICODE); 
245 
246         httppost.setRequestBody(new NameValuePair[] {
247             new NameValuePair("ru", ru_msg),
248             new NameValuePair("ch", ch_msg) 
249         });            
250 
251         httppost.setRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE 
252             + "; charset=" + CHARSET_UTF8);
253 
254         ByteArrayOutputStream bos = new ByteArrayOutputStream();
255         httppost.getRequestEntity().writeRequest(bos);
256         
257         Map params = new HashMap();
258         StringTokenizer tokenizer = new StringTokenizer(
259             new String(bos.toByteArray(), CHARSET_UTF8), "&");
260         while (tokenizer.hasMoreTokens()) {
261             String s = tokenizer.nextToken();
262             int i = s.indexOf('=');
263             assertTrue("Invalid url-encoded parameters", i != -1);
264             String name = s.substring(0, i).trim(); 
265             String value = s.substring(i + 1, s.length()).trim(); 
266             value = URIUtil.decode(value, CHARSET_UTF8);
267             params.put(name, value);
268         }
269         assertEquals(ru_msg, params.get("ru"));
270         assertEquals(ch_msg, params.get("ch"));
271     }
272     
273     public void testRequestEntityLength() throws IOException {
274         String s = constructString(SWISS_GERMAN_STUFF_UNICODE);
275         RequestEntity requestentity =
276             new StringRequestEntity(s, "text/plain", CHARSET_UTF8);
277         assertEquals(
278                 s.getBytes(CHARSET_UTF8).length, 
279                 requestentity.getContentLength()); 
280     }
281     
282 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestMultipartPost.html100644 0 0 40433 10661532627 27456 0ustar 0 0 TestMultipartPost xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestMultipartPost.java,v 1.3 2004/11/01 02:21:15 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32  
33  package org.apache.commons.httpclient;
34  
35  import java.io.ByteArrayInputStream;
36  import java.io.IOException;
37  import java.io.InputStream;
38  
39  import junit.framework.Test;
40  import junit.framework.TestSuite;
41  
42  import org.apache.commons.httpclient.methods.PostMethod;
43  import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
44  import org.apache.commons.httpclient.methods.multipart.FilePart;
45  import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
46  import org.apache.commons.httpclient.methods.multipart.Part;
47  import org.apache.commons.httpclient.methods.multipart.PartSource;
48  import org.apache.commons.httpclient.methods.multipart.StringPart;
49  
50  /**
51   * Webapp tests specific to the MultiPostMethod.
52   *
53   * @author <a href="oleg@ural.ru">Oleg Kalnichevski</a>
54   */
55  public class TestMultipartPost extends HttpClientTestBase {
56  
57      public TestMultipartPost(final String testName) throws IOException {
58          super(testName);
59      }
60  
61      public static Test suite() {
62          TestSuite suite = new TestSuite(TestMultipartPost.class);
63          ProxyTestDecorator.addTests(suite);
64          return suite;
65      }
66  
67      public static void main(String args[]) {
68          String[] testCaseName = { TestMultipartPost.class.getName() };
69          junit.textui.TestRunner.main(testCaseName);
70      }
71  
72      // ------------------------------------------------------------------ Tests
73      
74      /**
75       * Test that the body consisting of a string part can be posted.
76       */
77      public void testPostStringPart() throws Exception {
78          
79          this.server.setHttpService(new EchoService());
80          
81          PostMethod method = new PostMethod();
82          MultipartRequestEntity entity = new MultipartRequestEntity(
83              new Part[] { new StringPart("param", "Hello", "ISO-8859-1") },
84              method.getParams());
85          method.setRequestEntity(entity);
86          client.executeMethod(method);
87  
88          assertEquals(200,method.getStatusCode());
89          String body = method.getResponseBodyAsString();
90          assertTrue(body.indexOf("Content-Disposition: form-data; name=\"param\"") >= 0);
91          assertTrue(body.indexOf("Content-Type: text/plain; charset=ISO-8859-1") >= 0);
92          assertTrue(body.indexOf("Content-Transfer-Encoding: 8bit") >= 0);
93          assertTrue(body.indexOf("Hello") >= 0);
94      }
95  
96  
97      /**
98       * Test that the body consisting of a file part can be posted.
99       */
100     public void testPostFilePart() throws Exception {
101         
102         this.server.setHttpService(new EchoService());
103 
104         PostMethod method = new PostMethod();
105         byte[] content = "Hello".getBytes();
106         MultipartRequestEntity entity = new MultipartRequestEntity(
107             new Part[] { 
108                 new FilePart(
109                     "param1", 
110                     new ByteArrayPartSource("filename.txt", content), 
111                     "text/plain", 
112                     "ISO-8859-1") },
113             method.getParams());
114         method.setRequestEntity(entity);
115 
116         client.executeMethod(method);
117 
118         assertEquals(200,method.getStatusCode());
119         String body = method.getResponseBodyAsString();
120         assertTrue(body.indexOf("Content-Disposition: form-data; name=\"param1\"; filename=\"filename.txt\"") >= 0);
121         assertTrue(body.indexOf("Content-Type: text/plain; charset=ISO-8859-1") >= 0);
122         assertTrue(body.indexOf("Content-Transfer-Encoding: binary") >= 0);
123         assertTrue(body.indexOf("Hello") >= 0);
124     }
125 
126     /**
127      * Test that the body consisting of a file part of unknown length can be posted.
128      */
129 
130     public class TestPartSource implements PartSource {
131         private String fileName;
132         private byte[] data;
133 
134         public TestPartSource(String fileName, byte[] data) {
135             this.fileName = fileName;
136             this.data = data;
137         }
138 
139         public long getLength() {
140             return -1;
141         }
142 
143         public String getFileName() {
144             return fileName;
145         }
146 
147         public InputStream createInputStream() throws IOException {
148             return new ByteArrayInputStream(data);
149         }
150 
151     }
152     
153     public void testPostFilePartUnknownLength() throws Exception {
154         
155         this.server.setHttpService(new EchoService());
156 
157         String enc = "ISO-8859-1";
158         PostMethod method = new PostMethod();
159         byte[] content = "Hello".getBytes(enc);
160         MultipartRequestEntity entity = new MultipartRequestEntity(
161             new Part[] { 
162                 new FilePart(
163                     "param1", 
164                     new TestPartSource("filename.txt", content), 
165                      "text/plain", 
166                      enc) },
167              method.getParams());
168         method.setRequestEntity(entity);
169 
170         client.executeMethod(method);
171 
172         assertEquals(200,method.getStatusCode());
173         String body = method.getResponseBodyAsString();
174         assertTrue(body.indexOf("Content-Disposition: form-data; name=\"param1\"; filename=\"filename.txt\"") >= 0);
175         assertTrue(body.indexOf("Content-Type: text/plain; charset="+enc) >= 0);
176         assertTrue(body.indexOf("Content-Transfer-Encoding: binary") >= 0);
177         assertTrue(body.indexOf("Hello") >= 0);
178     }
179     
180 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestNVP.html100644 0 0 24325 10661532627 25274 0ustar 0 0 TestNVP xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestNVP.java,v 1.5 2004/02/22 18:08:49 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient;
31  
32  import junit.framework.*;
33  
34  /**
35   * Simple tests for {@link NameValuePair}.
36   *
37   * @author Rodney Waldhoff
38   * @version $Id: TestNVP.java 480424 2006-11-29 05:56:49Z bayard $
39   */
40  public class TestNVP extends TestCase {
41  
42      // ------------------------------------------------------------ Constructor
43      public TestNVP(String testName) {
44          super(testName);
45      }
46  
47      // ------------------------------------------------------------------- Main
48      public static void main(String args[]) {
49          String[] testCaseName = { TestNVP.class.getName() };
50          junit.textui.TestRunner.main(testCaseName);
51      }
52  
53      // ------------------------------------------------------- TestCase Methods
54  
55      public static Test suite() {
56          return new TestSuite(TestNVP.class);
57      }
58  
59      // ------------------------------------------------------ Protected Methods
60  
61      protected NameValuePair makePair() {
62          return new NameValuePair();
63      }
64  
65      protected NameValuePair makePair(String name, String value) {
66          return new NameValuePair(name,value);
67      }
68  
69  
70      // ----------------------------------------------------------- Test Methods
71  
72      public void testGet() {
73          NameValuePair pair = makePair("name 1","value 1");
74          assertEquals("name 1",pair.getName());
75          assertEquals("value 1",pair.getValue());
76      }
77  
78      public void testSet() {
79          NameValuePair pair = makePair();
80          assertTrue(null == pair.getName());
81          assertTrue(null == pair.getValue());
82          pair.setName("name");
83          assertEquals("name",pair.getName());
84          pair.setValue("value");
85          assertEquals("value",pair.getValue());
86      }
87  
88      public void testHashCode() {
89          NameValuePair param1 = new NameValuePair("name1", "value1");
90          NameValuePair param2 = new NameValuePair("name2", "value2");
91          NameValuePair param3 = new NameValuePair("name1", "value1");
92          assertTrue(param1.hashCode() != param2.hashCode());
93          assertTrue(param1.hashCode() == param3.hashCode());
94      }
95      
96      public void testEquals() {
97          NameValuePair param1 = new NameValuePair("name1", "value1");
98          NameValuePair param2 = new NameValuePair("name2", "value2");
99          NameValuePair param3 = new NameValuePair("name1", "value1");
100         assertFalse(param1.equals(param2));
101         assertFalse(param1.equals(null));
102         assertFalse(param1.equals("name1 = value1"));
103         assertTrue(param1.equals(param1));
104         assertTrue(param2.equals(param2));
105         assertTrue(param1.equals(param3));
106     }
107     
108 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestNoHost.html100644 0 0 14102 10661532627 26033 0ustar 0 0 TestNoHost xref

1   /*
2    * $HeadURL: 
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   */
28  
29  package org.apache.commons.httpclient;
30  
31  import junit.framework.Test;
32  import junit.framework.TestCase;
33  import junit.framework.TestSuite;
34  
35  /**
36   * Tests that don't require any external host.
37   * I.e., that run entirely within this JVM.
38   *
39   * (True unit tests, by some definitions.)
40   *
41   * @author Rodney Waldhoff
42   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
43   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
44   * 
45   * @deprecated Use TestAll
46   */
47  public class TestNoHost extends TestCase {
48  
49      public TestNoHost(String testName) {
50          super(testName);
51      }
52  
53      public static Test suite() {
54          TestSuite suite = new TestSuite();
55          suite.addTest(TestAll.suite());
56          return suite;
57      }
58  
59      public static void main(String args[]) {
60          String[] testCaseName = { TestNoHost.class.getName() };
61          junit.textui.TestRunner.main(testCaseName);
62      }
63  
64  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestNoncompliant.html100644 0 0 54177 10661532627 27302 0ustar 0 0 TestNoncompliant xref

1   /*
2    * ====================================================================
3    *
4    *  Licensed to the Apache Software Foundation (ASF) under one or more
5    *  contributor license agreements.  See the NOTICE file distributed with
6    *  this work for additional information regarding copyright ownership.
7    *  The ASF licenses this file to You under the Apache License, Version 2.0
8    *  (the "License"); you may not use this file except in compliance with
9    *  the License.  You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   *  Unless required by applicable law or agreed to in writing, software
14   *  distributed under the License is distributed on an "AS IS" BASIS,
15   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   *  See the License for the specific language governing permissions and
17   *  limitations under the License.
18   * ====================================================================
19   *
20   * This software consists of voluntary contributions made by many
21   * individuals on behalf of the Apache Software Foundation.  For more
22   * information on the Apache Software Foundation, please see
23   * <http://www.apache.org/>.
24   *
25   * [Additional notices, if required by prior licensing conditions]
26   *
27   */
28  package org.apache.commons.httpclient;
29  
30  import java.io.IOException;
31  
32  import junit.framework.*;
33  import org.apache.commons.httpclient.methods.*;
34  import org.apache.commons.httpclient.params.HttpMethodParams;
35  import org.apache.commons.httpclient.server.HttpRequestHandler;
36  import org.apache.commons.httpclient.server.ResponseWriter;
37  import org.apache.commons.httpclient.server.SimpleHttpServerConnection;
38  import org.apache.commons.httpclient.server.SimpleRequest;
39  
40  /**
41   * Tests handling of non-compliant responses.
42   * 
43   * @author Oleg Kalnichevski
44   * @author Jeff Dever
45   */
46  public class TestNoncompliant extends HttpClientTestBase {
47  
48      public TestNoncompliant(String s) throws IOException {
49          super(s);
50      }
51  
52      public static Test suite() {
53          TestSuite suite = new TestSuite(TestNoncompliant.class);
54          return suite;
55      }
56  
57      /**
58       * Tests if client is able to recover gracefully when HTTP server or
59       * proxy fails to send 100 status code when expected. The client should
60       * resume sending the request body after a defined timeout without having
61       * received "continue" code.
62       */
63      public void testNoncompliantPostMethodString() throws Exception {
64          this.server.setRequestHandler(new HttpRequestHandler() {
65              public boolean processRequest(SimpleHttpServerConnection conn,
66                      SimpleRequest request) throws IOException {
67                  ResponseWriter out = conn.getWriter();
68                  out.println("HTTP/1.1 200 OK");
69                  out.println("Connection: close");
70                  out.println("Content-Length: 0");
71                  out.println();
72                  out.flush();
73                  return true;
74              }
75          });
76  
77          PostMethod method = new PostMethod("/");
78          method.getParams().setBooleanParameter(
79                  HttpMethodParams.USE_EXPECT_CONTINUE, true);
80          method.setRequestEntity(new StringRequestEntity(
81                  "This is data to be sent in the body of an HTTP POST.", null, null));
82          client.executeMethod(method);
83          assertEquals(200, method.getStatusCode());
84      }
85  
86      /**
87       * Tests that a response status line containing \r and \n is handled.
88       */
89      public void testNoncompliantStatusLine() {
90          this.server.setRequestHandler(new HttpRequestHandler() {
91              public boolean processRequest(SimpleHttpServerConnection conn,
92                      SimpleRequest request) throws IOException {
93                  ResponseWriter out = conn.getWriter();
94                  out.println("HTTP/1.1 444 This status message contains\n"
95                          + " a newline and a\r"
96                          + " carrage return but that should be OK.");
97                  out.println("Connection: close");
98                  out.println("Content-Length: 0");
99                  out.println();
100                 out.flush();
101                 return true;
102             }
103         });
104         GetMethod method = new GetMethod("/");
105         try {
106             client.executeMethod(method);
107         } catch (Exception e) {
108             e.printStackTrace();
109             fail("Unexpected exception: " + e.toString());
110         }
111         assertEquals(444, method.getStatusCode());
112     }
113 
114     /**
115      * Test if a response to HEAD method from non-compliant server that contains
116      * an unexpected body content can be correctly redirected
117      */
118     public void testNoncompliantHeadWithResponseBody() throws Exception {
119         final String body = "Test body";
120         this.server.setRequestHandler(new HttpRequestHandler() {
121             public boolean processRequest(SimpleHttpServerConnection conn,
122                     SimpleRequest request) throws IOException {
123                 ResponseWriter out = conn.getWriter();
124                 out.println("HTTP/1.1 200 OK");
125                 out.println("Connection: close");
126                 out.println("Content-Length: " + body.length());
127                 out.println();
128                 out.print(body);
129                 out.flush();
130                 return true;
131             }
132         });
133         HeadMethod method = new HeadMethod("/");
134         method.getParams().setIntParameter(
135                 HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, 50);
136         client.executeMethod(method);
137         assertEquals(200, method.getStatusCode());
138         method.releaseConnection();
139     }
140 
141     /**
142      * Test if a response to HEAD method from non-compliant server causes an
143      * HttpException to be thrown
144      */
145     public void testNoncompliantHeadStrictMode() throws Exception {
146         final String body = "Test body";
147         this.server.setRequestHandler(new HttpRequestHandler() {
148             public boolean processRequest(SimpleHttpServerConnection conn,
149                     SimpleRequest request) throws IOException {
150                 ResponseWriter out = conn.getWriter();
151                 out.println("HTTP/1.1 200 OK");
152                 out.println("Connection: close");
153                 out.println("Content-Length: " + body.length());
154                 out.println();
155                 out.print(body);
156                 out.flush();
157                 return true;
158             }
159         });
160         client.getParams().setBooleanParameter(
161                 HttpMethodParams.REJECT_HEAD_BODY, true);
162         HeadMethod method = new NoncompliantHeadMethod("/");
163         method.getParams().setIntParameter(
164                 HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, 50);
165         try {
166             client.executeMethod(method);
167             fail("HttpException should have been thrown");
168         } catch (HttpException e) {
169             // Expected
170         }
171         method.releaseConnection();
172     }
173 
174     /**
175      * Tests if client is able to handle gracefully malformed responses
176      * that may not include response body.
177      */
178     public void testMalformed304Response() throws Exception {
179         this.server.setRequestHandler(new HttpRequestHandler() {
180             public boolean processRequest(SimpleHttpServerConnection conn,
181                     SimpleRequest request) throws IOException {
182                 conn.setSocketTimeout(20000);
183                 ResponseWriter out = conn.getWriter();
184                 out.println("HTTP/1.1 304 OK");
185                 out.println("Connection: keep-alive");
186                 out.println("Content-Length: 100");
187                 out.println();
188                 out.flush();
189                 conn.setKeepAlive(true);
190                 return true;
191             }
192         });
193 
194         GetMethod method = new GetMethod("/");
195         method.getParams().setSoTimeout(1000);
196         client.executeMethod(method);
197         assertEquals(HttpStatus.SC_NOT_MODIFIED, method.getStatusCode());
198         method.getResponseBody();
199     }
200 
201     public void testMalformed204Response() throws Exception {
202         this.server.setRequestHandler(new HttpRequestHandler() {
203             public boolean processRequest(SimpleHttpServerConnection conn,
204                     SimpleRequest request) throws IOException {
205                 conn.setSocketTimeout(20000);
206                 ResponseWriter out = conn.getWriter();
207                 out.println("HTTP/1.1 204 OK");
208                 out.println("Connection: close");
209                 out.println("Content-Length: 100");
210                 out.println();
211                 out.flush();
212                 conn.setKeepAlive(true);
213                 return true;
214             }
215         });
216 
217         GetMethod method = new GetMethod("/");
218         method.getParams().setSoTimeout(1000);
219         client.executeMethod(method);
220         assertEquals(HttpStatus.SC_NO_CONTENT, method.getStatusCode());
221         method.getResponseBody();
222     }
223     
224 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestParameterFormatter.html100644 0 0 23714 10661532627 30436 0ustar 0 0 TestParameterFormatter xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestParameterFormatter.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient;
31  
32  import org.apache.commons.httpclient.util.ParameterFormatter;
33  
34  import junit.framework.Test;
35  import junit.framework.TestCase;
36  import junit.framework.TestSuite;
37  
38  /**
39   * Unit tests for {@link ParameterFormatter}.
40   *
41   * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
42   */
43  public class TestParameterFormatter extends TestCase {
44  
45      // ------------------------------------------------------------ Constructor
46      public TestParameterFormatter(String testName) {
47          super(testName);
48      }
49  
50      // ------------------------------------------------------------------- Main
51      public static void main(String args[]) {
52          String[] testCaseName = { TestParameterFormatter.class.getName() };
53          junit.textui.TestRunner.main(testCaseName);
54      }
55  
56      // ------------------------------------------------------- TestCase Methods
57  
58      public static Test suite() {
59          return new TestSuite(TestParameterFormatter.class);
60      }
61  
62      public void testBasicValueFormatting() throws Exception {
63          ParameterFormatter formatter = new ParameterFormatter();
64          
65          NameValuePair param1 = new NameValuePair("param", "regular_stuff"); 
66          NameValuePair param2 = new NameValuePair("param", "this\\that"); 
67          NameValuePair param3 = new NameValuePair("param", "this,that"); 
68          NameValuePair param4 = new NameValuePair("param", "quote marks (\") must be escaped"); 
69          NameValuePair param5 = new NameValuePair("param", "back slash (\\) must be escaped too"); 
70          NameValuePair param6 = new NameValuePair("param", "values with\tblanks must always be quoted"); 
71          
72          formatter.setAlwaysUseQuotes(false);
73          assertEquals("param=regular_stuff", formatter.format(param1));
74          assertEquals("param=\"this\\\\that\"", formatter.format(param2));
75          assertEquals("param=\"this,that\"", formatter.format(param3));
76          assertEquals("param=\"quote marks (\\\") must be escaped\"", formatter.format(param4));
77          assertEquals("param=\"back slash (\\\\) must be escaped too\"", formatter.format(param5));
78          assertEquals("param=\"values with\tblanks must always be quoted\"", formatter.format(param6));
79  
80          formatter.setAlwaysUseQuotes(true);
81          assertEquals("param=\"regular_stuff\"", formatter.format(param1));
82          assertEquals("param=\"this\\\\that\"", formatter.format(param2));
83          assertEquals("param=\"this,that\"", formatter.format(param3));
84          assertEquals("param=\"quote marks (\\\") must be escaped\"", formatter.format(param4));
85          assertEquals("param=\"back slash (\\\\) must be escaped too\"", formatter.format(param5));
86          assertEquals("param=\"values with\tblanks must always be quoted\"", formatter.format(param6));
87      }
88      
89  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestParameterParser.html100644 0 0 33171 10661532627 27725 0ustar 0 0 TestParameterParser xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestParameterParser.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient;
31  
32  import junit.framework.Test;
33  import junit.framework.TestCase;
34  import junit.framework.TestSuite;
35  
36  import java.util.List;
37  
38  import org.apache.commons.httpclient.util.ParameterParser;
39  
40  /**
41   * Unit tests for {@link ParameterParser}.
42   *
43   * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
44   */
45  public class TestParameterParser extends TestCase {
46  
47      // ------------------------------------------------------------ Constructor
48      public TestParameterParser(String testName) {
49          super(testName);
50      }
51  
52      // ------------------------------------------------------------------- Main
53      public static void main(String args[]) {
54          String[] testCaseName = { TestParameterParser.class.getName() };
55          junit.textui.TestRunner.main(testCaseName);
56      }
57  
58      // ------------------------------------------------------- TestCase Methods
59  
60      public static Test suite() {
61          return new TestSuite(TestParameterParser.class);
62      }
63  
64      public void testParsing() {
65          String s = 
66            "test; test1 =  stuff   ; test2 =  \"stuff; stuff\"; test3=\"stuff";
67          ParameterParser  parser = new ParameterParser();
68          List params = parser.parse(s, ';');
69          assertEquals("test", ((NameValuePair)params.get(0)).getName());
70          assertEquals(null, ((NameValuePair)params.get(0)).getValue());
71          assertEquals("test1", ((NameValuePair)params.get(1)).getName());
72          assertEquals("stuff", ((NameValuePair)params.get(1)).getValue());
73          assertEquals("test2", ((NameValuePair)params.get(2)).getName());
74          assertEquals("stuff; stuff", ((NameValuePair)params.get(2)).getValue());
75          assertEquals("test3", ((NameValuePair)params.get(3)).getName());
76          assertEquals("\"stuff", ((NameValuePair)params.get(3)).getValue());
77  
78          s = "  test  , test1=stuff   ,  , test2=, test3, ";
79          params = parser.parse(s, ',');
80          assertEquals("test", ((NameValuePair)params.get(0)).getName());
81          assertEquals(null, ((NameValuePair)params.get(0)).getValue());
82          assertEquals("test1", ((NameValuePair)params.get(1)).getName());
83          assertEquals("stuff", ((NameValuePair)params.get(1)).getValue());
84          assertEquals("test2", ((NameValuePair)params.get(2)).getName());
85          assertEquals("", ((NameValuePair)params.get(2)).getValue());
86          assertEquals("test3", ((NameValuePair)params.get(3)).getName());
87          assertEquals(null, ((NameValuePair)params.get(3)).getValue());
88  
89          s = "  test";
90          params = parser.parse(s, ';');
91          assertEquals("test", ((NameValuePair)params.get(0)).getName());
92          assertEquals(null, ((NameValuePair)params.get(0)).getValue());
93  
94          s = "  ";
95          params = parser.parse(s, ';');
96          assertEquals(0, params.size());
97  
98          s = " = stuff ";
99          params = parser.parse(s, ';');
100         assertEquals(1, params.size());
101         assertEquals("", ((NameValuePair)params.get(0)).getName());
102         assertEquals("stuff", ((NameValuePair)params.get(0)).getValue());
103     }
104     
105     public void testParsingEscapedChars() {
106         String s = "param = \"stuff\\\"; more stuff\"";
107         ParameterParser parser = new ParameterParser();
108         List params = parser.parse(s, ';');
109         assertEquals(1, params.size());
110         assertEquals("param", 
111                 ((NameValuePair)params.get(0)).getName());
112         assertEquals("stuff\\\"; more stuff", 
113                 ((NameValuePair)params.get(0)).getValue());
114 
115         s = "param = \"stuff\\\\\"; anotherparam";
116         params = parser.parse(s, ';');
117         assertEquals(2, params.size());
118         assertEquals("param", 
119                 ((NameValuePair)params.get(0)).getName());
120         assertEquals("stuff\\\\", 
121                 ((NameValuePair)params.get(0)).getValue());
122         assertEquals("anotherparam", 
123                 ((NameValuePair)params.get(1)).getName());
124         assertNull(
125                 ((NameValuePair)params.get(1)).getValue());
126     }
127     
128     public void testParsingBlankParams() {
129         String s =  "test; test1 =  ; test2 = \"\"";
130         ParameterParser  parser = new ParameterParser();
131         List params = parser.parse(s, ';');
132         assertEquals("test", ((NameValuePair)params.get(0)).getName());
133         assertEquals(null, ((NameValuePair)params.get(0)).getValue());
134         assertEquals("test1", ((NameValuePair)params.get(1)).getName());
135         assertEquals("", ((NameValuePair)params.get(1)).getValue());
136         assertEquals("test2", ((NameValuePair)params.get(2)).getName());
137         assertEquals("", ((NameValuePair)params.get(2)).getValue());
138     }
139 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestPartsNoHost.html100644 0 0 25443 10661532627 27057 0ustar 0 0 TestPartsNoHost xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestPartsNoHost.java,v 1.7 2004/02/22 18:08:49 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import java.io.ByteArrayOutputStream;
35  import java.io.File;
36  import java.io.FileWriter;
37  import java.io.IOException;
38  import java.io.PrintWriter;
39  
40  import junit.framework.Test;
41  import junit.framework.TestCase;
42  import junit.framework.TestSuite;
43  
44  import org.apache.commons.httpclient.methods.multipart.FilePart;
45  import org.apache.commons.httpclient.methods.multipart.StringPart;
46  
47  /**
48   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
49   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
50   */
51  public class TestPartsNoHost extends TestCase {
52  
53      static final String PART_DATA = "This is the part data.";
54      static final String NAME = "name";
55  
56      // ------------------------------------------------------------ Constructor
57  
58      public TestPartsNoHost(String testName) {
59          super(testName);
60      }
61  
62      // ------------------------------------------------------- TestCase Methods
63  
64      public static Test suite() {
65          return new TestSuite(TestPartsNoHost.class);
66      }
67  
68      // ----------------------------------------------------------------- Tests
69  
70      public void testFilePartResendsFileData() throws Exception {
71          File file = createTempTestFile();
72          FilePart part = new FilePart(NAME, file);
73          ByteArrayOutputStream stream = new ByteArrayOutputStream();
74          part.send(stream);
75          String resp1 = stream.toString();
76          stream = new ByteArrayOutputStream();
77          part.send(stream);
78          String resp2 = stream.toString();
79          file.delete();
80          assertEquals(resp1, resp2);
81      }
82  
83      public void testStringPartResendsData() throws Exception {
84          StringPart part = new StringPart(NAME, PART_DATA);
85          ByteArrayOutputStream stream = new ByteArrayOutputStream();
86          part.send(stream);
87          String resp1 = stream.toString();
88          stream = new ByteArrayOutputStream();
89          part.send(stream);
90          String resp2 = stream.toString();
91          assertEquals(resp1, resp2);
92      }
93  
94      public void testFilePartNullFileResendsData() throws Exception {
95          FilePart part = new FilePart(NAME, "emptyfile.ext", null);
96          ByteArrayOutputStream stream = new ByteArrayOutputStream();
97          part.send(stream);
98          String resp1 = stream.toString();
99          stream = new ByteArrayOutputStream();
100         part.send(stream);
101         String resp2 = stream.toString();
102         assertEquals(resp1, resp2);
103     }
104 
105 
106     /** Writes PART_DATA out to a temporary file and returns the file it
107      * was written to.
108      * @return the File object representing the file the data was
109      * written to.
110      */
111     private File createTempTestFile() throws IOException {
112         File file = File.createTempFile("FilePartTest", ".txt");
113         PrintWriter out = new PrintWriter(new FileWriter(file));
114         out.println(PART_DATA);
115         out.flush();
116         out.close();
117         return file;
118     }
119 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestPostMethod.html100644 0 0 45206 10661532627 26720 0ustar 0 0 TestPostMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestWebappPostMethod.java,v 1.7 2004/05/12 20:43:54 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import junit.framework.*;
34  import org.apache.commons.httpclient.methods.*;
35  import java.io.*;
36  
37  /**
38   * Webapp tests specific to the PostMethod.
39   *
40   * @author <a href="jsdever@apache.org">Jeff Dever</a>
41   * @version $Id: TestPostMethod.java 480424 2006-11-29 05:56:49Z bayard $
42   */
43  public class TestPostMethod extends HttpClientTestBase {
44  
45      public TestPostMethod(String testName) throws IOException {
46          super(testName);
47      }
48  
49      public static Test suite() {
50          TestSuite suite = new TestSuite(TestPostMethod.class);
51          return suite;
52      }
53  
54      public static void main(String args[]) {
55          String[] testCaseName = { TestPostMethod.class.getName() };
56          junit.textui.TestRunner.main(testCaseName);
57      }
58  
59      // ------------------------------------------------------------------ Tests
60      
61      /**
62       * Test that the body can be set as a array of parameters
63       */
64      public void testParametersBodyToParamServlet() throws Exception {
65          PostMethod method = new PostMethod("/");
66          NameValuePair[] parametersBody =  new NameValuePair[] { 
67              new NameValuePair("pname1","pvalue1"),
68              new NameValuePair("pname2","pvalue2") 
69          };
70          method.setRequestBody(parametersBody);
71          this.server.setHttpService(new EchoService());
72          try {
73              this.client.executeMethod(method);
74              assertEquals(200, method.getStatusCode());
75              String body = method.getResponseBodyAsString();
76              assertEquals("pname1=pvalue1&pname2=pvalue2", body);
77          } finally {
78              method.releaseConnection();
79          }
80      }
81  
82      /**
83       * Test that the body can be set as a String
84       */
85      public void testStringBodyToParamServlet() throws Exception {
86          PostMethod method = new PostMethod("/");
87          String stringBody = "pname1=pvalue1&pname2=pvalue2";
88          method.setRequestEntity(
89              new StringRequestEntity(stringBody, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE, null));
90          this.server.setHttpService(new EchoService());
91          try {
92              this.client.executeMethod(method);
93              assertEquals(200, method.getStatusCode());
94              String body = method.getResponseBodyAsString();
95              assertEquals("pname1=pvalue1&pname2=pvalue2", body);
96          } finally {
97              method.releaseConnection();
98          }
99      }
100 
101     /**
102      * Test that the body can be set as a String without an explict 
103      * content type
104      */
105     public void testStringBodyToBodyServlet() throws Exception {
106         PostMethod method = new PostMethod("/");
107         String stringBody = "pname1=pvalue1&pname2=pvalue2";
108 
109         method.setRequestEntity(new StringRequestEntity(stringBody, null, null));
110         this.server.setHttpService(new EchoService());
111         try {
112             this.client.executeMethod(method);
113             assertEquals(200, method.getStatusCode());
114             String body = method.getResponseBodyAsString();
115             assertEquals("pname1=pvalue1&pname2=pvalue2", body);
116         } finally {
117             method.releaseConnection();
118         }
119     }
120 
121     /**
122      * Test that parameters can be added.
123      */
124     public void testAddParametersToParamServlet() throws Exception {
125         PostMethod method = new PostMethod("/");
126 
127         method.addParameter(new NameValuePair("pname1","pvalue1"));
128         method.addParameter(new NameValuePair("pname2","pvalue2"));
129 
130         this.server.setHttpService(new EchoService());
131         try {
132             this.client.executeMethod(method);
133             assertEquals(200, method.getStatusCode());
134             String body = method.getResponseBodyAsString();
135             assertEquals("pname1=pvalue1&pname2=pvalue2", body);
136         } finally {
137             method.releaseConnection();
138         }
139     }
140 
141     /**
142      * Test that parameters can be added and removed.
143      */
144     public void testAddRemoveParametersToParamServlet() throws Exception {
145         PostMethod method = new PostMethod("/");
146 
147         method.addParameter(new NameValuePair("pname0","pvalue0"));
148         method.addParameter(new NameValuePair("pname1","pvalue1"));
149         method.addParameter(new NameValuePair("pname2","pvalue2"));
150         method.addParameter(new NameValuePair("pname3","pvalue3"));
151         method.removeParameter("pname0");
152         method.removeParameter("pname3");
153 
154         this.server.setHttpService(new EchoService());
155         try {
156             this.client.executeMethod(method);
157             assertEquals(200, method.getStatusCode());
158             String body = method.getResponseBodyAsString();
159             assertEquals("pname1=pvalue1&pname2=pvalue2", body);
160         } finally {
161             method.releaseConnection();
162         }
163     }
164 
165     /**
166      * Test the return value of the PostMethod#removeParameter.
167      */
168     public void testRemoveParameterReturnValue() throws Exception {
169         PostMethod method = new PostMethod("/");
170 
171         method.addParameter("param", "whatever");
172         assertTrue("Return value of the method is expected to be true", method.removeParameter("param"));
173         assertFalse("Return value of the method is expected to be false", method.removeParameter("param"));
174     }
175 
176     private String getRequestAsString(RequestEntity entity) throws Exception {
177         ByteArrayOutputStream bos = new ByteArrayOutputStream();
178         entity.writeRequest(bos);
179         return new String(bos.toByteArray(), "UTF-8");
180     }
181     
182     /**
183      * Test if setParameter overwrites existing parameter values.
184      */
185     public void testAddParameterFollowedBySetParameter() throws Exception {
186         PostMethod method = new PostMethod("/");
187 
188         method.addParameter("param", "a");
189         method.addParameter("param", "b");
190         method.addParameter("param", "c");
191         assertEquals("param=a&param=b&param=c", getRequestAsString(method.getRequestEntity()));
192         method.setParameter("param", "a");
193         assertEquals("param=a", getRequestAsString(method.getRequestEntity()));
194     }
195 
196 }
197 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestPostParameterEncoding.html100644 0 0 26060 10661532627 31064 0ustar 0 0 TestPostParameterEncoding xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestPostMethod.java,v 1.5 2004/12/12 10:02:38 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient;
31  
32  import java.io.ByteArrayOutputStream;
33  import java.io.IOException;
34  
35  import junit.framework.Test;
36  import junit.framework.TestCase;
37  import junit.framework.TestSuite;
38  
39  import org.apache.commons.httpclient.methods.PostMethod;
40  import org.apache.commons.httpclient.methods.RequestEntity;
41  import org.apache.commons.httpclient.methods.StringRequestEntity;
42  
43  /**
44   * Tests basic method functionality.
45   *
46   * @author Remy Maucherat
47   * @author Rodney Waldhoff
48   * 
49   * @version $Id: TestPostParameterEncoding.java 480424 2006-11-29 05:56:49Z bayard $
50   */
51  public class TestPostParameterEncoding extends TestCase {
52  
53      static final String NAME = "name", VALUE = "value";
54      static final String NAME0 = "name0", VALUE0 = "value0";
55      static final String NAME1 = "name1", VALUE1 = "value1";
56      static final String NAME2 = "name2", VALUE2 = "value2";
57  
58      static final NameValuePair PAIR = new NameValuePair(NAME, VALUE);
59      static final NameValuePair PAIR0 = new NameValuePair(NAME0, VALUE0);
60      static final NameValuePair PAIR1 = new NameValuePair(NAME1, VALUE1);
61      static final NameValuePair PAIR2 = new NameValuePair(NAME2, VALUE2);
62  
63      public TestPostParameterEncoding(final String testName) throws IOException {
64          super(testName);
65      }
66  
67      public static Test suite() {
68          return new TestSuite(TestPostParameterEncoding.class);
69      }
70  
71      public static void main(String args[]) {
72          String[] testCaseName = { TestPostParameterEncoding.class.getName() };
73          junit.textui.TestRunner.main(testCaseName);
74      }
75      
76      private String getRequestAsString(RequestEntity entity) throws Exception {
77          ByteArrayOutputStream bos = new ByteArrayOutputStream();
78          entity.writeRequest(bos);
79          return new String(bos.toByteArray(), "UTF-8");
80      }
81      
82      public void testPostParametersEncoding() throws Exception {
83          PostMethod post = new PostMethod();
84          post.setRequestBody(new NameValuePair[] { PAIR });
85          assertEquals("name=value", getRequestAsString(post.getRequestEntity()));
86  
87          post.setRequestBody(new NameValuePair[]{ PAIR, PAIR1, PAIR2 });
88          assertEquals("name=value&name1=value1&name2=value2", 
89              getRequestAsString(post.getRequestEntity()));
90  
91          post.setRequestBody(new NameValuePair[]{ PAIR, PAIR1, PAIR2, new NameValuePair("hasSpace", "a b c d") });
92          assertEquals("name=value&name1=value1&name2=value2&hasSpace=a+b+c+d",
93              getRequestAsString(post.getRequestEntity()));
94  
95          post.setRequestBody(new NameValuePair[]{ new NameValuePair("escaping", ",.-\u00f6\u00e4\u00fc!+@#*&()=?:;}{[]$") });
96          assertEquals("escaping=%2C.-%F6%E4%FC%21%2B%40%23*%26%28%29%3D%3F%3A%3B%7D%7B%5B%5D%24",
97              getRequestAsString(post.getRequestEntity()));
98          
99      }
100 
101     public void testPostSetRequestBody() throws Exception {
102         PostMethod post = new PostMethod("/foo");
103         String body = "this+is+the+body";
104         post.setRequestEntity(new StringRequestEntity(body, null, null));
105         assertEquals(body, getRequestAsString(post.getRequestEntity()));
106     }
107     
108 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestProxy.html100644 0 0 241261 10661532627 25772 0ustar 0 0 TestProxy xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestProxy.java,v 1.11 2004/12/11 22:35:26 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  package org.apache.commons.httpclient;
30  
31  import java.io.IOException;
32  import java.util.Enumeration;
33  
34  import junit.extensions.TestSetup;
35  import junit.framework.Test;
36  import junit.framework.TestSuite;
37  
38  import org.apache.commons.httpclient.auth.AuthScheme;
39  import org.apache.commons.httpclient.auth.AuthScope;
40  import org.apache.commons.httpclient.auth.CredentialsNotAvailableException;
41  import org.apache.commons.httpclient.auth.CredentialsProvider;
42  import org.apache.commons.httpclient.methods.GetMethod;
43  import org.apache.commons.httpclient.methods.PostMethod;
44  import org.apache.commons.httpclient.methods.StringRequestEntity;
45  import org.apache.commons.httpclient.server.AuthRequestHandler;
46  import org.apache.commons.httpclient.server.HttpRequestHandlerChain;
47  import org.apache.commons.httpclient.server.HttpServiceHandler;
48  
49  /**
50   * Tests for proxied connections.
51   * 
52   * @author Ortwin Glueck
53   * @author Oleg Kalnichevski
54   */
55  public class TestProxy extends HttpClientTestBase {
56  
57      public TestProxy(String testName) throws IOException {
58          super(testName);
59          setUseProxy(true);
60      }
61  
62      static class SSLDecorator extends TestSetup {
63  
64          public static void addTests(TestSuite suite) {
65              TestSuite ts2 = new TestSuite();
66              addTest(ts2, suite);
67              suite.addTest(ts2);        
68          }
69          
70          private static void addTest(TestSuite suite, Test t) {
71              if (t instanceof TestProxy) {
72                  suite.addTest(new SSLDecorator((TestProxy) t));
73              } else if (t instanceof TestSuite) {
74                  Enumeration en = ((TestSuite) t).tests();
75                  while (en.hasMoreElements()) {
76                      addTest(suite, (Test) en.nextElement());
77                  }
78              }
79          }
80          
81          public SSLDecorator(TestProxy test) {
82              super(test);
83          }
84                  
85          protected void setUp() throws Exception {
86              TestProxy base = (TestProxy)getTest();
87              base.setUseSSL(true);
88          }  
89      }
90      
91      public static Test suite() {
92          TestSuite suite = new TestSuite(TestProxy.class);
93          SSLDecorator.addTests(suite);
94          return suite;
95      }
96  
97      class GetItWrongThenGetItRight implements CredentialsProvider {
98          
99          private int hostcount = 0;
100         private int proxycount = 0;
101         
102         public GetItWrongThenGetItRight() {
103             super();
104         }
105         
106         public Credentials getCredentials(AuthScheme scheme, String host, int port, boolean proxy)
107                 throws CredentialsNotAvailableException {
108             if (!proxy) {
109                 this.hostcount++;
110                 return provideCredentials(this.hostcount);
111             } else {
112                 this.proxycount++;
113                 return provideCredentials(this.proxycount);
114             }
115         }
116         
117         private Credentials provideCredentials(int count) {
118             switch (count) {
119             case 1: 
120                 return new UsernamePasswordCredentials("testuser", "wrongstuff");
121             case 2: 
122                 return new UsernamePasswordCredentials("testuser", "testpass");
123             default:
124                 return null;
125             }
126         }
127 
128     }
129     
130     /**
131      * Tests GET via non-authenticating proxy
132      */
133     public void testSimpleGet() throws Exception {
134         this.server.setHttpService(new FeedbackService());
135         GetMethod get = new GetMethod("/");
136         try {
137             this.client.executeMethod(get);
138             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
139         } finally {
140             get.releaseConnection();
141         }
142     }
143     
144     /**
145      * Tests GET via non-authenticating proxy + host auth + connection keep-alive 
146      */
147     public void testGetHostAuthConnKeepAlive() throws Exception {
148 
149         UsernamePasswordCredentials creds = 
150             new UsernamePasswordCredentials("testuser", "testpass");
151         
152         this.client.getState().setCredentials(AuthScope.ANY, creds);
153         
154         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
155         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
156         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
157         
158         this.server.setRequestHandler(handlerchain);
159         
160         GetMethod get = new GetMethod("/");
161         try {
162             this.client.executeMethod(get);
163             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
164         } finally {
165             get.releaseConnection();
166         }
167     }
168     
169     /**
170      * Tests GET via non-authenticating proxy + host auth + connection close 
171      */
172     public void testGetHostAuthConnClose() throws Exception {
173 
174         UsernamePasswordCredentials creds = 
175             new UsernamePasswordCredentials("testuser", "testpass");
176         
177         this.client.getState().setCredentials(AuthScope.ANY, creds);
178         
179         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
180         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
181         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
182         
183         this.server.setRequestHandler(handlerchain);
184         
185         GetMethod get = new GetMethod("/");
186         try {
187             this.client.executeMethod(get);
188             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
189         } finally {
190             get.releaseConnection();
191         }
192     }
193 
194     /**
195      * Tests GET via non-authenticating proxy + invalid host auth 
196      */
197     public void testGetHostInvalidAuth() throws Exception {
198 
199         UsernamePasswordCredentials creds = 
200             new UsernamePasswordCredentials("testuser", "testpass");
201         
202         this.client.getState().setCredentials(AuthScope.ANY, creds);
203         
204         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
205         handlerchain.appendHandler(new AuthRequestHandler(creds));
206         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
207         
208         this.client.getState().setCredentials(AuthScope.ANY,
209                 new UsernamePasswordCredentials("testuser", "wrongstuff"));
210         
211         this.server.setRequestHandler(handlerchain);
212         
213         GetMethod get = new GetMethod("/");
214         try {
215             this.client.executeMethod(get);
216             assertEquals(HttpStatus.SC_UNAUTHORIZED, get.getStatusCode());
217         } finally {
218             get.releaseConnection();
219         }
220     }
221 
222     /**
223      * Tests GET via non-authenticating proxy + interactive host auth + connection keep-alive 
224      */
225     public void testGetInteractiveHostAuthConnKeepAlive() throws Exception {
226 
227         UsernamePasswordCredentials creds = 
228             new UsernamePasswordCredentials("testuser", "testpass");
229         
230         this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
231                 new GetItWrongThenGetItRight());
232         
233         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
234         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
235         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
236         
237         this.server.setRequestHandler(handlerchain);
238         
239         GetMethod get = new GetMethod("/");
240         try {
241             this.client.executeMethod(get);
242             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
243         } finally {
244             get.releaseConnection();
245         }
246     }
247    
248     /**
249      * Tests GET via non-authenticating proxy + interactive host auth + connection close 
250      */
251     public void testGetInteractiveHostAuthConnClose() throws Exception {
252 
253         UsernamePasswordCredentials creds = 
254             new UsernamePasswordCredentials("testuser", "testpass");
255         
256         this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
257                 new GetItWrongThenGetItRight());
258         
259         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
260         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
261         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
262         
263         this.server.setRequestHandler(handlerchain);
264         
265         GetMethod get = new GetMethod("/");
266         try {
267             this.client.executeMethod(get);
268             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
269         } finally {
270             get.releaseConnection();
271         }
272     }
273 
274     /**
275      * Tests GET via authenticating proxy + host auth + connection keep-alive 
276      */
277     public void testGetProxyAuthHostAuthConnKeepAlive() throws Exception {
278 
279         UsernamePasswordCredentials creds = 
280             new UsernamePasswordCredentials("testuser", "testpass");
281         
282         this.client.getState().setCredentials(AuthScope.ANY, creds);
283         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
284         
285         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
286         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
287         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
288         
289         this.server.setRequestHandler(handlerchain);
290         
291         this.proxy.requireAuthentication(creds, "test", true);
292         
293         GetMethod get = new GetMethod("/");
294         try {
295             this.client.executeMethod(get);
296             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
297         } finally {
298             get.releaseConnection();
299         }
300     }
301     
302     /**
303      * Tests GET via authenticating proxy
304      */
305     public void testGetAuthProxy() throws Exception {
306         UsernamePasswordCredentials creds = 
307             new UsernamePasswordCredentials("testuser", "testpass");
308         
309         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
310         this.server.setHttpService(new FeedbackService());
311 
312         this.proxy.requireAuthentication(creds, "test", true);
313         
314         GetMethod get = new GetMethod("/");
315         try {
316             this.client.executeMethod(get);
317             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
318         } finally {
319             get.releaseConnection();
320         }
321     }
322     
323     /**
324      * Tests GET via authenticating proxy + host auth + connection close 
325      */
326     public void testGetProxyAuthHostAuthConnClose() throws Exception {
327 
328         UsernamePasswordCredentials creds = 
329             new UsernamePasswordCredentials("testuser", "testpass");
330         
331         this.client.getState().setCredentials(AuthScope.ANY, creds);
332         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
333         
334         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
335         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
336         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
337         
338         this.server.setRequestHandler(handlerchain);
339 
340         this.proxy.requireAuthentication(creds, "test", true);
341         
342         GetMethod get = new GetMethod("/");
343         try {
344             this.client.executeMethod(get);
345             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
346         } finally {
347             get.releaseConnection();
348         }
349     }
350     
351     /**
352      * Tests GET via authenticating proxy + invalid host auth 
353      */
354     public void testGetProxyAuthHostInvalidAuth() throws Exception {
355 
356         UsernamePasswordCredentials creds = 
357             new UsernamePasswordCredentials("testuser", "testpass");
358         
359         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
360         handlerchain.appendHandler(new AuthRequestHandler(creds));
361         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
362         
363         this.client.getState().setCredentials(AuthScope.ANY,
364                 new UsernamePasswordCredentials("testuser", "wrongstuff"));
365         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
366         
367         this.server.setRequestHandler(handlerchain);
368         
369         this.proxy.requireAuthentication(creds, "test", true);
370         
371         GetMethod get = new GetMethod("/");
372         try {
373             this.client.executeMethod(get);
374             assertEquals(HttpStatus.SC_UNAUTHORIZED, get.getStatusCode());
375         } finally {
376             get.releaseConnection();
377         }
378     }
379 
380     /**
381      * Tests GET via authenticating proxy + interactive host and proxy auth + connection keep-alive 
382      */
383     public void testGetInteractiveProxyAuthHostAuthConnKeepAlive() throws Exception {
384 
385         UsernamePasswordCredentials creds = 
386             new UsernamePasswordCredentials("testuser", "testpass");
387         
388         this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
389                 new GetItWrongThenGetItRight());
390         
391         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
392         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
393         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
394         
395         this.server.setRequestHandler(handlerchain);
396 
397         this.proxy.requireAuthentication(creds, "test", true);
398         
399         GetMethod get = new GetMethod("/");
400         try {
401             this.client.executeMethod(get);
402             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
403         } finally {
404             get.releaseConnection();
405         }
406     }
407 
408     /**
409      * Tests GET via authenticating proxy + interactive host and proxy auth + connection close 
410      */
411     public void testGetInteractiveProxyAuthHostAuthConnClose() throws Exception {
412 
413         UsernamePasswordCredentials creds = 
414             new UsernamePasswordCredentials("testuser", "testpass");
415         
416         this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
417                 new GetItWrongThenGetItRight());
418         
419         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
420         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
421         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
422         
423         this.server.setRequestHandler(handlerchain);
424         
425         this.proxy.requireAuthentication(creds, "test", true);
426         
427         GetMethod get = new GetMethod("/");
428         try {
429             this.client.executeMethod(get);
430             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
431         } finally {
432             get.releaseConnection();
433         }
434     }
435 
436     /**
437      * Tests POST via non-authenticating proxy
438      */
439     public void testSimplePost() throws Exception {
440         this.server.setHttpService(new FeedbackService());
441         PostMethod post = new PostMethod("/");
442         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
443         try {
444             this.client.executeMethod(post);
445             assertEquals(HttpStatus.SC_OK, post.getStatusCode());
446             assertNotNull(post.getResponseBodyAsString());
447         } finally {
448             post.releaseConnection();
449         }
450     }
451 
452     /**
453      * Tests POST via non-authenticating proxy + host auth + connection keep-alive 
454      */
455     public void testPostHostAuthConnKeepAlive() throws Exception {
456         UsernamePasswordCredentials creds = 
457             new UsernamePasswordCredentials("testuser", "testpass");
458         
459         this.client.getState().setCredentials(AuthScope.ANY, creds);
460         
461         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
462         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
463         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
464         
465         this.server.setRequestHandler(handlerchain);
466         
467         PostMethod post = new PostMethod("/");
468         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
469         try {
470             this.client.executeMethod(post);
471             assertEquals(HttpStatus.SC_OK, post.getStatusCode());
472             assertNotNull(post.getResponseBodyAsString());
473         } finally {
474             post.releaseConnection();
475         }
476     }
477 
478     /**
479      * Tests POST via non-authenticating proxy + host auth + connection close 
480      */
481     public void testPostHostAuthConnClose() throws Exception {
482         UsernamePasswordCredentials creds = 
483             new UsernamePasswordCredentials("testuser", "testpass");
484         
485         this.client.getState().setCredentials(AuthScope.ANY, creds);
486         
487         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
488         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
489         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
490         
491         this.server.setRequestHandler(handlerchain);
492         
493         PostMethod post = new PostMethod("/");
494         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
495         try {
496             this.client.executeMethod(post);
497             assertEquals(HttpStatus.SC_OK, post.getStatusCode());
498             assertNotNull(post.getResponseBodyAsString());
499         } finally {
500             post.releaseConnection();
501         }
502     }
503 
504     /**
505      * Tests POST via non-authenticating proxy + invalid host auth 
506      */
507     public void testPostHostInvalidAuth() throws Exception {
508 
509         UsernamePasswordCredentials creds = 
510             new UsernamePasswordCredentials("testuser", "testpass");
511         
512         this.client.getState().setCredentials(AuthScope.ANY, creds);
513         
514         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
515         handlerchain.appendHandler(new AuthRequestHandler(creds));
516         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
517         
518         this.client.getState().setCredentials(AuthScope.ANY,
519                 new UsernamePasswordCredentials("testuser", "wrongstuff"));
520         
521         this.server.setRequestHandler(handlerchain);
522         
523         PostMethod post = new PostMethod("/");
524         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
525         try {
526             this.client.executeMethod(post);
527             assertEquals(HttpStatus.SC_UNAUTHORIZED, post.getStatusCode());
528         } finally {
529             post.releaseConnection();
530         }
531     }
532 
533     /**
534      * Tests POST via non-authenticating proxy + interactive host auth + connection keep-alive 
535      */
536     public void testPostInteractiveHostAuthConnKeepAlive() throws Exception {
537         UsernamePasswordCredentials creds = 
538             new UsernamePasswordCredentials("testuser", "testpass");
539         
540         this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
541                 new GetItWrongThenGetItRight());
542         
543         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
544         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
545         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
546         
547         this.server.setRequestHandler(handlerchain);
548         
549         PostMethod post = new PostMethod("/");
550         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
551         try {
552             this.client.executeMethod(post);
553             assertEquals(HttpStatus.SC_OK, post.getStatusCode());
554             assertNotNull(post.getResponseBodyAsString());
555         } finally {
556             post.releaseConnection();
557         }
558     }
559 
560     /**
561      * Tests POST via non-authenticating proxy + interactive host auth + connection close 
562      */
563     public void testPostInteractiveHostAuthConnClose() throws Exception {
564         UsernamePasswordCredentials creds = 
565             new UsernamePasswordCredentials("testuser", "testpass");
566         
567         this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
568                 new GetItWrongThenGetItRight());
569                 
570         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
571         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
572         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
573         
574         this.server.setRequestHandler(handlerchain);
575         
576         PostMethod post = new PostMethod("/");
577         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
578         try {
579             this.client.executeMethod(post);
580             assertEquals(HttpStatus.SC_OK, post.getStatusCode());
581             assertNotNull(post.getResponseBodyAsString());
582         } finally {
583             post.releaseConnection();
584         }
585     }
586 
587     /**
588      * Tests POST via authenticating proxy
589      */
590     public void testPostAuthProxy() throws Exception {
591         UsernamePasswordCredentials creds = 
592             new UsernamePasswordCredentials("testuser", "testpass");
593         
594         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
595         this.server.setHttpService(new FeedbackService());
596 
597         this.proxy.requireAuthentication(creds, "test", true);
598 
599         PostMethod post = new PostMethod("/");
600         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
601         try {
602             this.client.executeMethod(post);
603             assertEquals(HttpStatus.SC_OK, post.getStatusCode());
604             assertNotNull(post.getResponseBodyAsString());
605         } finally {
606             post.releaseConnection();
607         }
608     }
609 
610     /**
611      * Tests POST via authenticating proxy + host auth + connection keep-alive 
612      */
613     public void testPostProxyAuthHostAuthConnKeepAlive() throws Exception {
614         UsernamePasswordCredentials creds = 
615             new UsernamePasswordCredentials("testuser", "testpass");
616         
617         this.client.getState().setCredentials(AuthScope.ANY, creds);
618         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
619         
620         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
621         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
622         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
623         
624         this.server.setRequestHandler(handlerchain);
625         
626         this.proxy.requireAuthentication(creds, "test", true);
627 
628         PostMethod post = new PostMethod("/");
629         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
630         try {
631             this.client.executeMethod(post);
632             assertEquals(HttpStatus.SC_OK, post.getStatusCode());
633             assertNotNull(post.getResponseBodyAsString());
634         } finally {
635             post.releaseConnection();
636         }
637     }
638 
639     /**
640      * Tests POST via authenticating proxy + host auth + connection close 
641      */
642     public void testPostProxyAuthHostAuthConnClose() throws Exception {
643         UsernamePasswordCredentials creds = 
644             new UsernamePasswordCredentials("testuser", "testpass");
645         
646         this.client.getState().setCredentials(AuthScope.ANY, creds);
647         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
648         
649         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
650         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
651         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
652         
653         this.server.setRequestHandler(handlerchain);
654         
655         this.proxy.requireAuthentication(creds, "test", true);
656 
657         PostMethod post = new PostMethod("/");
658         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
659         try {
660             this.client.executeMethod(post);
661             assertEquals(HttpStatus.SC_OK, post.getStatusCode());
662             assertNotNull(post.getResponseBodyAsString());
663         } finally {
664             post.releaseConnection();
665         }
666     }
667 
668     /**
669      * Tests POST via non-authenticating proxy + invalid host auth 
670      */
671     public void testPostProxyAuthHostInvalidAuth() throws Exception {
672 
673         UsernamePasswordCredentials creds = 
674             new UsernamePasswordCredentials("testuser", "testpass");
675         
676         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
677         
678         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
679         handlerchain.appendHandler(new AuthRequestHandler(creds));
680         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
681         
682         this.client.getState().setCredentials(AuthScope.ANY,
683                 new UsernamePasswordCredentials("testuser", "wrongstuff"));
684         
685         this.server.setRequestHandler(handlerchain);
686         
687         this.proxy.requireAuthentication(creds, "test", true);
688 
689         PostMethod post = new PostMethod("/");
690         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
691         try {
692             this.client.executeMethod(post);
693             assertEquals(HttpStatus.SC_UNAUTHORIZED, post.getStatusCode());
694         } finally {
695             post.releaseConnection();
696         }
697     }
698 
699     /**
700      * Tests POST via non-authenticating proxy + interactive host auth + connection keep-alive 
701      */
702     public void testPostInteractiveProxyAuthHostAuthConnKeepAlive() throws Exception {
703         UsernamePasswordCredentials creds = 
704             new UsernamePasswordCredentials("testuser", "testpass");
705         
706         this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
707                 new GetItWrongThenGetItRight());
708         
709         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
710         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
711         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
712         
713         this.server.setRequestHandler(handlerchain);
714         
715         this.proxy.requireAuthentication(creds, "test", true);
716 
717         PostMethod post = new PostMethod("/");
718         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
719         try {
720             this.client.executeMethod(post);
721             assertEquals(HttpStatus.SC_OK, post.getStatusCode());
722             assertNotNull(post.getResponseBodyAsString());
723         } finally {
724             post.releaseConnection();
725         }
726     }
727 
728     /**
729      * Tests POST via non-authenticating proxy + interactive host auth + connection close 
730      */
731     public void testPostInteractiveProxyAuthHostAuthConnClose() throws Exception {
732         UsernamePasswordCredentials creds = 
733             new UsernamePasswordCredentials("testuser", "testpass");
734         
735         this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
736                 new GetItWrongThenGetItRight());
737                 
738         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
739         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
740         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
741         
742         this.server.setRequestHandler(handlerchain);
743         
744         this.proxy.requireAuthentication(creds, "test", true);
745 
746         PostMethod post = new PostMethod("/");
747         post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
748         try {
749             this.client.executeMethod(post);
750             assertEquals(HttpStatus.SC_OK, post.getStatusCode());
751             assertNotNull(post.getResponseBodyAsString());
752         } finally {
753             post.releaseConnection();
754         }
755     }
756 
757     public void testPreemptiveAuthProxy() throws Exception {
758         UsernamePasswordCredentials creds = 
759             new UsernamePasswordCredentials("testuser", "testpass");
760         
761         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
762         this.client.getParams().setAuthenticationPreemptive(true);
763         this.server.setHttpService(new FeedbackService());
764 
765         this.proxy.requireAuthentication(creds, "test", true);
766         
767         GetMethod get = new GetMethod("/");
768         try {
769             this.client.executeMethod(get);
770             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
771             if (isUseSSL()) {
772                 assertNull(get.getRequestHeader("Proxy-Authorization"));
773             } else {
774                 assertNotNull(get.getRequestHeader("Proxy-Authorization"));
775             }
776         } finally {
777             get.releaseConnection();
778         }
779     }
780 
781     /**
782      * Tests GET via authenticating proxy + host auth + HTTP/1.0 
783      */
784     public void testGetProxyAuthHostAuthHTTP10() throws Exception {
785 
786         UsernamePasswordCredentials creds = 
787             new UsernamePasswordCredentials("testuser", "testpass");
788         
789         this.client.getState().setCredentials(AuthScope.ANY, creds);
790         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
791         this.client.getParams().setVersion(HttpVersion.HTTP_1_0);
792         
793         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
794         handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
795         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
796         
797         this.server.setRequestHandler(handlerchain);
798         
799         this.proxy.requireAuthentication(creds, "test", false);
800         
801         GetMethod get = new GetMethod("/");
802         try {
803             this.client.executeMethod(get);
804             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
805         } finally {
806             get.releaseConnection();
807         }
808     }
809     
810 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestProxyWithRedirect.html100644 0 0 33010 10661532627 30257 0ustar 0 0 TestProxyWithRedirect xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestProxyWithRedirect.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  package org.apache.commons.httpclient;
30  
31  import java.io.IOException;
32  
33  import junit.framework.Test;
34  import junit.framework.TestSuite;
35  
36  import org.apache.commons.httpclient.auth.AuthScope;
37  import org.apache.commons.httpclient.methods.GetMethod;
38  import org.apache.commons.httpclient.server.RequestLine;
39  import org.apache.commons.httpclient.server.SimpleRequest;
40  import org.apache.commons.httpclient.server.SimpleResponse;
41  
42  /**
43   * Tests for proxied connections.
44   * 
45   * @author Ortwin Glueck
46   * @author Oleg Kalnichevski
47   */
48  public class TestProxyWithRedirect extends HttpClientTestBase {
49  
50      public TestProxyWithRedirect(String testName) throws IOException {
51          super(testName);
52          setUseProxy(true);
53      }
54  
55      public static Test suite() {
56          return new TestSuite(TestProxyWithRedirect.class);
57      }
58      
59      private class BasicRedirectService extends EchoService {
60          
61          private String location = null;
62  
63          public BasicRedirectService(final String location) {
64              super();
65              this.location = location;
66          }
67  
68          public boolean process(final SimpleRequest request, final SimpleResponse response)
69              throws IOException
70          {
71              RequestLine reqline = request.getRequestLine();
72              HttpVersion ver = reqline.getHttpVersion();
73              if (reqline.getUri().equals("/redirect/")) {
74                  response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY);
75                  response.addHeader(new Header("Location", this.location));
76                  response.addHeader(new Header("Connection", "Close"));
77                  return true;
78              } else {
79                  return super.process(request, response);
80              }
81          }
82      }
83      
84      public void testAuthProxyWithRedirect() throws Exception {
85          UsernamePasswordCredentials creds = 
86              new UsernamePasswordCredentials("testuser", "testpass");
87          
88          this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
89          this.server.setHttpService(new BasicRedirectService("/"));
90          this.proxy.requireAuthentication(creds, "test", true);
91          
92          GetMethod get = new GetMethod("/redirect/");
93          try {
94              this.client.executeMethod(get);
95              assertEquals(HttpStatus.SC_OK, get.getStatusCode());
96          } finally {
97              get.releaseConnection();
98          }
99      }
100     
101     public void testAuthProxyWithCrossSiteRedirect() throws Exception {
102         UsernamePasswordCredentials creds = 
103             new UsernamePasswordCredentials("testuser", "testpass");
104         
105         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
106         this.server.setHttpService(new BasicRedirectService(
107                 "http://127.0.0.1:" + this.server.getLocalPort()));
108 
109         this.proxy.requireAuthentication(creds, "test", true);
110         
111         GetMethod get = new GetMethod("/redirect/");
112         try {
113             this.client.executeMethod(get);
114             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
115         } finally {
116             get.releaseConnection();
117         }
118     }
119 
120     public void testPreemptiveAuthProxyWithCrossSiteRedirect() throws Exception {
121         UsernamePasswordCredentials creds = 
122             new UsernamePasswordCredentials("testuser", "testpass");
123         
124         this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
125         this.client.getParams().setAuthenticationPreemptive(true);
126         this.server.setHttpService(new BasicRedirectService(
127                 "http://127.0.0.1:" + this.server.getLocalPort()));
128 
129         this.proxy.requireAuthentication(creds, "test", true);
130         
131         GetMethod get = new GetMethod("/redirect/");
132         try {
133             this.client.executeMethod(get);
134             assertEquals(HttpStatus.SC_OK, get.getStatusCode());
135         } finally {
136             get.releaseConnection();
137         }
138     }
139     
140 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestQueryParameters.html100644 0 0 55343 10661532627 27766 0ustar 0 0 TestQueryParameters xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestQueryParameters.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient;
31  
32  import java.io.IOException;
33  
34  import junit.framework.*;
35  import org.apache.commons.httpclient.methods.*;
36  import org.apache.commons.httpclient.server.HttpService;
37  import org.apache.commons.httpclient.server.SimpleRequest;
38  import org.apache.commons.httpclient.server.SimpleResponse;
39  
40  /**
41   * @author Rodney Waldhoff
42   * @version $Id: TestQueryParameters.java 480424 2006-11-29 05:56:49Z bayard $
43   */
44  public class TestQueryParameters extends HttpClientTestBase {
45  
46      public TestQueryParameters(String testName) throws Exception {
47          super(testName);
48      }
49  
50      public static Test suite() {
51          TestSuite suite = new TestSuite(TestQueryParameters.class);
52          return suite;
53      }
54  
55      public static void main(String args[]) {
56          String[] testCaseName = { TestQueryParameters.class.getName() };
57          junit.textui.TestRunner.main(testCaseName);
58      }
59  
60      // ------------------------------------------------------------------ Tests
61  
62      class QueryInfoService implements HttpService {
63  
64          public QueryInfoService() {
65              super();
66          }
67  
68          public boolean process(final SimpleRequest request, final SimpleResponse response)
69              throws IOException
70          {
71              HttpVersion httpversion = request.getRequestLine().getHttpVersion();
72              response.setStatusLine(httpversion, HttpStatus.SC_OK);
73              response.addHeader(new Header("Content-Type", "text/plain"));
74  			
75  			URI uri = new URI(request.getRequestLine().getUri(), true);
76  
77              StringBuffer buffer = new StringBuffer();
78              buffer.append("QueryString=\"");
79              buffer.append(uri.getQuery());
80              buffer.append("\"\r\n");
81              response.setBodyString(buffer.toString());
82              return true;
83          }
84      }
85  	
86      /**
87       * Test that {@link GetMethod#setQueryString(java.lang.String)}
88       * can include a leading question mark.
89       */
90      public void testGetMethodQueryString() throws Exception {
91  		this.server.setHttpService(new QueryInfoService());
92          GetMethod method = new GetMethod("/");
93          method.setQueryString("?hadQuestionMark=true");
94  		try {
95  			this.client.executeMethod(method);
96  	        assertEquals(200, method.getStatusCode());
97  			String response = method.getResponseBodyAsString(); 
98  	        assertTrue(response.indexOf("QueryString=\"hadQuestionMark=true\"") >= 0);
99          } finally {
100 			method.releaseConnection();
101         }
102     }
103 
104     /**
105      * Test that {@link GetMethod#setQueryString(java.lang.String)}
106      * doesn't have to include a leading question mark.
107      */
108     public void testGetMethodQueryString2() throws Exception {
109 		this.server.setHttpService(new QueryInfoService());
110         GetMethod method = new GetMethod("/");
111         method.setQueryString("hadQuestionMark=false");
112 		try {
113 			this.client.executeMethod(method);
114 	        assertEquals(200, method.getStatusCode());
115 			String response = method.getResponseBodyAsString(); 
116 	        assertTrue(response.indexOf("QueryString=\"hadQuestionMark=false\"") >= 0);
117         } finally {
118 			method.releaseConnection();
119         }
120     }
121 
122     /**
123      * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)}
124      * values get added to the query string.
125      */
126     public void testGetMethodParameters() throws Exception {
127 		this.server.setHttpService(new QueryInfoService());
128         GetMethod method = new GetMethod("/");
129         method.setQueryString(new NameValuePair[] { new NameValuePair("param-one","param-value") });
130 		try {
131 			this.client.executeMethod(method);
132 	        assertEquals(200, method.getStatusCode());
133 			String response = method.getResponseBodyAsString(); 
134 	        assertTrue(response.indexOf("QueryString=\"param-one=param-value\"") >= 0);
135         } finally {
136 			method.releaseConnection();
137         }
138     }
139 
140     /**
141      * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)}
142      * works with multiple parameters.
143      */
144     public void testGetMethodMultiParameters() throws Exception {
145 		this.server.setHttpService(new QueryInfoService());
146         GetMethod method = new GetMethod("/");
147         method.setQueryString(new NameValuePair[] {
148                                 new NameValuePair("param-one","param-value"),
149                                 new NameValuePair("param-two","param-value2"),
150                                 new NameValuePair("special-chars",":/?~.")
151                               });
152 		try {
153 			this.client.executeMethod(method);
154 	        assertEquals(200, method.getStatusCode());
155 			String response = method.getResponseBodyAsString();
156 	        assertTrue(response.indexOf("QueryString=\"param-one=param-value&param-two=param-value2&special-chars=:/?~.\"") >= 0);
157         } finally {
158 			method.releaseConnection();
159         }
160     }
161 
162     /**
163      * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)}
164      * works with a parameter name but no value.
165      */
166     public void testGetMethodParameterWithoutValue() throws Exception {
167 		this.server.setHttpService(new QueryInfoService());
168         GetMethod method = new GetMethod("/");
169         method.setQueryString(new NameValuePair[] { new NameValuePair("param-without-value", null) });
170 		try {
171 			this.client.executeMethod(method);
172 	        assertEquals(200, method.getStatusCode());
173 			String response = method.getResponseBodyAsString();
174 	        assertTrue(response.indexOf("QueryString=\"param-without-value=\"") >= 0);
175         } finally {
176 			method.releaseConnection();
177         }
178     }
179 
180     /**
181      * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)}
182      * works with a parameter name that occurs more than once.
183      */
184     public void testGetMethodParameterAppearsTwice() throws Exception {
185 		this.server.setHttpService(new QueryInfoService());
186         GetMethod method = new GetMethod("/");
187         method.setQueryString(new NameValuePair[] {
188                                   new NameValuePair("foo","one"),
189                                   new NameValuePair("foo","two")
190                              });
191 		try {
192 			this.client.executeMethod(method);
193 	        assertEquals(200, method.getStatusCode());
194 			String response = method.getResponseBodyAsString();
195 	        assertTrue(response.indexOf("QueryString=\"foo=one&foo=two\"") >= 0);
196         } finally {
197 			method.releaseConnection();
198         }
199     }
200 
201     public void testGetMethodOverwriteQueryString() throws Exception {
202 		this.server.setHttpService(new QueryInfoService());
203         GetMethod method = new GetMethod("/");
204         method.setQueryString("query=string");
205         method.setQueryString(new NameValuePair[] {
206                                   new NameValuePair("param","eter"),
207                                   new NameValuePair("para","meter")
208                              });
209 		try {
210 			this.client.executeMethod(method);
211 	        assertEquals(200, method.getStatusCode());
212 			String response = method.getResponseBodyAsString();
213 	        assertFalse(response.indexOf("QueryString=\"query=string\"") >= 0);
214 	        assertTrue(response.indexOf("QueryString=\"param=eter&para=meter\"") >= 0);
215         } finally {
216 			method.releaseConnection();
217         }
218     }
219 
220     /**
221      * Test that {@link PostMethod#addParameter(java.lang.String,java.lang.String)}
222      * and {@link PostMethod#setQueryString(java.lang.String)} combine
223      * properly.
224      */
225     public void testPostMethodParameterAndQueryString() throws Exception {
226 		this.server.setHttpService(new QueryInfoService());
227         PostMethod method = new PostMethod("/");
228         method.setQueryString("query=string");
229         method.setRequestBody(new NameValuePair[] { 
230            new NameValuePair("param","eter"),
231            new NameValuePair("para","meter") } );
232 		try {
233 			this.client.executeMethod(method);
234 	        assertEquals(200, method.getStatusCode());
235 			String response = method.getResponseBodyAsString();
236 	        assertTrue(response.indexOf("QueryString=\"query=string\"") >= 0);
237 	        assertFalse(response.indexOf("QueryString=\"param=eter&para=meter\"") >= 0);
238         } finally {
239 			method.releaseConnection();
240         }
241     }
242 }
243 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestRedirects.html100644 0 0 142250 10661532627 26573 0ustar 0 0 TestRedirects xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestRedirects.java,v 1.9 2005/01/14 19:40:39 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient;
31  
32  import java.io.IOException;
33  
34  import junit.framework.Test;
35  import junit.framework.TestSuite;
36  
37  import org.apache.commons.httpclient.methods.GetMethod;
38  import org.apache.commons.httpclient.methods.PostMethod;
39  import org.apache.commons.httpclient.methods.StringRequestEntity;
40  import org.apache.commons.httpclient.params.HttpClientParams;
41  import org.apache.commons.httpclient.protocol.Protocol;
42  import org.apache.commons.httpclient.server.HttpService;
43  import org.apache.commons.httpclient.server.RequestLine;
44  import org.apache.commons.httpclient.server.SimpleHttpServer;
45  import org.apache.commons.httpclient.server.SimpleRequest;
46  import org.apache.commons.httpclient.server.SimpleResponse;
47  
48  /**
49   * Redirection test cases.
50   *
51   * @author Oleg Kalnichevski
52   * 
53   * @version $Id: TestRedirects.java 480424 2006-11-29 05:56:49Z bayard $
54   */
55  public class TestRedirects extends HttpClientTestBase {
56  
57      // ------------------------------------------------------------ Constructor
58      public TestRedirects(final String testName) throws IOException {
59          super(testName);
60      }
61  
62      // ------------------------------------------------------------------- Main
63      public static void main(String args[]) {
64          String[] testCaseName = { TestRedirects.class.getName() };
65          junit.textui.TestRunner.main(testCaseName);
66      }
67  
68      // ------------------------------------------------------- TestCase Methods
69  
70      public static Test suite() {
71          TestSuite suite = new TestSuite(TestRedirects.class);
72          ProxyTestDecorator.addTests(suite);
73          return suite;
74      }
75  
76      private class BasicRedirectService implements HttpService {
77  		private int statuscode = HttpStatus.SC_MOVED_TEMPORARILY;
78  		private String host = null;
79          private int port;
80  
81          public BasicRedirectService(final String host, int port, int statuscode) {
82              super();
83              this.host = host;
84              this.port = port;
85              if (statuscode > 0) {
86              	this.statuscode = statuscode;
87              }
88          }
89  
90          public BasicRedirectService(final String host, int port) {
91              this(host, port, -1);
92          }
93  
94          public boolean process(final SimpleRequest request, final SimpleResponse response)
95              throws IOException {
96              RequestLine reqline = request.getRequestLine();
97              HttpVersion ver = reqline.getHttpVersion();
98              if (reqline.getUri().equals("/oldlocation/")) {
99                  response.setStatusLine(ver, this.statuscode);
100                 response.addHeader(new Header("Location", 
101                 		"http://" + this.host + ":" + this.port + "/newlocation/"));
102                 response.addHeader(new Header("Connection", "close"));
103             } else if (reqline.getUri().equals("/newlocation/")) {
104                 response.setStatusLine(ver, HttpStatus.SC_OK);
105                 response.setBodyString("Successful redirect");
106             } else {
107                 response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND);
108             }
109             return true;
110         }
111     }
112 
113     private class CircularRedirectService implements HttpService {
114 
115         private int invocations = 0;
116         
117         public CircularRedirectService() {
118             super();
119         }
120         
121         public boolean process(final SimpleRequest request, final SimpleResponse response)
122             throws IOException
123         {
124             RequestLine reqline = request.getRequestLine();
125             HttpVersion ver = reqline.getHttpVersion();
126             if (reqline.getUri().startsWith("/circular-oldlocation")) {
127                 response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY);
128                 response.addHeader(new Header("Location", "/circular-location2?invk=" + (++this.invocations)));
129             } else if (reqline.getUri().startsWith("/circular-location2")) {
130                 response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY);
131                 response.addHeader(new Header("Location", "/circular-oldlocation?invk=" + (++this.invocations)));
132             } else {
133                 response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND);
134             }
135             return true;
136         }
137     }
138 
139     private class RelativeRedirectService implements HttpService {
140         
141             public RelativeRedirectService() {
142                 super();
143             }
144 
145             public boolean process(final SimpleRequest request, final SimpleResponse response)
146                 throws IOException
147             {
148                 RequestLine reqline = request.getRequestLine();
149                 HttpVersion ver = reqline.getHttpVersion();
150                 if (reqline.getUri().equals("/oldlocation/")) {
151                     response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY);
152                     response.addHeader(new Header("Location", "/relativelocation/"));
153                 } else if (reqline.getUri().equals("/relativelocation/")) {
154                     response.setStatusLine(ver, HttpStatus.SC_OK);
155                     response.setBodyString("Successful redirect");
156                 } else {
157                     response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND);
158                 }
159                 return true;
160             }
161         }
162 
163     private class BogusRedirectService implements HttpService {
164         private String url;
165         
166         public BogusRedirectService(String redirectUrl) {
167             super();
168             this.url = redirectUrl;
169         }
170 
171         public boolean process(final SimpleRequest request, final SimpleResponse response)
172             throws IOException {
173             RequestLine reqline = request.getRequestLine();
174             HttpVersion ver = reqline.getHttpVersion();
175             if (reqline.getUri().equals("/oldlocation/")) {
176                 response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY);
177                 response.addHeader(new Header("Location", url));
178             } else if (reqline.getUri().equals("/relativelocation/")) {
179                 response.setStatusLine(ver, HttpStatus.SC_OK);
180                 response.setBodyString("Successful redirect");
181             } else {
182                 response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND);
183             }
184             return true;
185         }
186     }
187 
188     public void testBasicRedirect300() throws IOException {
189         String host = this.server.getLocalAddress();
190         int port = this.server.getLocalPort();
191         this.server.setHttpService(
192                 new BasicRedirectService(host, port, HttpStatus.SC_MULTIPLE_CHOICES));
193         GetMethod httpget = new GetMethod("/oldlocation/");
194         httpget.setFollowRedirects(false);
195         try {
196             this.client.executeMethod(httpget);
197             assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, httpget.getStatusCode());
198             assertEquals("/oldlocation/", httpget.getPath());
199             assertEquals(new URI("/oldlocation/", false), httpget.getURI());
200         } finally {
201             httpget.releaseConnection();
202         }
203     }
204 
205     public void testBasicRedirect301() throws IOException {
206         String host = this.server.getLocalAddress();
207         int port = this.server.getLocalPort();
208         this.server.setHttpService(
209                 new BasicRedirectService(host, port, HttpStatus.SC_MOVED_PERMANENTLY));
210         GetMethod httpget = new GetMethod("/oldlocation/");
211         httpget.setFollowRedirects(true);
212         try {
213             this.client.executeMethod(httpget);
214             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
215             assertEquals("/newlocation/", httpget.getPath());
216             assertEquals(host, httpget.getURI().getHost());
217             assertEquals(port, httpget.getURI().getPort());
218             assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), httpget.getURI());
219         } finally {
220             httpget.releaseConnection();
221         }
222     }
223 
224     public void testBasicRedirect302() throws IOException {
225         String host = this.server.getLocalAddress();
226         int port = this.server.getLocalPort();
227         this.server.setHttpService(
228                 new BasicRedirectService(host, port, HttpStatus.SC_MOVED_TEMPORARILY));
229         GetMethod httpget = new GetMethod("/oldlocation/");
230         httpget.setFollowRedirects(true);
231         try {
232             this.client.executeMethod(httpget);
233             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
234             assertEquals("/newlocation/", httpget.getPath());
235             assertEquals(host, httpget.getURI().getHost());
236             assertEquals(port, httpget.getURI().getPort());
237             assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), httpget.getURI());
238         } finally {
239             httpget.releaseConnection();
240         }
241     }
242 
243     public void testBasicRedirect303() throws IOException {
244         String host = this.server.getLocalAddress();
245         int port = this.server.getLocalPort();
246         this.server.setHttpService(
247                 new BasicRedirectService(host, port, HttpStatus.SC_SEE_OTHER));
248         GetMethod httpget = new GetMethod("/oldlocation/");
249         httpget.setFollowRedirects(true);
250         try {
251             this.client.executeMethod(httpget);
252             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
253             assertEquals("/newlocation/", httpget.getPath());
254             assertEquals(host, httpget.getURI().getHost());
255             assertEquals(port, httpget.getURI().getPort());
256             assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), httpget.getURI());
257         } finally {
258             httpget.releaseConnection();
259         }
260     }
261 
262     public void testBasicRedirect304() throws IOException {
263         String host = this.server.getLocalAddress();
264         int port = this.server.getLocalPort();
265         this.server.setHttpService(
266                 new BasicRedirectService(host, port, HttpStatus.SC_NOT_MODIFIED));
267         GetMethod httpget = new GetMethod("/oldlocation/");
268         httpget.setFollowRedirects(true);
269         try {
270             this.client.executeMethod(httpget);
271             assertEquals(HttpStatus.SC_NOT_MODIFIED, httpget.getStatusCode());
272             assertEquals("/oldlocation/", httpget.getPath());
273             assertEquals(new URI("/oldlocation/", false), httpget.getURI());
274         } finally {
275             httpget.releaseConnection();
276         }
277     }
278 
279     public void testBasicRedirect305() throws IOException {
280         String host = this.server.getLocalAddress();
281         int port = this.server.getLocalPort();
282         this.server.setHttpService(
283                 new BasicRedirectService(host, port, HttpStatus.SC_USE_PROXY));
284         GetMethod httpget = new GetMethod("/oldlocation/");
285         httpget.setFollowRedirects(true);
286         try {
287             this.client.executeMethod(httpget);
288             assertEquals(HttpStatus.SC_USE_PROXY, httpget.getStatusCode());
289             assertEquals("/oldlocation/", httpget.getPath());
290             assertEquals(new URI("/oldlocation/", false), httpget.getURI());
291         } finally {
292             httpget.releaseConnection();
293         }
294     }
295 
296     public void testBasicRedirect307() throws IOException {
297         String host = this.server.getLocalAddress();
298         int port = this.server.getLocalPort();
299         this.server.setHttpService(
300                 new BasicRedirectService(host, port, HttpStatus.SC_TEMPORARY_REDIRECT));
301         GetMethod httpget = new GetMethod("/oldlocation/");
302         httpget.setFollowRedirects(true);
303         try {
304             this.client.executeMethod(httpget);
305             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
306             assertEquals("/newlocation/", httpget.getPath());
307             assertEquals(host, httpget.getURI().getHost());
308             assertEquals(port, httpget.getURI().getPort());
309             assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), httpget.getURI());
310         } finally {
311             httpget.releaseConnection();
312         }
313     }
314 
315     public void testNoRedirect() throws IOException {
316         String host = this.server.getLocalAddress();
317         int port = this.server.getLocalPort();
318         this.server.setHttpService(new BasicRedirectService(host, port));
319         GetMethod httpget = new GetMethod("/oldlocation/");
320         httpget.setFollowRedirects(false);
321         try {
322             this.client.executeMethod(httpget);
323             assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, httpget.getStatusCode());
324             assertEquals("/oldlocation/", httpget.getPath());
325             assertEquals(new URI("/oldlocation/", false), httpget.getURI());
326         } finally {
327             httpget.releaseConnection();
328         }
329     }
330 
331     public void testMaxRedirectCheck() throws IOException {
332         this.server.setHttpService(new CircularRedirectService());
333         GetMethod httpget = new GetMethod("/circular-oldlocation/");
334         try {
335             this.client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
336             this.client.getParams().setIntParameter(HttpClientParams.MAX_REDIRECTS, 5);
337             this.client.executeMethod(httpget);
338             fail("RedirectException exception should have been thrown");
339         }
340         catch (RedirectException e) {
341             // expected
342         } finally {
343             httpget.releaseConnection();
344         }
345     }
346 
347     public void testCircularRedirect() throws IOException {
348         this.server.setHttpService(new CircularRedirectService());
349         GetMethod httpget = new GetMethod("/circular-oldlocation/");
350         try {
351             this.client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, false);
352             this.client.executeMethod(httpget);
353             fail("CircularRedirectException exception should have been thrown");
354         } catch (CircularRedirectException expected) {
355         } finally {
356             httpget.releaseConnection();
357         }
358     }
359 
360     public void testPostRedirect() throws IOException {
361         String host = this.server.getLocalAddress();
362         int port = this.server.getLocalPort();
363         this.server.setHttpService(new BasicRedirectService(host, port));
364         PostMethod httppost = new PostMethod("/oldlocation/");
365         httppost.setRequestEntity(new StringRequestEntity("stuff", null, null));
366         try {
367             this.client.executeMethod(httppost);
368             assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, httppost.getStatusCode());
369             assertEquals("/oldlocation/", httppost.getPath());
370             assertEquals(new URI("/oldlocation/", false), httppost.getURI());
371         } finally {
372         	httppost.releaseConnection();
373         }
374     }
375 
376     public void testRelativeRedirect() throws IOException {
377         String host = this.server.getLocalAddress();
378         int port = this.server.getLocalPort();
379         this.server.setHttpService(new RelativeRedirectService());
380         this.client.getParams().setBooleanParameter(
381                 HttpClientParams.REJECT_RELATIVE_REDIRECT, false);
382         GetMethod httpget = new GetMethod("/oldlocation/");
383         httpget.setFollowRedirects(true);
384         try {
385             this.client.executeMethod(httpget);
386             assertEquals("/relativelocation/", httpget.getPath());
387             assertEquals(host, httpget.getURI().getHost());
388             assertEquals(port, httpget.getURI().getPort());
389             assertEquals(new URI("http://" + host + ":" + port + "/relativelocation/", false), 
390             		httpget.getURI());
391         } finally {
392             httpget.releaseConnection();
393         }
394     }
395 
396     public void testRejectRelativeRedirect() throws IOException {
397         String host = this.server.getLocalAddress();
398         int port = this.server.getLocalPort();
399         this.server.setHttpService(new RelativeRedirectService());
400         this.client.getParams().setBooleanParameter(
401                 HttpClientParams.REJECT_RELATIVE_REDIRECT, true);
402         GetMethod httpget = new GetMethod("/oldlocation/");
403         httpget.setFollowRedirects(true);
404         try {
405             this.client.executeMethod(httpget);
406             assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, httpget.getStatusCode());
407             assertEquals("/oldlocation/", httpget.getPath());
408             assertEquals(new URI("/oldlocation/", false), httpget.getURI());
409         } finally {
410             httpget.releaseConnection();
411         }
412     }
413 
414     public void testRejectBogusRedirectLocation() throws IOException {
415         String host = this.server.getLocalAddress();
416         int port = this.server.getLocalPort();
417         this.server.setHttpService(new BogusRedirectService("xxx://bogus"));
418         GetMethod httpget = new GetMethod("/oldlocation/");
419         httpget.setFollowRedirects(true);
420         try {
421             this.client.executeMethod(httpget);
422             fail("BogusRedirectService should have been thrown");
423         } catch (IllegalStateException e) {
424         	//expected
425         } finally {
426             httpget.releaseConnection();
427         }
428     }
429 
430     public void testRejectInvalidRedirectLocation() throws IOException {
431         String host = this.server.getLocalAddress();
432         int port = this.server.getLocalPort();
433         this.server.setHttpService(new BogusRedirectService("http://"+ host +":"+ port +"/newlocation/?p=I have spaces"));
434         GetMethod httpget = new GetMethod("/oldlocation/");
435         httpget.setFollowRedirects(true);
436         try {
437             this.client.executeMethod(httpget);
438             fail("InvalidRedirectLocationException should have been thrown");
439         } catch (InvalidRedirectLocationException e) {
440             //expected a protocol exception
441         } finally {
442             httpget.releaseConnection();
443         }
444     }
445 
446     public void testCrossSiteRedirect() throws IOException {
447         String host = this.server.getLocalAddress();
448         int port = this.server.getLocalPort();
449         
450         SimpleHttpServer thatserver = new SimpleHttpServer();
451         this.server.setHttpService(new BasicRedirectService(host, port));
452         thatserver.setHttpService(new BasicRedirectService(host, port));
453         thatserver.setTestname(getName());
454         
455         HostConfiguration hostconfig = new HostConfiguration();
456         hostconfig.setHost(
457                 thatserver.getLocalAddress(), 
458                 thatserver.getLocalPort(),
459                 Protocol.getProtocol("http"));
460 
461         GetMethod httpget = new GetMethod("/oldlocation/");
462         httpget.setFollowRedirects(true);
463         try {
464             this.client.executeMethod(hostconfig, httpget);
465             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
466             assertEquals("/newlocation/", httpget.getPath());
467             assertEquals(host, httpget.getURI().getHost());
468             assertEquals(port, httpget.getURI().getPort());
469             assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), 
470             		httpget.getURI());
471         } finally {
472             httpget.releaseConnection();
473         }
474         thatserver.destroy();
475     }
476 
477     public void testRedirectWithCookie() throws IOException {
478     	
479         client.getState().addCookie(new Cookie("localhost", "name", "value", "/", -1, false)); 
480 
481         String host = this.server.getLocalAddress();
482         int port = this.server.getLocalPort();
483 
484         this.server.setHttpService(new BasicRedirectService(host, port));
485         GetMethod httpget = new GetMethod("/oldlocation/");
486         httpget.setFollowRedirects(true);
487         try {
488             this.client.executeMethod(httpget);
489             assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
490             assertEquals("/newlocation/", httpget.getPath());
491 
492             Header[] headers = httpget.getRequestHeaders();
493             int cookiecount = 0;
494             for (int i = 0; i < headers.length; i++) {
495                 if ("cookie".equalsIgnoreCase(headers[i].getName())) {
496                     ++cookiecount;
497                 }
498             }
499             assertEquals("There can only be one (cookie)", 1, cookiecount);            
500         } finally {
501             httpget.releaseConnection();
502         }
503     }
504 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestRequestHeaders.html100644 0 0 31560 10661532627 27554 0ustar 0 0 TestRequestHeaders xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestRequestHeaders.java,v 1.8 2004/10/31 14:04:13 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import org.apache.commons.httpclient.protocol.Protocol;
35  
36  import junit.framework.Test;
37  import junit.framework.TestCase;
38  import junit.framework.TestSuite;
39  
40  /**
41   * Tests for reading response headers.
42   *
43   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
44   * @version $Id: TestRequestHeaders.java 480424 2006-11-29 05:56:49Z bayard $
45   */
46  public class TestRequestHeaders extends TestCase {
47  
48      // ------------------------------------------------------------ Constructor
49      public TestRequestHeaders(String testName) {
50          super(testName);
51      }
52  
53      // ------------------------------------------------------------------- Main
54      public static void main(String args[]) {
55          String[] testCaseName = {TestRequestHeaders.class.getName()};
56          junit.textui.TestRunner.main(testCaseName);
57      }
58  
59      // ------------------------------------------------------- TestCase Methods
60      public static Test suite() {
61          return new TestSuite(TestRequestHeaders.class);
62      }
63  
64      public void testNullHeader() throws Exception {
65          FakeHttpMethod method = new FakeHttpMethod();
66          assertEquals(null, method.getRequestHeader(null));
67          assertEquals(null, method.getRequestHeader("bogus"));
68      }
69  
70      public void testHostHeaderPortHTTP80() throws Exception {
71          HttpConnection conn = new HttpConnection("some.host.name", 80);
72          HttpState state = new HttpState();
73          FakeHttpMethod method = new FakeHttpMethod();
74          method.addRequestHeaders(state, conn);
75          assertEquals("Host: some.host.name", method.getRequestHeader("Host").toString().trim());
76      }
77  
78      public void testHostHeaderPortHTTP81() throws Exception {
79          HttpConnection conn = new HttpConnection("some.host.name", 81);
80          HttpState state = new HttpState();
81          FakeHttpMethod method = new FakeHttpMethod();
82          method.addRequestHeaders(state, conn);
83          assertEquals("Host: some.host.name:81", method.getRequestHeader("Host").toString().trim());
84      }
85  
86      public void testHostHeaderPortHTTPS443() throws Exception {
87          HttpConnection conn = new HttpConnection("some.host.name", 443, 
88                  Protocol.getProtocol("https"));
89          HttpState state = new HttpState();
90          FakeHttpMethod method = new FakeHttpMethod();
91          method.addRequestHeaders(state, conn);
92          assertEquals("Host: some.host.name", method.getRequestHeader("Host").toString().trim());
93      }
94  
95      public void testHostHeaderPortHTTPS444() throws Exception {
96          HttpConnection conn = new HttpConnection("some.host.name", 444, 
97                  Protocol.getProtocol("https"));
98          HttpState state = new HttpState();
99          FakeHttpMethod method = new FakeHttpMethod();
100         method.addRequestHeaders(state, conn);
101         assertEquals("Host: some.host.name:444", method.getRequestHeader("Host").toString().trim());
102     }
103 
104     public void testHeadersPreserveCaseKeyIgnoresCase() throws Exception {
105         FakeHttpMethod method = new FakeHttpMethod();
106         method.addRequestHeader(new Header("NAME", "VALUE"));
107         Header upHeader =  method.getRequestHeader("NAME");
108         Header loHeader =  method.getRequestHeader("name");
109         Header mixHeader =  method.getRequestHeader("nAmE");
110         assertEquals("NAME", upHeader.getName());
111         assertEquals("VALUE", upHeader.getValue());
112         assertEquals("NAME", loHeader.getName());
113         assertEquals("VALUE", loHeader.getValue());
114         assertEquals("NAME", mixHeader.getName());
115         assertEquals("VALUE", mixHeader.getValue());
116     }
117 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestRequestLine.html100644 0 0 31765 10661532627 27077 0ustar 0 0 TestRequestLine xref

1   /*
2    * ====================================================================
3    *
4    *  Licensed to the Apache Software Foundation (ASF) under one or more
5    *  contributor license agreements.  See the NOTICE file distributed with
6    *  this work for additional information regarding copyright ownership.
7    *  The ASF licenses this file to You under the Apache License, Version 2.0
8    *  (the "License"); you may not use this file except in compliance with
9    *  the License.  You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   *  Unless required by applicable law or agreed to in writing, software
14   *  distributed under the License is distributed on an "AS IS" BASIS,
15   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   *  See the License for the specific language governing permissions and
17   *  limitations under the License.
18   * ====================================================================
19   *
20   * This software consists of voluntary contributions made by many
21   * individuals on behalf of the Apache Software Foundation.  For more
22   * information on the Apache Software Foundation, please see
23   * <http://www.apache.org/>.
24   */
25  
26  package org.apache.commons.httpclient;
27  
28  
29  import org.apache.commons.httpclient.protocol.Protocol; 
30  import junit.framework.*;
31  
32  /**
33   * Simple tests for {@link StatusLine}.
34   *
35   * @author <a href="mailto:oleg@ural.ru">oleg Kalnichevski</a>
36   * @version $Id: TestRequestLine.java 480424 2006-11-29 05:56:49Z bayard $
37   */
38  public class TestRequestLine extends TestCase {
39  
40      // ------------------------------------------------------------ Constructor
41      public TestRequestLine(String testName) {
42          super(testName);
43      }
44  
45      // ------------------------------------------------------------------- Main
46      public static void main(String args[]) {
47          String[] testCaseName = { TestRequestLine.class.getName() };
48          junit.textui.TestRunner.main(testCaseName);
49      }
50  
51      // ------------------------------------------------------- TestCase Methods
52  
53      public static Test suite() {
54          return new TestSuite(TestRequestLine.class);
55      }
56  
57      // ----------------------------------------------------------- Test Methods
58  
59      public void testRequestLineGeneral() throws Exception {
60          
61          HttpConnection conn = new HttpConnection("localhost", 80);
62          FakeHttpMethod method = new FakeHttpMethod();
63          assertEquals("Simple / HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1));
64  
65          method = new FakeHttpMethod("stuff");
66          assertEquals("Simple stuff HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1));
67  
68          conn = new HttpConnection("proxy", 8080, "localhost", 80, Protocol.getProtocol("http"));
69  
70          method = new FakeHttpMethod();
71          assertEquals("Simple http://localhost/ HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1));
72  
73          method = new FakeHttpMethod("stuff");
74          assertEquals("Simple http://localhost/stuff HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1));
75  
76          conn = new HttpConnection("proxy", 8080, "localhost", -1, Protocol.getProtocol("http"));
77  
78          method = new FakeHttpMethod();
79          assertEquals("Simple http://localhost/ HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1));
80  
81          method = new FakeHttpMethod("stuff");
82          assertEquals("Simple http://localhost/stuff HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1));
83  
84          conn = new HttpConnection("proxy", 8080, "localhost", 666, Protocol.getProtocol("http"));
85  
86          method = new FakeHttpMethod();
87          assertEquals("Simple http://localhost:666/ HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1));
88  
89          method = new FakeHttpMethod("stuff");
90          assertEquals("Simple http://localhost:666/stuff HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1));
91      }
92  
93      public void testRequestLineQuery() throws Exception {
94          HttpConnection conn = new HttpConnection("localhost", 80);
95  
96          FakeHttpMethod method = new FakeHttpMethod();
97          method.setQueryString( new NameValuePair[] {
98              new NameValuePair("param1", " !#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~"),
99              new NameValuePair("param2", "some stuff")
100           } );
101         assertEquals("Simple /?param1=+%21%23%24%25%26%27%28%29*%2B%2C-.%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E_%60%7B%7C%7D%7E&param2=some+stuff HTTP/1.1\r\n", 
102                 method.generateRequestLine(conn, HttpVersion.HTTP_1_1));
103     }
104 
105     public void testRequestLinePath() throws Exception {
106         HttpConnection conn = new HttpConnection("localhost", 80);
107 
108         FakeHttpMethod method = new FakeHttpMethod();
109         method.setPath("/some%20stuff/");
110         assertEquals("Simple /some%20stuff/ HTTP/1.1\r\n", 
111                 method.generateRequestLine(conn, HttpVersion.HTTP_1_1));
112 
113         method = new FakeHttpMethod("/some%20stuff/");
114         assertEquals("Simple /some%20stuff/ HTTP/1.1\r\n", 
115                 method.generateRequestLine(conn, HttpVersion.HTTP_1_1));
116     }
117 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestResponseHeaders.html100644 0 0 130040 10661532627 27733 0ustar 0 0 TestResponseHeaders xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestResponseHeaders.java,v 1.18 2004/11/07 12:31:42 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import java.io.IOException;
35  
36  import junit.framework.Test;
37  import junit.framework.TestSuite;
38  
39  import org.apache.commons.httpclient.methods.GetMethod;
40  import org.apache.commons.httpclient.server.HttpRequestHandler;
41  import org.apache.commons.httpclient.server.HttpService;
42  import org.apache.commons.httpclient.server.ResponseWriter;
43  import org.apache.commons.httpclient.server.SimpleHttpServerConnection;
44  import org.apache.commons.httpclient.server.SimpleRequest;
45  import org.apache.commons.httpclient.server.SimpleResponse;
46  
47  /**
48   * Tests for reading response headers.
49   *
50   * @author <a href="mailto:dims@apache.org">Davanum Srinivas</a>
51   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
52   * @author <a href="mailto:adrian@intencha.com">Adrian Sutton</a>
53   * @version $Id: TestResponseHeaders.java 480424 2006-11-29 05:56:49Z bayard $
54   */
55  public class TestResponseHeaders extends HttpClientTestBase {
56  
57      private AccessibleHttpConnectionManager connectionManager;
58      
59      // ------------------------------------------------------------ Constructor
60      public TestResponseHeaders(final String testName) throws IOException {
61          super(testName);
62      }
63      
64      public void setUp() throws IOException {
65          super.setUp();
66          this.connectionManager = new AccessibleHttpConnectionManager();
67          this.client.setHttpConnectionManager(connectionManager);
68      }
69  
70      // ------------------------------------------------------------------- Main
71      public static void main(String args[]) {
72          String[] testCaseName = {TestResponseHeaders.class.getName()};
73          junit.textui.TestRunner.main(testCaseName);
74      }
75  
76      // ------------------------------------------------------- TestCase Methods
77      public static Test suite() {
78          return new TestSuite(TestResponseHeaders.class);
79      }
80  
81      // ----------------------------------------------------------- Test Methods
82      public void testHeaders() throws Exception {
83          final String body = "XXX\r\nYYY\r\nZZZ";
84          this.server.setHttpService(new HttpService() {
85              public boolean process(SimpleRequest request,
86                      SimpleResponse response) throws IOException {
87                  response.setStatusLine(request.getRequestLine().getHttpVersion(), 200);
88                  response.addHeader(new Header("Connection", "close"));
89                  response.addHeader(new Header("Content-Length", Integer.toString(body.length())));
90                  response.addHeader(new Header("Content-Type", "text/xml; charset=utf-8"));
91                  response.addHeader(new Header("Date", "Wed, 28 Mar 2001 05:05:04 GMT"));
92                  response.addHeader(new Header("Server", "UserLand Frontier/7.0-WinNT"));
93                  response.setBodyString(body);
94                  return true;
95              }
96          });
97          
98          HttpMethod method = new GetMethod();
99          client.executeMethod(method);
100         assertEquals("close", method.getResponseHeader("Connection").getValue());
101         assertEquals(body.length(), Integer.parseInt(method.getResponseHeader("Content-Length").getValue()));
102         assertEquals("text/xml; charset=utf-8", method.getResponseHeader("Content-Type").getValue());
103         assertEquals("Wed, 28 Mar 2001 05:05:04 GMT", method.getResponseHeader("Date").getValue());
104         assertEquals("UserLand Frontier/7.0-WinNT", method.getResponseHeader("Server").getValue());
105     }
106 
107     /**
108      * Tests that having a duplicate content length causes no problems.
109      */    
110     public void testDuplicateContentLength() throws Exception {
111         
112         final String body = "XXX\r\nYYY\r\nZZZ";
113         this.server.setHttpService(new HttpService() {
114             public boolean process(SimpleRequest request,
115                     SimpleResponse response) throws IOException {
116                 response.setStatusLine(request.getRequestLine().getHttpVersion(), 200);
117                 response.addHeader(new Header("Content-Length", Integer.toString(body.length())));
118                 response.addHeader(new Header("Content-Length", Integer.toString(body.length())));
119                 response.setBodyString(body);
120                 return true;
121             }
122         });
123         HttpMethod method = new GetMethod();
124         client.executeMethod(method);
125         assertNotNull( "Response body is null.", method.getResponseBodyAsStream() );
126     }
127 
128     public void testDuplicateConnection() throws Exception {
129         
130         this.server.setHttpService(new HttpService() {
131             public boolean process(SimpleRequest request,
132                     SimpleResponse response) throws IOException {
133                 response.setStatusLine(request.getRequestLine().getHttpVersion(), 200);
134                 response.addHeader(new Header("Connection", "close"));
135                 response.addHeader(new Header("Connection", "close"));
136                 return true;
137             }
138         });
139 
140         GetMethod method = new GetMethod("/");
141         client.executeMethod(method);
142         method.getResponseBodyAsString();
143         
144         assertFalse(connectionManager.getConection().isOpen());
145 
146         this.server.setHttpService(new HttpService() {
147             public boolean process(SimpleRequest request,
148                     SimpleResponse response) throws IOException {
149                 response.setStatusLine(HttpVersion.HTTP_1_0, 200);
150                 response.addHeader(new Header("Connection", "keep-alive"));
151                 response.addHeader(new Header("Connection", "keep-alive"));
152                 response.setBodyString("aa");
153                 return true;
154             }
155         });
156 
157         method = new GetMethod("/");
158         client.executeMethod(method);
159         method.getResponseBodyAsString();
160         
161         assertTrue(connectionManager.getConection().isOpen());
162     }
163     
164     public void testNoContentLength() throws Exception {
165         // test with connection header
166         this.server.setRequestHandler(new HttpRequestHandler() {
167             public boolean processRequest(SimpleHttpServerConnection conn,
168                     SimpleRequest request) throws IOException {
169                 ResponseWriter out = conn.getWriter();
170                 out.println("HTTP/1.1 200 OK");
171                 out.println("Connection: keep-alive");
172                 out.println();
173                 out.println("12345");
174                 out.flush();
175                 return true;
176             }
177         });
178 
179         GetMethod method = new GetMethod("/");
180         client.executeMethod(method);
181         method.getResponseBodyAsString();
182         
183         assertFalse(connectionManager.getConection().isOpen());
184         
185         // test without connection header
186         this.server.setRequestHandler(new HttpRequestHandler() {
187             public boolean processRequest(SimpleHttpServerConnection conn,
188                     SimpleRequest request) throws IOException {
189                 ResponseWriter out = conn.getWriter();
190                 out.println("HTTP/1.1 200 OK");
191                 out.println();
192                 out.println("12345");
193                 out.flush();
194                 return true;
195             }
196         });
197 
198         // test with connection header
199         method = new GetMethod("/");
200         client.executeMethod(method);
201         method.getResponseBodyAsString();
202         
203         assertFalse(connectionManager.getConection().isOpen());
204     }
205 
206     public void testInvalidContentLength1() throws Exception {
207         this.server.setHttpService(new HttpService() {
208             public boolean process(SimpleRequest request,
209                     SimpleResponse response) throws IOException {
210                 response.setStatusLine(request.getRequestLine().getHttpVersion(), 200);
211                 response.addHeader(new Header("Content-Length", "5"));
212                 response.addHeader(new Header("Content-Length", "stuff"));
213                 response.setBodyString("12345");
214                 return true;
215             }
216         });
217         GetMethod method = new GetMethod("/");
218         client.executeMethod(method);
219         assertEquals(5, method.getResponseContentLength()); 
220     }
221 
222     public void testInvalidContentLength2() throws Exception {
223         this.server.setHttpService(new HttpService() {
224             public boolean process(SimpleRequest request,
225                     SimpleResponse response) throws IOException {
226                 response.setStatusLine(request.getRequestLine().getHttpVersion(), 200);
227                 response.addHeader(new Header("Content-Length", "stuff"));
228                 response.addHeader(new Header("Content-Length", "5"));
229                 response.setBodyString("12345");
230                 return true;
231             }
232         });
233         GetMethod method = new GetMethod("/");
234         client.executeMethod(method);
235         assertEquals(5, method.getResponseContentLength()); 
236     }
237 
238     public void testProxyNoContentLength() throws Exception {
239         // test with proxy-connection header
240         this.server.setRequestHandler(new HttpRequestHandler() {
241             public boolean processRequest(SimpleHttpServerConnection conn,
242                     SimpleRequest request) throws IOException {
243                 ResponseWriter out = conn.getWriter();
244                 out.println("HTTP/1.1 200 OK");
245                 out.println("proxy-connection: keep-alive");
246                 out.println();
247                 out.println("12345");
248                 out.flush();
249                 return true;
250             }
251         });
252 
253         client.getHostConfiguration().setProxy(server.getLocalAddress(), server.getLocalPort());
254         GetMethod method = new GetMethod("/");
255         client.executeMethod(method);
256         method.getResponseBodyAsString();
257         
258         assertFalse(connectionManager.getConection().isOpen());
259 
260         // test without proxy-connection header
261         this.server.setRequestHandler(new HttpRequestHandler() {
262             public boolean processRequest(SimpleHttpServerConnection conn,
263                     SimpleRequest request) throws IOException {
264                 ResponseWriter out = conn.getWriter();
265                 out.println("HTTP/1.1 200 OK");
266                 out.println();
267                 out.println("12345");
268                 out.flush();
269                 return true;
270             }
271         });
272 
273         method = new GetMethod("/");
274         client.executeMethod(method);
275         method.getResponseBodyAsString();
276         
277         assertFalse(connectionManager.getConection().isOpen());
278     }
279 
280     public void testNullHeaders() throws Exception {
281         this.server.setHttpService(new HttpService() {
282             public boolean process(SimpleRequest request,
283                     SimpleResponse response) throws IOException {
284                 response.setStatusLine(request.getRequestLine().getHttpVersion(), 200);
285                 response.addHeader(new Header("Connection", "close"));
286                 response.setBodyString("XXX\r\nYYY\r\nZZZ");
287                 return true;
288             }
289         });
290         HttpMethod method = new GetMethod("/");
291         client.executeMethod(method);
292         assertEquals(null, method.getResponseHeader(null));
293         assertEquals(null, method.getResponseHeader("bogus"));
294     }
295     
296     public void testFoldedHeaders() throws Exception {
297         final String body = "XXX\r\nYYY\r\nZZZ";
298         this.server.setRequestHandler(new HttpRequestHandler() {
299             public boolean processRequest(SimpleHttpServerConnection conn,
300                     SimpleRequest request) throws IOException {
301                 ResponseWriter out = conn.getWriter();
302                 out.println("HTTP/1.1 200 OK");
303                 out.println("Connection: close");
304                 out.println("Content-Length: " + body.length());
305                 out.println("Content-Type: text/xml; charset=utf-8");
306                 out.println("\tboundary=XXXX");
307                 out.println("Date: Wed, 28 Mar 2001");
308                 out.println(" 05:05:04 GMT");
309                 out.println("Server: UserLand Frontier/7.0-WinNT");
310                 out.println();
311                 out.println(body);
312                 out.flush();
313                 return true;
314             }
315         });
316         HttpMethod method = new GetMethod("/");
317         client.executeMethod(method);
318         assertEquals("close", method.getResponseHeader("Connection").getValue());
319         assertEquals(body.length(), Integer.parseInt(method.getResponseHeader("Content-Length").getValue()));
320         assertEquals("text/xml; charset=utf-8 boundary=XXXX", method.getResponseHeader("Content-Type").getValue());
321         assertEquals("Wed, 28 Mar 2001 05:05:04 GMT", method.getResponseHeader("Date").getValue());
322         assertEquals("UserLand Frontier/7.0-WinNT", method.getResponseHeader("Server").getValue());
323         assertTrue(method.getResponseHeader("Content-Type").toString().indexOf("boundary") != -1);
324     }
325 
326 
327 	public void testForceCloseConnection() throws Exception {
328         this.server.setRequestHandler(new HttpRequestHandler() {
329             public boolean processRequest(SimpleHttpServerConnection conn,
330                     SimpleRequest request) throws IOException {
331                 ResponseWriter out = conn.getWriter();
332                 out.println("HTTP/1.1 200 OK");
333                 out.println("Content-Type: garbage");
334                 out.println();
335                 out.println("stuff");
336                 out.flush();
337                 return true;
338             }
339         });
340         FakeHttpMethod method = new FakeHttpMethod();
341         client.executeMethod(method);
342 		assertTrue("Connection should be closed", 
343                 method.shouldCloseConnection(connectionManager.getConection()));
344 		assertTrue("Connection should be force-closed", method.isConnectionCloseForced());
345 	}
346     
347 	public void testForceCloseConnection2() throws Exception {
348         this.server.setRequestHandler(new HttpRequestHandler() {
349             public boolean processRequest(SimpleHttpServerConnection conn,
350                     SimpleRequest request) throws IOException {
351                 ResponseWriter out = conn.getWriter();
352                 out.println("HTTP/1.1 200 OK");
353                 out.println("Content-Type: garbage");
354                 out.println("Connection: close");
355                 out.println();
356                 out.println("stuff");
357                 out.flush();
358                 return true;
359             }
360         });
361         FakeHttpMethod method = new FakeHttpMethod();
362         client.executeMethod(method);
363 		assertTrue("Connection should be closed", 
364                 method.shouldCloseConnection(connectionManager.getConection()));
365 		assertFalse("Connection should NOT be closed", method.isConnectionCloseForced());
366 	}
367     
368     public void testNoContent() throws Exception {
369         // test with connection header
370         this.server.setRequestHandler(new HttpRequestHandler() {
371             public boolean processRequest(SimpleHttpServerConnection conn,
372                     SimpleRequest request) throws IOException {
373                 ResponseWriter out = conn.getWriter();
374                 out.println("HTTP/1.1 204 NO CONTENT");
375                 out.println();
376                 out.flush();
377                 return true;
378             }
379         });
380 
381         GetMethod method = new GetMethod("/");
382         client.executeMethod(method);
383         method.getResponseBodyAsString();
384 
385         assertTrue(connectionManager.getConection().isOpen());
386 
387         // test without connection header
388         this.server.setRequestHandler(new HttpRequestHandler() {
389             public boolean processRequest(SimpleHttpServerConnection conn,
390                     SimpleRequest request) throws IOException {
391                 ResponseWriter out = conn.getWriter();
392                 out.println("HTTP/1.1 204 NO CONTENT");
393                 out.println("Connection: keep-alive");
394                 out.println();
395                 out.flush();
396                 return true;
397             }
398         });
399 
400         // test with connection header
401         method = new GetMethod("/");
402         client.executeMethod(method);
403         method.getResponseBodyAsString();
404 
405         assertTrue(connectionManager.getConection().isOpen());
406     }
407     
408 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestStatusLine.html100644 0 0 34601 10661532627 26722 0ustar 0 0 TestStatusLine xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestStatusLine.java,v 1.9 2004/07/19 20:24:21 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import junit.framework.*;
35  
36  /**
37   * Simple tests for {@link StatusLine}.
38   *
39   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
40   * @version $Id: TestStatusLine.java 480424 2006-11-29 05:56:49Z bayard $
41   */
42  public class TestStatusLine extends TestCase {
43  
44      private StatusLine statusLine = null;
45  
46      // ------------------------------------------------------------ Constructor
47      public TestStatusLine(String testName) {
48          super(testName);
49      }
50  
51      // ------------------------------------------------------------------- Main
52      public static void main(String args[]) {
53          String[] testCaseName = { TestStatusLine.class.getName() };
54          junit.textui.TestRunner.main(testCaseName);
55      }
56  
57      // ------------------------------------------------------- TestCase Methods
58  
59      public static Test suite() {
60          return new TestSuite(TestStatusLine.class);
61      }
62  
63      // ------------------------------------------------------ Protected Methods
64  
65  
66      // ----------------------------------------------------------- Test Methods
67  
68      public void testIfStatusLine() throws Exception {
69          assertTrue(StatusLine.startsWithHTTP("HTTP"));
70          assertTrue(StatusLine.startsWithHTTP("         HTTP"));
71          assertTrue(StatusLine.startsWithHTTP("\rHTTP"));
72          assertTrue(StatusLine.startsWithHTTP("\tHTTP"));
73          assertFalse(StatusLine.startsWithHTTP("crap"));
74          assertFalse(StatusLine.startsWithHTTP("HTT"));
75          assertFalse(StatusLine.startsWithHTTP("http"));
76      }
77  
78      public void testSuccess() throws Exception {
79          //typical status line
80          statusLine = new StatusLine("HTTP/1.1 200 OK");
81          assertEquals("HTTP/1.1 200 OK", statusLine.toString());
82          assertEquals("HTTP/1.1", statusLine.getHttpVersion());
83          assertEquals(200, statusLine.getStatusCode());
84          assertEquals("OK", statusLine.getReasonPhrase());
85  
86          //status line with multi word reason phrase
87          statusLine = new StatusLine("HTTP/1.1 404 Not Found");
88          assertEquals(404, statusLine.getStatusCode());
89          assertEquals("Not Found", statusLine.getReasonPhrase());
90  
91          //reason phrase can be anyting
92          statusLine = new StatusLine("HTTP/1.1 404 Non Trouve");
93          assertEquals("Non Trouve", statusLine.getReasonPhrase());
94  
95          //its ok to end with a \n\r
96          statusLine = new StatusLine("HTTP/1.1 404 Not Found\r\n");
97          assertEquals("Not Found", statusLine.getReasonPhrase());
98  
99          //this is valid according to the Status-Line BNF
100         statusLine = new StatusLine("HTTP/1.1 200 ");
101         assertEquals(200, statusLine.getStatusCode());
102         assertEquals("", statusLine.getReasonPhrase());
103 
104         //this is not strictly valid, but is lienent
105         statusLine = new StatusLine("HTTP/1.1 200");
106         assertEquals(200, statusLine.getStatusCode());
107         assertEquals("", statusLine.getReasonPhrase());
108 
109         //this is not strictly valid, but is lienent
110         statusLine = new StatusLine("HTTP/1.1     200 OK");
111         assertEquals(200, statusLine.getStatusCode());
112         assertEquals("OK", statusLine.getReasonPhrase());
113 
114         //this is not strictly valid, but is lienent
115         statusLine = new StatusLine("\rHTTP/1.1 200 OK");
116         assertEquals(200, statusLine.getStatusCode());
117         assertEquals("OK", statusLine.getReasonPhrase());
118         assertEquals("HTTP/1.1", statusLine.getHttpVersion());
119 
120         //this is not strictly valid, but is lienent
121         statusLine = new StatusLine("  HTTP/1.1 200 OK");
122         assertEquals(200, statusLine.getStatusCode());
123         assertEquals("OK", statusLine.getReasonPhrase());
124         assertEquals("HTTP/1.1", statusLine.getHttpVersion());
125     }
126 
127     public void testFailure() throws Exception {
128         try {
129             statusLine = new StatusLine(null);
130             fail();
131         } catch (NullPointerException e) { /* expected */ }
132 
133         try {
134             statusLine = new StatusLine("xxx 200 OK");
135             fail();
136         } catch (HttpException e) { /* expected */ }
137 
138         try {
139             statusLine = new StatusLine("HTTP/1.1 xxx OK");
140             fail();
141         } catch (HttpException e) { /* expected */ }
142 
143         try {
144             statusLine = new StatusLine("HTTP/1.1    ");
145             fail();
146         } catch (HttpException e) { /* expected */ }
147     }
148 
149 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestStreams.html100644 0 0 67253 10661532627 26256 0ustar 0 0 TestStreams xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestStreams.java,v 1.19 2004/10/31 14:04:13 olegk Exp $
3    * $Revision: 505890 $
4    * $Date: 2007-02-11 12:25:25 +0100 (Sun, 11 Feb 2007) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import java.io.ByteArrayInputStream;
35  import java.io.ByteArrayOutputStream;
36  import java.io.IOException;
37  import java.io.InputStream;
38  import java.io.OutputStream;
39  
40  import junit.framework.Test;
41  import junit.framework.TestCase;
42  import junit.framework.TestSuite;
43  
44  import org.apache.commons.httpclient.methods.GetMethod;
45  import org.apache.commons.httpclient.util.EncodingUtil;
46  
47  
48  public class TestStreams extends TestCase {
49  
50      private static final String CONTENT_CHARSET = "ISO-8859-1";
51      
52      public TestStreams(String testName) {
53          super(testName);
54      }
55  
56      public void testChunkedInputStream() throws IOException {
57          String correctInput = "10;key=\"value\r\nnewline\"\r\n1234567890123456\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\r\n";
58          String correctResult = "123456789012345612345";
59          HttpMethod method = new FakeHttpMethod();
60  
61          //Test for when buffer is larger than chunk size
62          InputStream in = new ChunkedInputStream(new ByteArrayInputStream(
63              EncodingUtil.getBytes(correctInput, CONTENT_CHARSET)), method);
64          byte[] buffer = new byte[300];
65          ByteArrayOutputStream out = new ByteArrayOutputStream();
66          int len;
67          while ((len = in.read(buffer)) > 0) {
68              out.write(buffer, 0, len);
69          }
70          String result = EncodingUtil.getString(out.toByteArray(), CONTENT_CHARSET);
71          assertEquals(result, correctResult);
72          Header footer = method.getResponseFooter("footer1");
73          assertEquals(footer.getValue(), "abcde");
74          footer = method.getResponseFooter("footer2");
75          assertEquals(footer.getValue(), "fghij");
76  
77          method = new FakeHttpMethod();
78  
79          //Test for when buffer is smaller than chunk size.
80          in = new ChunkedInputStream(new ByteArrayInputStream(
81              EncodingUtil.getBytes(correctInput, CONTENT_CHARSET)), method);
82          buffer = new byte[7];
83          out = new ByteArrayOutputStream();
84          while ((len = in.read(buffer)) > 0) {
85              out.write(buffer, 0, len);
86          }
87          result = EncodingUtil.getString(out.toByteArray(), CONTENT_CHARSET);
88          assertEquals(result, correctResult);
89          footer = method.getResponseFooter("footer1");
90          assertEquals(footer.getValue(), "abcde");
91          footer = method.getResponseFooter("footer2");
92          assertEquals(footer.getValue(), "fghij");
93      }
94  
95      public void testCorruptChunkedInputStream1() throws IOException {
96          //missing \r\n at the end of the first chunk
97          String corrupInput = "10;key=\"value\"\r\n123456789012345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\r\n";
98          HttpMethod method = new FakeHttpMethod();
99  
100         InputStream in = new ChunkedInputStream(new ByteArrayInputStream(
101             EncodingUtil.getBytes(corrupInput, CONTENT_CHARSET)), method);
102         byte[] buffer = new byte[300];
103         ByteArrayOutputStream out = new ByteArrayOutputStream();
104         int len;
105         try {
106             while ((len = in.read(buffer)) > 0) {
107                 out.write(buffer, 0, len);
108             }
109             fail("Should have thrown exception");
110         } catch(IOException e) {
111             /* expected exception */
112         }
113     }
114 
115     public void testEmptyChunkedInputStream() throws IOException {
116         String input = "0\r\n";
117         HttpMethod method = new FakeHttpMethod();
118 
119         InputStream in = new ChunkedInputStream(new ByteArrayInputStream(
120             EncodingUtil.getBytes(input, CONTENT_CHARSET)), method);
121         byte[] buffer = new byte[300];
122         ByteArrayOutputStream out = new ByteArrayOutputStream();
123         int len;
124         while ((len = in.read(buffer)) > 0) {
125             out.write(buffer, 0, len);
126         }
127         assertEquals(0, out.size());
128     }
129 
130     public void testContentLengthInputStream() throws IOException {
131         String correct = "1234567890123456";
132         InputStream in = new ContentLengthInputStream(new ByteArrayInputStream(
133             EncodingUtil.getBytes(correct, CONTENT_CHARSET)), 10L);
134         byte[] buffer = new byte[50];
135         int len = in.read(buffer);
136         ByteArrayOutputStream out = new ByteArrayOutputStream();
137         out.write(buffer, 0, len);
138         String result = EncodingUtil.getString(out.toByteArray(), CONTENT_CHARSET);
139         assertEquals(result, "1234567890");
140     }
141 
142     public void testContentLengthInputStreamSkip() throws IOException {
143         InputStream in = new ContentLengthInputStream(new ByteArrayInputStream(new byte[20]), 10L);
144         assertEquals(10, in.skip(10));
145         assertTrue(in.read() == -1);
146 
147         in = new ContentLengthInputStream(new ByteArrayInputStream(new byte[20]), 10L);
148         in.read();
149         assertEquals(9, in.skip(10));
150         assertTrue(in.read() == -1);
151 
152         in = new ContentLengthInputStream(new ByteArrayInputStream(new byte[20]), 2L);
153         in.read();
154         in.read();
155         assertTrue(in.skip(10) <= 0);
156         assertTrue(in.read() == -1);
157     }
158 
159     public void testChunkedConsitance() throws IOException {
160         String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb";
161         ByteArrayOutputStream buffer = new ByteArrayOutputStream();
162         OutputStream out = new ChunkedOutputStream(buffer);
163         out.write(EncodingUtil.getBytes(input, CONTENT_CHARSET));
164         out.close();
165         buffer.close();
166         InputStream in = new ChunkedInputStream(new ByteArrayInputStream(buffer.toByteArray()), new GetMethod());
167 
168         byte[] d = new byte[10];
169         ByteArrayOutputStream result = new ByteArrayOutputStream();
170         int len = 0;
171         while ((len = in.read(d)) > 0) {
172             result.write(d, 0, len);
173         }
174 
175         String output = EncodingUtil.getString(result.toByteArray(), CONTENT_CHARSET);
176         assertEquals(input, output);
177     }
178 
179     public void testChunkedOutputStream() throws IOException {
180         ByteArrayOutputStream buffer = new ByteArrayOutputStream();
181         ChunkedOutputStream out = new ChunkedOutputStream(buffer, 2);
182         out.write('1');  
183         out.write('2');  
184         out.write('3');  
185         out.write('4');  
186         out.finish();
187         out.close();
188         
189         byte [] rawdata =  buffer.toByteArray();
190         
191         assertEquals(19, rawdata.length);
192         assertEquals('2', rawdata[0]);
193         assertEquals('\r', rawdata[1]);
194         assertEquals('\n', rawdata[2]);
195         assertEquals('1', rawdata[3]);
196         assertEquals('2', rawdata[4]);
197         assertEquals('\r', rawdata[5]);
198         assertEquals('\n', rawdata[6]);
199         assertEquals('2', rawdata[7]);
200         assertEquals('\r', rawdata[8]);
201         assertEquals('\n', rawdata[9]);
202         assertEquals('3', rawdata[10]);
203         assertEquals('4', rawdata[11]);
204         assertEquals('\r', rawdata[12]);
205         assertEquals('\n', rawdata[13]);
206         assertEquals('0', rawdata[14]);
207         assertEquals('\r', rawdata[15]);
208         assertEquals('\n', rawdata[16]);
209         assertEquals('\r', rawdata[17]);
210         assertEquals('\n', rawdata[18]);
211     }
212 
213     public void testChunkedOutputStreamLargeChunk() throws IOException {
214         ByteArrayOutputStream buffer = new ByteArrayOutputStream();
215         ChunkedOutputStream out = new ChunkedOutputStream(buffer, 2);
216         out.write(new byte[] {'1', '2', '3', '4'});
217         out.finish();
218         out.close();
219         
220         byte [] rawdata =  buffer.toByteArray();
221         
222         assertEquals(14, rawdata.length);
223         assertEquals('4', rawdata[0]);
224         assertEquals('\r', rawdata[1]);
225         assertEquals('\n', rawdata[2]);
226         assertEquals('1', rawdata[3]);
227         assertEquals('2', rawdata[4]);
228         assertEquals('3', rawdata[5]);
229         assertEquals('4', rawdata[6]);
230         assertEquals('\r', rawdata[7]);
231         assertEquals('\n', rawdata[8]);
232         assertEquals('0', rawdata[9]);
233         assertEquals('\r', rawdata[10]);
234         assertEquals('\n', rawdata[11]);
235         assertEquals('\r', rawdata[12]);
236         assertEquals('\n', rawdata[13]);
237     }
238 
239     public void testChunkedOutputStreamSmallChunk() throws IOException {
240         ByteArrayOutputStream buffer = new ByteArrayOutputStream();
241         ChunkedOutputStream out = new ChunkedOutputStream(buffer, 2);
242         out.write('1');  
243         out.finish();
244         out.close();
245         
246         byte [] rawdata =  buffer.toByteArray();
247         
248         assertEquals(11, rawdata.length);
249         assertEquals('1', rawdata[0]);
250         assertEquals('\r', rawdata[1]);
251         assertEquals('\n', rawdata[2]);
252         assertEquals('1', rawdata[3]);
253         assertEquals('\r', rawdata[4]);
254         assertEquals('\n', rawdata[5]);
255         assertEquals('0', rawdata[6]);
256         assertEquals('\r', rawdata[7]);
257         assertEquals('\n', rawdata[8]);
258         assertEquals('\r', rawdata[9]);
259         assertEquals('\n', rawdata[10]);
260     }
261 
262     // ------------------------------------------------------- TestCase Methods
263 
264     public static Test suite() {
265         return new TestSuite(TestStreams.class);
266     }
267 
268     // ------------------------------------------------------------------- Main
269     public static void main(String args[]) {
270         String[] testCaseName = { TestStreams.class.getName() };
271         junit.textui.TestRunner.main(testCaseName);
272     }
273 
274 
275     public void testAutoCloseInputStream() throws IOException {
276         // The purpose of this test is to check EOF handling of ACIS with
277         // respect to exceptions being thrown. Putting it on top of a
278         // plain ByteArrayInputStream won't do, since BAIS can't be closed.
279         ByteArrayInputStream bais =
280             new ByteArrayInputStream("whatever".getBytes());
281         InputStream fbais = new java.io.FilterInputStream(bais) {
282                 private boolean closed = false;
283                 public void close() throws IOException {
284                     closed = true;
285                     super.close();
286                 }
287                 public int available() throws IOException {
288                     if (closed)
289                         throw new IOException("closed");
290                     return super.available();
291                 }
292             };
293 
294         AutoCloseInputStream acis = new AutoCloseInputStream(fbais, null);
295         byte[] data = new byte[16];
296         int count = 0;
297         while (count >= 0) {
298             count = acis.read(data);
299         }
300         // We're at EOF. The underlying stream should be closed,
301         // but the ACIS itself not.
302         try {
303             fbais.available();
304             fail("underlying stream not auto-closed");
305         } catch (IOException x) {
306             // expected, pis should be closed
307         }
308 
309         // don't want to see an exception being thrown here
310         acis.available();
311 
312         acis.close();
313         try {
314             acis.available();
315             fail("auto-close stream not closed");
316         } catch (IOException x) {
317             // expected, acis should be closed
318         }
319     }
320 }
321 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestURI.html100644 0 0 115227 10661532627 25312 0ustar 0 0 TestURI xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestURI.java $
3    * $Revision: 564973 $
4    * $Date: 2007-08-11 22:51:47 +0200 (Sat, 11 Aug 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import org.apache.commons.httpclient.methods.GetMethod;
34  
35  import junit.framework.Test;
36  import junit.framework.TestCase;
37  import junit.framework.TestSuite;
38  
39  /**
40   * Simple tests for the URI class.
41   * 
42   * @author Michael Becke
43   */
44  public class TestURI extends TestCase {
45  
46      /**
47       * Constructor for TestURI.
48       * @param testName
49       */
50      public TestURI(String testName) {
51          super(testName);
52      }
53      
54      public static Test suite() {
55          return new TestSuite(TestURI.class);
56      }
57      
58      public void testIPv4Address() throws URIException {
59  
60          URI base = new URI("http://10.0.1.10:8830", false);
61          
62          URI uri = base;        
63          assertTrue("Should be an IPv4 address", uri.isIPv4address());
64              
65          uri = new URI(base, "/04-1.html", false);
66          assertTrue("Should be an IPv4 address", uri.isIPv4address());
67  
68          uri = new URI("/04-1.html", false);
69          assertFalse("Should NOT be an IPv4 address", uri.isIPv4address());
70  
71          uri = new URI(base, "http://10.0.1.10:8830/04-1.html", false);
72          assertTrue("Should be an IPv4 address", uri.isIPv4address());
73  
74          uri = new URI("http://10.0.1.10:8830/04-1.html", false);
75          assertTrue("Should be an IPv4 address", uri.isIPv4address());
76  
77          uri = new URI(base, "http://host.org/04-1.html", false);
78          assertFalse("Should NOT be an IPv4 address", uri.isIPv4address());
79  
80          uri = new URI("http://host.org/04-1.html", false);
81          assertFalse("Should NOT be an IPv4 address", uri.isIPv4address());
82          
83      }
84      
85      public void testUrl() throws URIException {
86          URI url = new HttpURL("http://jakarta.apache.org");
87          assertEquals(80, url.getPort());
88          assertEquals("http", url.getScheme());
89          
90          url = new HttpsURL("https://jakarta.apache.org");
91          assertEquals(443, url.getPort());
92          assertEquals("https", url.getScheme());
93      }
94      
95      /**
96       * Tests the URI(URI, String) constructor.  This tests URIs ability to
97       * resolve relative URIs.
98       */
99      public void testRelativeURIConstructor() {
100         
101         URI baseURI = null;
102         
103         try {
104             baseURI = new URI("http://a/b/c/d;p?q", false);
105         } catch ( URIException e ) {
106             fail( "unable to create base URI: " + e );
107         }
108         
109         // the following is an array of arrays in the following order
110         // relative URI, scheme, host(authority), path, query, fragment, abs. URI
111         //
112         // these examples were taken from rfc 2396
113         String[][] testRelativeURIs = {
114             { "g:h", "g", null, "h", null, null, "g:h" },
115             { "g", "http", "a", "/b/c/g", null, null, "http://a/b/c/g" },
116             { "./g", "http", "a", "/b/c/g", null, null, "http://a/b/c/g" },
117             { "g/", "http", "a", "/b/c/g/", null, null, "http://a/b/c/g/" },
118             { "/g", "http", "a", "/g", null, null, "http://a/g" },
119             { "//g", "http", "g", null, null, null, "http://g" },
120             { "?y", "http", "a", "/b/c/d;p", "y", null, "http://a/b/c/d;p?y" },
121             { "g?y", "http", "a", "/b/c/g", "y", null, "http://a/b/c/g?y" },
122             { "#s", "http", "a", "/b/c/d;p", "q", "s", "http://a/b/c/d;p?q#s" },
123             { "#", "http", "a", "/b/c/d;p", "q", "", "http://a/b/c/d;p?q#" },
124             { "", "http", "a", "/b/c/d;p", "q", null, "http://a/b/c/d;p?q" },
125             { "g#s", "http", "a", "/b/c/g", null, "s", "http://a/b/c/g#s" },
126             { "g?y#s","http", "a", "/b/c/g", "y", "s", "http://a/b/c/g?y#s" },
127             { ";x", "http", "a", "/b/c/;x", null, null, "http://a/b/c/;x" },
128             { "g;x", "http", "a", "/b/c/g;x", null, null, "http://a/b/c/g;x" },
129             { "g;x?y#s", "http", "a", "/b/c/g;x", "y", "s", "http://a/b/c/g;x?y#s" },
130             { ".", "http", "a", "/b/c/", null, null, "http://a/b/c/" },
131             { "./", "http", "a", "/b/c/", null, null, "http://a/b/c/" },
132             { "..", "http", "a", "/b/", null, null, "http://a/b/" },
133             { "../", "http", "a", "/b/", null, null, "http://a/b/" },
134             { "../g", "http", "a", "/b/g", null, null, "http://a/b/g" },
135             { "../..", "http", "a", "/", null, null, "http://a/" },
136             { "../../", "http", "a", "/", null, null, "http://a/" },
137             { "../../g", "http", "a", "/g", null, null, "http://a/g" },
138             { "../../../g", "http", "a", "/g", null, null, "http://a/g" },
139             { "../../../../g", "http", "a", "/g", null, null, "http://a/g" },
140             { "/./g", "http", "a", "/g", null, null, "http://a/g" },
141             { "/../g", "http", "a", "/g", null, null, "http://a/g" },
142             { "g.", "http", "a", "/b/c/g.", null, null, "http://a/b/c/g." },
143             { ".g", "http", "a", "/b/c/.g", null, null, "http://a/b/c/.g" },
144             { "g..", "http", "a", "/b/c/g..", null, null, "http://a/b/c/g.." },
145             { "..g", "http", "a", "/b/c/..g", null, null, "http://a/b/c/..g" },
146             { "./../g", "http", "a", "/b/g", null, null, "http://a/b/g" },
147             { "./g/.", "http", "a", "/b/c/g/", null, null, "http://a/b/c/g/" },
148             { "g/./h", "http", "a", "/b/c/g/h", null, null, "http://a/b/c/g/h" },
149             { "g/../h", "http", "a", "/b/c/h", null, null, "http://a/b/c/h" },
150             { "g;x=1/./y", "http", "a", "/b/c/g;x=1/y", null, null, "http://a/b/c/g;x=1/y" },
151             { "g;x=1/../y", "http", "a", "/b/c/y", null, null, "http://a/b/c/y" },
152             { "g?y/./x", "http", "a", "/b/c/g", "y/./x", null, "http://a/b/c/g?y/./x" },
153             { "g?y/../x", "http", "a", "/b/c/g", "y/../x", null, "http://a/b/c/g?y/../x" },
154             { "g#s/./x", "http", "a", "/b/c/g", null, "s/./x", "http://a/b/c/g#s/./x" },
155             { "g#s/../x", "http", "a", "/b/c/g", null, "s/../x", "http://a/b/c/g#s/../x" },
156             { ":g", "http", "a", "/b/c/:g", null, null, "http://a/b/c/:g" }, // see issue #35148
157             { "//a/b/c", "http", "a", "/b/c", null, null, "http://a/b/c" } // see HTTPCLIENT-580 
158         };
159         for (int i = 0; i < testRelativeURIs.length; i++) {
160             URI testURI = null;
161             
162             try {
163                 testURI = new URI( baseURI, testRelativeURIs[i][0], false );
164             } catch ( URIException e ) {
165                 e.printStackTrace();
166                 fail( 
167                     "unable to create URI with relative value(" 
168                     + testRelativeURIs[i][0] + "): " + e 
169                 );   
170             }
171             
172             try {
173                 assertEquals("array index "+i, testRelativeURIs[i][1], testURI.getScheme());
174                 assertEquals("array index "+i, testRelativeURIs[i][2], testURI.getAuthority());
175                 assertEquals("array index "+i, testRelativeURIs[i][3], testURI.getPath());
176                 assertEquals("array index "+i, testRelativeURIs[i][4], testURI.getQuery());
177                 assertEquals("array index "+i, testRelativeURIs[i][5], testURI.getFragment());
178                 assertEquals("array index "+i, testRelativeURIs[i][6], testURI.getURIReference());
179             } catch ( URIException e ) {
180                 fail( "error getting URI property: " + e );
181             }            
182         }
183         
184     }
185 
186     public void testTestURIAuthorityString() throws Exception {
187         URI url = new URI("ftp", "user:password", "localhost", -1, "/");
188         assertEquals("ftp://user:password@localhost/", url.toString());
189         assertEquals("user:password@localhost", url.getAuthority());
190     }
191     
192     public void testTestHttpUrlAuthorityString() throws Exception {
193         HttpURL url = new HttpURL("localhost", -1, "/");
194         assertEquals("http://localhost/", url.toString());
195         url.setRawUserinfo("user".toCharArray(), "password".toCharArray());
196         assertEquals("http://localhost/", url.toString());
197         assertEquals("user:password@localhost", url.getAuthority());
198 
199         url = new HttpURL("user#@", "pass#@", "localhost", 8080, "/");
200         assertEquals("http://localhost:8080/", url.toString());
201         assertEquals("user#@:pass#@", url.getUserinfo());
202         assertEquals("user%23%40:pass%23%40", url.getEscapedUserinfo());
203 
204         url = new HttpURL("user%23%40:pass%23%40", "localhost", 8080, "/");
205         assertEquals("http://localhost:8080/", url.toString());
206         assertEquals("user#@:pass#@", url.getUserinfo());
207         assertEquals("user%23%40:pass%23%40", url.getEscapedUserinfo());
208         
209         url = new HttpURL("localhost", 8080, "/");
210         assertEquals("http://localhost:8080/", url.toString());
211         url.setRawUserinfo("user".toCharArray(), "password".toCharArray());
212         assertEquals("http://localhost:8080/", url.toString());
213         assertEquals("user:password@localhost:8080", url.getAuthority());
214     }
215     
216     public void testTestHttpsUrlAuthorityString() throws Exception {
217         HttpsURL url = new HttpsURL("localhost", -1, "/");
218         assertEquals("https://localhost/", url.toString());
219         url.setRawUserinfo("user".toCharArray(), "password".toCharArray());
220         assertEquals("https://localhost/", url.toString());
221         assertEquals("user:password@localhost", url.getAuthority());
222 
223         url = new HttpsURL("user#@", "pass#@", "localhost", 8080, "/");
224         assertEquals("https://localhost:8080/", url.toString());
225         assertEquals("user#@:pass#@", url.getUserinfo());
226         assertEquals("user%23%40:pass%23%40", url.getEscapedUserinfo());
227         
228         url = new HttpsURL("user%23%40:pass%23%40", "localhost", 8080, "/");
229         assertEquals("https://localhost:8080/", url.toString());
230         assertEquals("user#@:pass#@", url.getUserinfo());
231         assertEquals("user%23%40:pass%23%40", url.getEscapedUserinfo());        
232         
233         url = new HttpsURL("localhost", 8080, "/");
234         assertEquals("https://localhost:8080/", url.toString());
235         url.setRawUserinfo("user".toCharArray(), "password".toCharArray());
236         assertEquals("https://localhost:8080/", url.toString());
237         assertEquals("user:password@localhost:8080", url.getAuthority());
238         
239     }
240 
241     public void testURIEscaping() throws Exception {
242         String escaped = "http://some.host.com/%41.html";
243         String unescaped = "http://some.host.com/A.html";
244         URI u1 = new URI(escaped, true);
245         GetMethod method = new GetMethod();
246         method.setURI(u1);
247         URI u2 = method.getURI();
248 
249         assertEquals(escaped, u1.toString());
250         assertEquals(escaped, new String(u1.getRawURI()));
251         assertEquals(unescaped, u1.getURI());
252         assertEquals(escaped, u2.toString());
253         assertEquals(escaped, new String(u2.getRawURI()));
254         assertEquals(unescaped, u2.getURI());        
255     }
256 
257     public void testBug578() throws Exception {
258         HttpURL url = new HttpURL("http://localhost/test+test");
259         assertEquals("/test+test", url.getPath());
260     }
261     
262     public void testVariousCharacters() throws Exception {
263         verifyInvalidURI("http://authority:123/path/path?query&name=val ue");
264         verifyInvalidURI("http://authority:123/path/path?query&na me=value");
265         verifyInvalidURI("http://authority:123/path/path?qu ery&name=value");
266         verifyInvalidURI("http://authority:123/path/pa th?query&name=value");
267         verifyInvalidURI("http://authority:123/pa th/path?query&name=value");
268         verifyInvalidURI("http://authority:12 3/path/path?query&name=value");
269         verifyInvalidURI("http://autho rity:123/path/path?query&name=value");
270         verifyInvalidURI("htt p://authority:123/path/path?query&name=value");
271     }
272     
273     private void verifyInvalidURI(String uri) {
274         try {
275             new URI(uri, true);
276             fail("should have thrown URIException");
277         } catch(URIException e) {
278             /* expected */
279         }
280     }    
281     
282     /**
283      * Verify proper handling of relative URIs which have a scheme. 
284      * See bug http://issues.apache.org/jira/browse/HTTPCLIENT-587
285      * 
286      * @throws Exception
287      */
288     public void testRelativeWithScheme() throws Exception {
289         URI base = new URI("http://www.example.com/some/path", true);
290         URI rel1 = new URI("http:", true);
291         URI rel2 = new URI("http:foo", true);
292         URI rel3 = new URI("http:../../bar", true);
293         URI derel1 = new URI(base, rel1);
294         assertEquals("http://www.example.com/some/path",derel1.toString());
295         URI derel2 = new URI(base, rel2);
296         assertEquals("http://www.example.com/some/foo",derel2.toString());
297         URI derel3 = new URI(base,rel3);
298         assertEquals("http://www.example.com/bar",derel3.toString());
299     }
300     
301     /**
302      * Verify proper handling of relative URIs with embedded double-slashes,
303      * like "foo//bar//baz". 
304      * See bug http://issues.apache.org/jira/browse/HTTPCLIENT-588
305      * 
306      * @throws Exception
307      */
308     public void testRelativeWithDoubleSlash() throws Exception {
309         URI rel = new URI("foo//bar//baz",true);
310         assertEquals("foo//bar//baz",rel.toString());
311     }
312     
313 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestURIUtil.html100644 0 0 34202 10661532627 26121 0ustar 0 0 TestURIUtil xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestURIUtil.java,v 1.6 2004/02/22 18:08:50 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import junit.framework.Test;
35  import junit.framework.TestCase;
36  import junit.framework.TestSuite;
37  
38  import org.apache.commons.httpclient.util.URIUtil;
39  
40  /**
41   *
42   * Unit tests for {@link URIUtil}.  These tests care currently quite limited
43   * and should be expanded to test more functionality.
44   *
45   * @author Marc A. Saegesser
46   * @version $Id: TestURIUtil.java 480424 2006-11-29 05:56:49Z bayard $
47   */
48  public class TestURIUtil extends TestCase {
49      // ----------------------------------------------------- Instance Variables
50      URITestCase pathTests[] = {new URITestCase("http://www.server.com/path1/path2", "/path1/path2"),
51                                 new URITestCase("http://www.server.com/path1/path2/", "/path1/path2/"),
52                                 new URITestCase("http://www.server.com/path1/path2?query=string", "/path1/path2"),
53                                 new URITestCase("http://www.server.com/path1/path2/?query=string", "/path1/path2/"),
54                                 new URITestCase("www.noscheme.com/path1/path2", "/path1/path2"),
55                                 new URITestCase("www.noscheme.com/path1/path2#anchor?query=string", "/path1/path2"),
56                                 new URITestCase("/noscheme/nohost/path", "/noscheme/nohost/path"),
57                                 new URITestCase("http://www.server.com", "/"),
58                                 new URITestCase("https://www.server.com:443/ssl/path", "/ssl/path"),
59                                 new URITestCase("http://www.server.com:8080/path/with/port", "/path/with/port"),
60                                 new URITestCase("http://www.server.com/path1/path2?query1=string?1&query2=string2", "/path1/path2")};
61  
62      URITestCase queryTests[] = {new URITestCase("http://www.server.com/path1/path2", null),
63                                  new URITestCase("http://www.server.com/path1/path2?query=string", "query=string"),
64                                  new URITestCase("http://www.server.com/path1/path2/?query=string", "query=string"),
65                                  new URITestCase("www.noscheme.com/path1/path2#anchor?query=string", "query=string"),
66                                  new URITestCase("/noscheme/nohost/path?query1=string1&query2=string2", "query1=string1&query2=string2"),
67                                  new URITestCase("https://www.server.com:443/ssl/path?query1=string1&query2=string2", "query1=string1&query2=string2"),
68                                  new URITestCase("http://www.server.com:8080/path/with/port?query1=string1&query2=string2", "query1=string1&query2=string2"),
69                                  new URITestCase("http://www.server.com/path1/path2?query1=string?1&query2=string2", "query1=string?1&query2=string2")};
70  
71  
72  
73      // ------------------------------------------------------------ Constructor
74      public TestURIUtil(String testName) {
75          super(testName);
76      }
77  
78      // ------------------------------------------------------------------- Main
79      public static void main(String args[]) {
80          String[] testCaseName = { TestURIUtil.class.getName() };
81          junit.textui.TestRunner.main(testCaseName);
82      }
83  
84      // ------------------------------------------------------- TestCase Methods
85  
86      public static Test suite() {
87          return new TestSuite(TestURIUtil.class);
88      }
89  
90  
91      // ----------------------------------------------------------- Test Methods
92      public void testGetPath()
93      {
94          String testValue = "";
95          String expectedResult = "";
96  
97          for(int i=0;i<pathTests.length;i++){
98              testValue = pathTests[i].getTestValue();
99              expectedResult = pathTests[i].getExpectedResult();
100             assertEquals("Path test", expectedResult, URIUtil.getPath(testValue));
101         }
102     }
103 
104     public void testGetQueryString()
105     {
106         String testValue = "";
107         String expectedResult = "";
108 
109         for(int i=0;i<queryTests.length;i++){
110             testValue = queryTests[i].getTestValue();
111             expectedResult = queryTests[i].getExpectedResult();
112             assertEquals("Path test", expectedResult, URIUtil.getQuery(testValue));
113         }
114     }
115 
116     private class URITestCase{
117         private String testValue;
118         private String expectedResult;
119 
120         public URITestCase(String testValue, String expectedResult){
121             this.testValue = testValue;
122             this.expectedResult = expectedResult;
123         }
124 
125         public String getTestValue(){
126             return testValue;
127         }
128 
129         public String getExpectedResult(){
130             return expectedResult;
131         }
132     }
133 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestURIUtil2.html100644 0 0 14275 10661532627 26213 0ustar 0 0 TestURIUtil2 xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestURIUtil2.java,v 1.4 2004/02/22 18:08:50 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  package org.apache.commons.httpclient;
32  
33  import org.apache.commons.httpclient.util.URIUtil;
34  import junit.framework.*;
35  
36  
37  /**
38   * Tests the util.URIUtil class.
39   *
40   * @author Ortwin Gl?ck
41   *
42   * @since 2.0
43   */
44  public class TestURIUtil2 extends TestCase {
45  
46      public TestURIUtil2(String s) {
47          super(s);
48      }
49  
50      public static Test suite() {
51          return new TestSuite(TestURIUtil.class);
52      }
53  
54      public void testEncodeWithinQuery() {
55          String unescaped1=  "abc123+ %_?=&#.?";
56          try {
57              String stringRet = URIUtil.encodeWithinQuery(unescaped1);
58              assertEquals("abc123%2B%20%25_%3F%3D%26%23.%C3%A4", stringRet);
59              stringRet = URIUtil.decode(stringRet);
60              assertEquals(unescaped1, stringRet);
61          } catch(Exception e) {
62              System.err.println("Exception thrown:  "+e);
63          }
64      }
65  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/TestVirtualHost.html100644 0 0 52511 10661532627 27113 0ustar 0 0 TestVirtualHost xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestVirtualHost.java,v 1.2 2004/10/31 14:42:59 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient;
33  
34  import java.io.IOException;
35  import java.net.InetAddress;
36  import java.net.Socket;
37  import java.net.UnknownHostException;
38  
39  import junit.framework.Test;
40  import junit.framework.TestSuite;
41  
42  import org.apache.commons.httpclient.methods.GetMethod;
43  import org.apache.commons.httpclient.params.HttpConnectionParams;
44  import org.apache.commons.httpclient.protocol.Protocol;
45  import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
46  import org.apache.commons.httpclient.server.HttpService;
47  import org.apache.commons.httpclient.server.RequestLine;
48  import org.apache.commons.httpclient.server.SimpleRequest;
49  import org.apache.commons.httpclient.server.SimpleResponse;
50  
51  /**
52   * HTTP protocol versioning tests.
53   *
54   * @author Oleg Kalnichevski
55   * 
56   * @version $Revision: 480424 $
57   */
58  public class TestVirtualHost extends HttpClientTestBase {
59  
60      // ------------------------------------------------------------ Constructor
61      public TestVirtualHost(final String testName) throws IOException {
62          super(testName);
63      }
64  
65      // ------------------------------------------------------------------- Main
66      public static void main(String args[]) {
67          String[] testCaseName = { TestVirtualHost.class.getName() };
68          junit.textui.TestRunner.main(testCaseName);
69      }
70  
71      // ------------------------------------------------------- TestCase Methods
72  
73      public static Test suite() {
74          return new TestSuite(TestVirtualHost.class);
75      }
76  
77      private class VirtualService implements HttpService {
78  
79          public VirtualService() {
80              super();
81          }
82  
83          public boolean process(final SimpleRequest request, final SimpleResponse response)
84              throws IOException
85          {
86              HttpVersion httpversion = request.getRequestLine().getHttpVersion();
87              Header hostheader = request.getFirstHeader("Host");
88              if (hostheader == null) {
89                  response.setStatusLine(httpversion, HttpStatus.SC_BAD_REQUEST);
90                  response.setBodyString("Host header missing");
91              } else {
92                  response.setStatusLine(httpversion, HttpStatus.SC_OK);
93                  response.setBodyString(hostheader.getValue());
94              }
95              return true;
96          }
97      }
98  
99      public void testVirtualHostHeader() throws IOException {
100         this.server.setHttpService(new VirtualService());
101 
102         GetMethod httpget = new GetMethod("/test/");
103         
104         HostConfiguration hostconf = new HostConfiguration();
105         hostconf.setHost(this.server.getLocalAddress(), this.server.getLocalPort(), "http");
106         hostconf.getParams().setVirtualHost("somehost");
107         try {
108             this.client.executeMethod(hostconf, httpget);
109             String hostheader = "somehost:" + this.server.getLocalPort();
110             assertEquals(hostheader, httpget.getResponseBodyAsString());
111         } finally {
112             httpget.releaseConnection();
113         }
114     }
115 
116     public void testNoVirtualHostHeader() throws IOException {
117         this.server.setHttpService(new VirtualService());
118 
119         GetMethod httpget = new GetMethod("/test/");
120         
121         HostConfiguration hostconf = new HostConfiguration();
122         hostconf.setHost(this.server.getLocalAddress(), this.server.getLocalPort(), "http");
123         hostconf.getParams().setVirtualHost(null);
124         try {
125             this.client.executeMethod(hostconf, httpget);
126             String hostheader = this.server.getLocalAddress() + ":" + this.server.getLocalPort();
127             assertEquals(hostheader, httpget.getResponseBodyAsString());
128         } finally {
129             httpget.releaseConnection();
130         }
131     }
132     
133     private class VirtualHostService implements HttpService {
134 
135         public VirtualHostService() {
136             super();
137         }
138 
139         public boolean process(final SimpleRequest request, final SimpleResponse response)
140             throws IOException {
141             RequestLine reqline = request.getRequestLine();
142             HttpVersion ver = reqline.getHttpVersion();
143             Header header =  request.getFirstHeader("Host");
144             if (header == null) {
145                 response.setStatusLine(ver, HttpStatus.SC_BAD_REQUEST);
146                 return true;
147             }
148             String host = header.getValue();
149             if (host.equalsIgnoreCase("whatever.com")) {
150                 response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY);
151                 response.setHeader(new Header("Location", "testhttp://www.whatever.com/"));
152                 return true;
153             } else if (host.equalsIgnoreCase("www.whatever.com")) {
154                 response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY);
155                 response.setHeader(new Header("Location", "testhttp://www.whatever.co.nz/"));
156                 return true;
157             } else if (host.equalsIgnoreCase("www.whatever.co.nz")) {
158                 response.setStatusLine(ver, HttpStatus.SC_OK);
159                 return true;
160             } else {
161                 response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND);
162                 return true;
163             }
164         }
165     }
166     
167     private class VirtualSocketFactory implements ProtocolSocketFactory {
168         
169         private final String hostname;
170         private final int port;
171         
172         public VirtualSocketFactory(final String hostname, int port) {
173             super();
174             this.hostname = hostname;
175             this.port = port;
176         }
177 
178         public Socket createSocket(
179                 final String host, 
180                 int port, 
181                 final InetAddress localAddress, 
182                 int localPort, 
183                 final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
184             return new Socket(this.hostname, this.port);
185         }
186 
187         public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException, UnknownHostException {
188             return new Socket(this.hostname, this.port);
189         }
190 
191         public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
192             return new Socket(this.hostname, this.port);
193         }
194         
195     }
196 
197     public void testRedirectWithVirtualHost() throws IOException {
198         String host = this.server.getLocalAddress();
199         int port = this.server.getLocalPort();
200 
201         Protocol testhttp = new Protocol("http", new VirtualSocketFactory(host, port), port);
202         Protocol.registerProtocol("testhttp", testhttp);
203         try {
204             this.server.setHttpService(new VirtualHostService());
205             this.client.getHostConfiguration().setHost(host, port, "testhttp");
206             this.client.getHostConfiguration().getParams().setVirtualHost("whatever.com");
207             GetMethod httpget = new GetMethod("/");
208             httpget.setFollowRedirects(true);
209             try {
210                 this.client.executeMethod(httpget);
211                 assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
212                 assertEquals("http://www.whatever.co.nz/", httpget.getURI().toString());
213             } finally {
214                 httpget.releaseConnection();
215             }
216         } finally {
217             Protocol.unregisterProtocol("testhttp");
218         }
219         
220     }
221     
222 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/auth/TestAuthAll.html100644 0 0 13547 10661532627 27130 0ustar 0 0 TestAuthAll xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestAuthAll.java,v 1.1 2004/10/31 13:46:54 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   */
28  
29  package org.apache.commons.httpclient.auth;
30  
31  import junit.framework.*;
32  
33  /**
34   * @author Oleg Kalnichevski 
35   * 
36   * @version $Id: TestAuthAll.java 480424 2006-11-29 05:56:49Z bayard $
37   */
38  public class TestAuthAll extends TestCase {
39  
40      public TestAuthAll(String testName) {
41          super(testName);
42      }
43  
44      public static Test suite() {
45          TestSuite suite = new TestSuite();
46          suite.addTest(TestChallengeParser.suite());
47          suite.addTest(TestChallengeProcessor.suite());
48          suite.addTest(TestBasicAuth.suite());
49          suite.addTest(TestDigestAuth.suite());
50          suite.addTest(TestNTLMAuth.suite());
51          return suite;
52      }
53  
54      public static void main(String args[]) {
55          String[] testCaseName = { TestAuthAll.class.getName() };
56          junit.textui.TestRunner.main(testCaseName);
57      }
58  
59  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/auth/TestBasicAuth.html100644 0 0 170272 10661532627 27460 0ustar 0 0 TestBasicAuth xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestBasicAuth.java,v 1.9 2004/11/20 17:56:40 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.auth;
31  
32  import java.io.IOException;
33  
34  import junit.framework.Test;
35  import junit.framework.TestSuite;
36  
37  import org.apache.commons.codec.binary.Base64;
38  import org.apache.commons.httpclient.EchoService;
39  import org.apache.commons.httpclient.FeedbackService;
40  import org.apache.commons.httpclient.Header;
41  import org.apache.commons.httpclient.HttpClientTestBase;
42  import org.apache.commons.httpclient.HttpState;
43  import org.apache.commons.httpclient.HttpStatus;
44  import org.apache.commons.httpclient.ProxyTestDecorator;
45  import org.apache.commons.httpclient.UsernamePasswordCredentials;
46  import org.apache.commons.httpclient.methods.GetMethod;
47  import org.apache.commons.httpclient.methods.HeadMethod;
48  import org.apache.commons.httpclient.methods.PostMethod;
49  import org.apache.commons.httpclient.methods.PutMethod;
50  import org.apache.commons.httpclient.methods.StringRequestEntity;
51  import org.apache.commons.httpclient.server.AuthRequestHandler;
52  import org.apache.commons.httpclient.server.HttpRequestHandlerChain;
53  import org.apache.commons.httpclient.server.HttpServiceHandler;
54  import org.apache.commons.httpclient.util.EncodingUtil;
55  
56  /**
57   * Basic authentication test cases.
58   *
59   * @author Oleg Kalnichevski
60   * 
61   * @version $Id: TestBasicAuth.java 480424 2006-11-29 05:56:49Z bayard $
62   */
63  public class TestBasicAuth extends HttpClientTestBase {
64  
65      // ------------------------------------------------------------ Constructor
66      public TestBasicAuth(final String testName) throws IOException {
67          super(testName);
68      }
69  
70      // ------------------------------------------------------------------- Main
71      public static void main(String args[]) {
72          String[] testCaseName = { TestBasicAuth.class.getName() };
73          junit.textui.TestRunner.main(testCaseName);
74      }
75  
76      // ------------------------------------------------------- TestCase Methods
77  
78      public static Test suite() {
79          TestSuite suite = new TestSuite(TestBasicAuth.class);
80          ProxyTestDecorator.addTests(suite);
81          return suite;
82      }
83  
84      public void testBasicAuthenticationWithNoCreds() throws IOException {
85  
86          UsernamePasswordCredentials creds = 
87              new UsernamePasswordCredentials("testuser", "testpass");
88          
89          HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
90          handlerchain.appendHandler(new AuthRequestHandler(creds));
91          handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
92          
93          this.server.setRequestHandler(handlerchain);
94          GetMethod httpget = new GetMethod("/test/");
95          try {
96              this.client.executeMethod(httpget);
97              assertNotNull(httpget.getStatusLine());
98              assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode());
99              AuthState authstate = httpget.getHostAuthState();
100             assertNotNull(authstate.getAuthScheme());
101             assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
102             assertEquals("test", authstate.getRealm());
103         } finally {
104             httpget.releaseConnection();
105         }
106     }
107 
108     public void testBasicAuthenticationWithNoCredsRetry() throws IOException {
109         UsernamePasswordCredentials creds = 
110             new UsernamePasswordCredentials("testuser", "testpass");
111         
112         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
113         handlerchain.appendHandler(new AuthRequestHandler(creds));
114         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
115         
116         this.server.setRequestHandler(handlerchain);
117 
118         GetMethod httpget = new GetMethod("/test/");
119         try {
120             this.client.executeMethod(httpget);
121             assertNotNull(httpget.getStatusLine());
122             assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode());
123             AuthState authstate = httpget.getHostAuthState();
124             assertNotNull(authstate.getAuthScheme());
125             assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
126             assertEquals("test", authstate.getRealm());
127         } finally {
128             httpget.releaseConnection();
129         }
130         // now try with credentials
131         httpget = new GetMethod("/test/");
132         try {
133             this.client.getState().setCredentials(AuthScope.ANY, creds);
134             this.client.executeMethod(httpget);
135             assertNotNull(httpget.getStatusLine());
136             assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
137         } finally {
138             httpget.releaseConnection();
139         }
140     }
141     
142     public void testBasicAuthenticationWithNoRealm() {
143         String challenge = "Basic";
144         try {
145             AuthScheme authscheme = new BasicScheme();
146             authscheme.processChallenge(challenge);
147             fail("Should have thrown MalformedChallengeException");
148         } catch(MalformedChallengeException e) {
149             // expected
150         }
151     }
152 
153     public void testBasicAuthenticationWith88591Chars() throws Exception {
154         int[] germanChars = { 0xE4, 0x2D, 0xF6, 0x2D, 0xFc };
155         StringBuffer buffer = new StringBuffer();
156         for (int i = 0; i < germanChars.length; i++) {
157             buffer.append((char)germanChars[i]); 
158         }
159         
160         UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("dh", buffer.toString());
161         assertEquals("Basic ZGg65C32Lfw=", 
162             BasicScheme.authenticate(credentials, "ISO-8859-1"));
163     }
164     
165     public void testBasicAuthenticationWithDefaultCreds() throws Exception {
166         UsernamePasswordCredentials creds = 
167             new UsernamePasswordCredentials("testuser", "testpass");
168         
169         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
170         handlerchain.appendHandler(new AuthRequestHandler(creds));
171         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
172 
173         HttpState state = new HttpState();
174         state.setCredentials(AuthScope.ANY, creds);
175         this.client.setState(state);
176         
177         this.server.setRequestHandler(handlerchain);
178 
179         GetMethod httpget = new GetMethod("/test/");
180         try {
181             this.client.executeMethod(httpget);
182         } finally {
183             httpget.releaseConnection();
184         }
185         assertNotNull(httpget.getStatusLine());
186         assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
187         Header auth = httpget.getRequestHeader("Authorization");
188         assertNotNull(auth);
189         String expected = "Basic " + EncodingUtil.getAsciiString(
190             Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
191         assertEquals(expected, auth.getValue());
192         AuthState authstate = httpget.getHostAuthState();
193         assertNotNull(authstate.getAuthScheme());
194         assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
195         assertEquals("test", authstate.getRealm());
196     }
197 
198     public void testBasicAuthentication() throws Exception {
199         UsernamePasswordCredentials creds = 
200             new UsernamePasswordCredentials("testuser", "testpass");
201         
202         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
203         handlerchain.appendHandler(new AuthRequestHandler(creds));
204         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
205 
206         HttpState state = new HttpState();
207         AuthScope authscope = new AuthScope(
208             this.server.getLocalAddress(), 
209             this.server.getLocalPort(),
210             "test");
211         state.setCredentials(authscope, creds);
212         this.client.setState(state);
213 
214         this.server.setRequestHandler(handlerchain);
215 
216         GetMethod httpget = new GetMethod("/test/");
217         try {
218             this.client.executeMethod(httpget);
219         } finally {
220             httpget.releaseConnection();
221         }
222         assertNotNull(httpget.getStatusLine());
223         assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
224         Header auth = httpget.getRequestHeader("Authorization");
225         assertNotNull(auth);
226         String expected = "Basic " + EncodingUtil.getAsciiString(
227             Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
228         assertEquals(expected, auth.getValue());
229         AuthState authstate = httpget.getHostAuthState();
230         assertNotNull(authstate.getAuthScheme());
231         assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
232         assertEquals("test", authstate.getRealm());
233     }
234 
235     public void testBasicAuthenticationWithInvalidCredentials() throws Exception {
236         UsernamePasswordCredentials creds = 
237             new UsernamePasswordCredentials("testuser", "testpass");
238         
239         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
240         handlerchain.appendHandler(new AuthRequestHandler(creds));
241         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
242 
243         HttpState state = new HttpState();
244         AuthScope authscope = new AuthScope(
245             this.server.getLocalAddress(), 
246             this.server.getLocalPort(),
247             "test");
248         state.setCredentials(authscope, new UsernamePasswordCredentials("test", "stuff"));
249         this.client.setState(state);
250 
251         this.server.setRequestHandler(handlerchain);
252         
253         GetMethod httpget = new GetMethod("/test/");
254         try {
255             this.client.executeMethod(httpget);
256         } finally {
257             httpget.releaseConnection();
258         }
259         assertNotNull(httpget.getStatusLine());
260         assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode());
261         AuthState authstate = httpget.getHostAuthState();
262         assertNotNull(authstate.getAuthScheme());
263         assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
264         assertEquals("test", authstate.getRealm());
265     }
266 
267     public void testBasicAuthenticationWithMutlipleRealms1() throws Exception {
268         UsernamePasswordCredentials creds = 
269             new UsernamePasswordCredentials("testuser", "testpass");
270         
271         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
272         handlerchain.appendHandler(new AuthRequestHandler(creds));
273         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
274 
275         HttpState state = new HttpState();
276         AuthScope realm1 = new AuthScope(
277             this.server.getLocalAddress(), 
278             this.server.getLocalPort(),
279             "test");
280         AuthScope realm2 = new AuthScope(
281             this.server.getLocalAddress(), 
282             this.server.getLocalPort(),
283             "test2");
284         state.setCredentials(realm1, new UsernamePasswordCredentials("testuser","testpass"));
285         state.setCredentials(realm2, new UsernamePasswordCredentials("testuser2","testpass2"));
286         this.client.setState(state);
287 
288         this.server.setRequestHandler(handlerchain);
289         
290         GetMethod httpget = new GetMethod("/test/");
291         try {
292             this.client.executeMethod(httpget);
293         } finally {
294             httpget.releaseConnection();
295         }
296         assertNotNull(httpget.getStatusLine());
297         assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
298         Header auth = httpget.getRequestHeader("Authorization");
299         assertNotNull(auth);
300         String expected = "Basic " + EncodingUtil.getAsciiString(
301             Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
302         assertEquals(expected, auth.getValue());
303         AuthState authstate = httpget.getHostAuthState();
304         assertNotNull(authstate.getAuthScheme());
305         assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
306         assertEquals("test", authstate.getRealm());
307     }
308 
309     public void testBasicAuthenticationWithMutlipleRealms2() throws Exception {
310         UsernamePasswordCredentials creds = 
311             new UsernamePasswordCredentials("testuser2", "testpass2");
312         
313         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
314         handlerchain.appendHandler(new AuthRequestHandler(creds, "test2"));
315         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
316 
317         HttpState state = new HttpState();
318         AuthScope realm1 = new AuthScope(
319             this.server.getLocalAddress(), 
320             this.server.getLocalPort(),
321             "test");
322         AuthScope realm2 = new AuthScope(
323             this.server.getLocalAddress(), 
324             this.server.getLocalPort(),
325             "test2");
326         state.setCredentials(realm1, new UsernamePasswordCredentials("testuser","testpass"));
327         state.setCredentials(realm2, new UsernamePasswordCredentials("testuser2","testpass2"));
328         this.client.setState(state);
329 
330         this.server.setRequestHandler(handlerchain);
331         
332         GetMethod httpget = new GetMethod("/test2/");
333         try {
334             this.client.executeMethod(httpget);
335         } finally {
336             httpget.releaseConnection();
337         }
338         assertNotNull(httpget.getStatusLine());
339         assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
340         Header auth = httpget.getRequestHeader("Authorization");
341         assertNotNull(auth);
342         String expected = "Basic " + EncodingUtil.getAsciiString(
343             Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser2:testpass2")));
344         assertEquals(expected, auth.getValue());
345         AuthState authstate = httpget.getHostAuthState();
346         assertNotNull(authstate.getAuthScheme());
347         assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
348         assertEquals("test2", authstate.getRealm());
349     }
350 
351     public void testPreemptiveAuthorizationTrueWithCreds() throws Exception {
352         UsernamePasswordCredentials creds = 
353             new UsernamePasswordCredentials("testuser", "testpass");
354         
355         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
356         handlerchain.appendHandler(new AuthRequestHandler(creds));
357         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
358 
359         HttpState state = new HttpState();
360         state.setCredentials(AuthScope.ANY, creds);
361         this.client.setState(state);
362         this.client.getParams().setAuthenticationPreemptive(true);
363         
364         this.server.setRequestHandler(handlerchain);
365 
366         GetMethod httpget = new GetMethod("/test/");
367         try {
368             this.client.executeMethod(httpget);
369         } finally {
370             httpget.releaseConnection();
371         }
372         assertNotNull(httpget.getStatusLine());
373         assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
374         Header auth = httpget.getRequestHeader("Authorization");
375         assertNotNull(auth);
376         String expected = "Basic " + EncodingUtil.getAsciiString(
377             Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
378         assertEquals(expected, auth.getValue());
379         AuthState authstate = httpget.getHostAuthState();
380         assertNotNull(authstate.getAuthScheme());
381         assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
382         assertNull(authstate.getRealm());
383         assertTrue(authstate.isPreemptive());
384     }
385 
386     public void testPreemptiveAuthorizationTrueWithoutCreds() throws Exception {
387         UsernamePasswordCredentials creds = 
388             new UsernamePasswordCredentials("testuser", "testpass");
389         
390         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
391         handlerchain.appendHandler(new AuthRequestHandler(creds));
392         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
393 
394         HttpState state = new HttpState();
395         this.client.setState(state);
396         this.client.getParams().setAuthenticationPreemptive(true);
397         
398         this.server.setRequestHandler(handlerchain);
399 
400         GetMethod httpget = new GetMethod("/test/");
401         try {
402             this.client.executeMethod(httpget);
403         } finally {
404             httpget.releaseConnection();
405         }
406         assertNotNull(httpget.getStatusLine());
407         assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode());
408         Header auth = httpget.getRequestHeader("Authorization");
409         assertNull(auth);
410         AuthState authstate = httpget.getHostAuthState();
411         assertNotNull(authstate.getAuthScheme());
412         assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
413         assertNotNull(authstate.getRealm());
414         assertTrue(authstate.isPreemptive());
415     }
416 
417     public void testCustomAuthorizationHeader() throws Exception {
418         UsernamePasswordCredentials creds = 
419             new UsernamePasswordCredentials("testuser", "testpass");
420         
421         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
422         handlerchain.appendHandler(new AuthRequestHandler(creds));
423         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
424 
425         this.server.setRequestHandler(handlerchain);
426 
427         GetMethod httpget = new GetMethod("/test/");
428         String authResponse = "Basic " + EncodingUtil.getAsciiString(
429                 Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
430         httpget.addRequestHeader(new Header("Authorization", authResponse));
431         try {
432             this.client.executeMethod(httpget);
433         } finally {
434             httpget.releaseConnection();
435         }
436         assertNotNull(httpget.getStatusLine());
437         assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
438     }
439     
440     public void testHeadBasicAuthentication() throws Exception {
441         UsernamePasswordCredentials creds = 
442             new UsernamePasswordCredentials("testuser", "testpass");
443         
444         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
445         handlerchain.appendHandler(new AuthRequestHandler(creds));
446         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
447 
448         HttpState state = new HttpState();
449         AuthScope authscope = new AuthScope(
450             this.server.getLocalAddress(), 
451             this.server.getLocalPort(),
452             "test");
453         state.setCredentials(authscope, creds);
454         this.client.setState(state);
455 
456         this.server.setRequestHandler(handlerchain);
457 
458         HeadMethod head = new HeadMethod("/test/");
459         try {
460             this.client.executeMethod(head);
461         } finally {
462             head.releaseConnection();
463         }
464         assertNotNull(head.getStatusLine());
465         assertEquals(HttpStatus.SC_OK, head.getStatusLine().getStatusCode());
466         Header auth = head.getRequestHeader("Authorization");
467         assertNotNull(auth);
468         String expected = "Basic " + EncodingUtil.getAsciiString(
469             Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
470         assertEquals(expected, auth.getValue());
471         AuthState authstate = head.getHostAuthState();
472         assertNotNull(authstate.getAuthScheme());
473         assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
474         assertEquals("test", authstate.getRealm());
475     }
476 
477     public void testPostBasicAuthentication() throws Exception {
478         UsernamePasswordCredentials creds = 
479             new UsernamePasswordCredentials("testuser", "testpass");
480         
481         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
482         handlerchain.appendHandler(new AuthRequestHandler(creds));
483         handlerchain.appendHandler(new HttpServiceHandler(new EchoService()));
484 
485         HttpState state = new HttpState();
486         AuthScope authscope = new AuthScope(
487             this.server.getLocalAddress(), 
488             this.server.getLocalPort(),
489             "test");
490         state.setCredentials(authscope, creds);
491         this.client.setState(state);
492 
493         this.server.setRequestHandler(handlerchain);
494 
495         PostMethod post = new PostMethod("/test/");
496         post.setRequestEntity(new StringRequestEntity("Test body", null, null));
497         try {
498             this.client.executeMethod(post);
499             assertEquals("Test body", post.getResponseBodyAsString());
500         } finally {
501             post.releaseConnection();
502         }
503         assertNotNull(post.getStatusLine());
504         assertEquals(HttpStatus.SC_OK, post.getStatusLine().getStatusCode());
505         Header auth = post.getRequestHeader("Authorization");
506         assertNotNull(auth);
507         String expected = "Basic " + EncodingUtil.getAsciiString(
508             Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
509         assertEquals(expected, auth.getValue());
510         AuthState authstate = post.getHostAuthState();
511         assertNotNull(authstate.getAuthScheme());
512         assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
513         assertEquals("test", authstate.getRealm());
514     }
515     
516     public void testPutBasicAuthentication() throws Exception {
517         UsernamePasswordCredentials creds = 
518             new UsernamePasswordCredentials("testuser", "testpass");
519         
520         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
521         handlerchain.appendHandler(new AuthRequestHandler(creds));
522         handlerchain.appendHandler(new HttpServiceHandler(new EchoService()));
523 
524         HttpState state = new HttpState();
525         AuthScope authscope = new AuthScope(
526             this.server.getLocalAddress(), 
527             this.server.getLocalPort(),
528             "test");
529         state.setCredentials(authscope, creds);
530         this.client.setState(state);
531 
532         this.server.setRequestHandler(handlerchain);
533 
534         PutMethod put = new PutMethod("/test/");
535         put.setRequestEntity(new StringRequestEntity("Test body", null, null));
536         try {
537             this.client.executeMethod(put);
538             assertEquals("Test body", put.getResponseBodyAsString());
539         } finally {
540             put.releaseConnection();
541         }
542         assertNotNull(put.getStatusLine());
543         assertEquals(HttpStatus.SC_OK, put.getStatusLine().getStatusCode());
544         Header auth = put.getRequestHeader("Authorization");
545         assertNotNull(auth);
546         String expected = "Basic " + EncodingUtil.getAsciiString(
547             Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
548         assertEquals(expected, auth.getValue());
549         AuthState authstate = put.getHostAuthState();
550         assertNotNull(authstate.getAuthScheme());
551         assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
552         assertEquals("test", authstate.getRealm());
553     }
554 
555     public void testPreemptiveAuthorizationFailure() throws Exception {
556         UsernamePasswordCredentials creds = 
557             new UsernamePasswordCredentials("testuser", "testpass");
558         UsernamePasswordCredentials wrongcreds = 
559             new UsernamePasswordCredentials("testuser", "garbage");
560         
561         HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
562         handlerchain.appendHandler(new AuthRequestHandler(creds));
563         handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
564 
565         HttpState state = new HttpState();
566         state.setCredentials(AuthScope.ANY, wrongcreds);
567         this.client.setState(state);
568         this.client.getParams().setAuthenticationPreemptive(true);
569         
570         this.server.setRequestHandler(handlerchain);
571 
572         GetMethod httpget = new GetMethod("/test/");
573         try {
574             this.client.executeMethod(httpget);
575         } finally {
576             httpget.releaseConnection();
577         }
578         assertNotNull(httpget.getStatusLine());
579         assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode());
580         AuthState authstate = httpget.getHostAuthState();
581         assertNotNull(authstate.getAuthScheme());
582         assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
583         assertEquals("test", authstate.getRealm());
584         assertTrue(authstate.isPreemptive());
585     }
586     
587 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/auth/TestChallengeParser.html100644 0 0 21071 10661532627 30624 0ustar 0 0 TestChallengeParser xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestChallengeParser.java,v 1.1 2004/03/25 20:37:20 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient.auth;
33  
34  import junit.framework.Test;
35  import junit.framework.TestCase;
36  import junit.framework.TestSuite;
37  import java.util.Map;
38  import org.apache.commons.httpclient.auth.AuthChallengeParser;
39  import org.apache.commons.httpclient.auth.MalformedChallengeException; 
40  
41  /**
42   * Unit tests for {@link AuthChallengeParser}.
43   *
44   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
45   */
46  public class TestChallengeParser extends TestCase {
47  
48      // ------------------------------------------------------------ Constructor
49      public TestChallengeParser(String testName) {
50          super(testName);
51      }
52  
53      // ------------------------------------------------------------------- Main
54      public static void main(String args[]) {
55          String[] testCaseName = { TestChallengeParser.class.getName() };
56          junit.textui.TestRunner.main(testCaseName);
57      }
58  
59      // ------------------------------------------------------- TestCase Methods
60  
61      public static Test suite() {
62          return new TestSuite(TestChallengeParser.class);
63      }
64  
65  
66      public void testParsingChallenge() {
67          String challenge = 
68            "Basic realm=\"realm1\", test, test1 =  stuff, test2 =  \"stuff, stuff\", test3=\"crap";
69          String scheme = null;
70          Map elements = null;
71          try {
72              scheme = AuthChallengeParser.extractScheme(challenge);
73              elements = AuthChallengeParser.extractParams(challenge);
74          } catch (MalformedChallengeException e) {
75              fail("Unexpected exception: " + e.toString());
76          }
77          assertEquals("basic", scheme);
78          assertEquals("realm1", elements.get("realm"));
79          assertEquals(null, elements.get("test"));
80          assertEquals("stuff", elements.get("test1"));
81          assertEquals("stuff, stuff", elements.get("test2"));
82          assertEquals("\"crap", elements.get("test3"));
83      }
84  }

././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/auth/TestChallengeProcessor.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/auth/TestChallengeProcessor.html100644 0 0 40066 10661532627 31354 0ustar 0 0 TestChallengeProcessor xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestChallengeProcessor.java,v 1.1 2004/03/25 20:37:20 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   * [Additional notices, if required by prior licensing conditions]
29   *
30   */
31  
32  package org.apache.commons.httpclient.auth;
33  
34  import java.util.ArrayList;
35  import java.util.HashMap;
36  import java.util.List;
37  import java.util.Map;
38  
39  import junit.framework.Test;
40  import junit.framework.TestCase;
41  import junit.framework.TestSuite;
42  
43  import org.apache.commons.httpclient.params.DefaultHttpParams;
44  import org.apache.commons.httpclient.params.HttpParams;
45  
46  /**
47   * Unit tests for {@link testParsingChallenge}.
48   *
49   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
50   */
51  public class TestChallengeProcessor extends TestCase {
52  
53      // ------------------------------------------------------------ Constructor
54      public TestChallengeProcessor(String testName) {
55          super(testName);
56      }
57  
58      // ------------------------------------------------------------------- Main
59      public static void main(String args[]) {
60          String[] testCaseName = { TestChallengeProcessor.class.getName() };
61          junit.textui.TestRunner.main(testCaseName);
62      }
63  
64      // ------------------------------------------------------- TestCase Methods
65  
66      public static Test suite() {
67          return new TestSuite(TestChallengeProcessor.class);
68      }
69  
70  
71      public void testChallengeSelection() throws Exception {
72          List authPrefs = new ArrayList(3);
73          authPrefs.add(AuthPolicy.NTLM);
74          authPrefs.add(AuthPolicy.DIGEST);
75          authPrefs.add(AuthPolicy.BASIC);
76          HttpParams httpparams = new DefaultHttpParams(); 
77          httpparams.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
78          
79          AuthChallengeProcessor processor = new AuthChallengeProcessor(httpparams);
80  
81          Map map = new HashMap(); 
82          map.put("unknown", "unknown realm=\"whatever\"");
83          map.put("basic", "basic realm=\"whatever\"");
84          
85          AuthScheme authscheme = processor.selectAuthScheme(map);
86          assertTrue(authscheme instanceof BasicScheme);
87      }
88  
89  
90      public void testInvalidChallenge() throws Exception {
91          List authPrefs = new ArrayList(3);
92          authPrefs.add("unsupported1");
93          authPrefs.add("unsupported2");
94          HttpParams httpparams = new DefaultHttpParams(); 
95          httpparams.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
96          
97          AuthChallengeProcessor processor = new AuthChallengeProcessor(httpparams);
98  
99          Map map = new HashMap(); 
100         map.put("unsupported1", "unsupported1 realm=\"whatever\"");
101         map.put("unsupported2", "unsupported2 realm=\"whatever\"");
102         try {
103             AuthScheme authscheme = processor.selectAuthScheme(map);
104             fail("AuthChallengeException should have been thrown");
105         } catch (AuthChallengeException e) {
106             //ignore
107         }
108     }
109 
110 
111     public void testUnsupportedChallenge() throws Exception {
112         List authPrefs = new ArrayList(3);
113         authPrefs.add(AuthPolicy.NTLM);
114         authPrefs.add(AuthPolicy.BASIC);
115         authPrefs.add(AuthPolicy.DIGEST);
116         HttpParams httpparams = new DefaultHttpParams(); 
117         httpparams.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
118         
119         AuthChallengeProcessor processor = new AuthChallengeProcessor(httpparams);
120 
121         Map map = new HashMap(); 
122         map.put("unsupported1", "unsupported1 realm=\"whatever\"");
123         map.put("unsupported2", "unsupported2 realm=\"whatever\"");
124         
125         try {
126             AuthScheme authscheme = processor.selectAuthScheme(map);
127             fail("AuthChallengeException should have been thrown");
128         } catch (AuthChallengeException e) {
129             //expected
130         }
131     }
132 
133     public void testChallengeProcessing() throws Exception {
134         HttpParams httpparams = new DefaultHttpParams(); 
135         AuthChallengeProcessor processor = new AuthChallengeProcessor(httpparams);
136 
137         Map map = new HashMap(); 
138         map.put("basic", "basic realm=\"whatever\", param=\"value\"");
139         
140         AuthState authstate = new AuthState();
141         
142         AuthScheme authscheme = processor.processChallenge(authstate, map);
143         assertTrue(authscheme instanceof BasicScheme);
144         assertEquals("whatever", authscheme.getRealm());
145         assertEquals(authscheme, authstate.getAuthScheme());
146         assertEquals("value", authscheme.getParameter("param"));
147     }
148 
149     public void testInvalidChallengeProcessing() throws Exception {
150         HttpParams httpparams = new DefaultHttpParams(); 
151         AuthChallengeProcessor processor = new AuthChallengeProcessor(httpparams);
152 
153         Map map = new HashMap(); 
154         map.put("basic", "basic realm=\"whatever\", param=\"value\"");
155         
156         AuthState authstate = new AuthState();
157         
158         AuthScheme authscheme = processor.processChallenge(authstate, map);
159         assertTrue(authscheme instanceof BasicScheme);
160         assertEquals("whatever", authscheme.getRealm());
161         assertEquals(authscheme, authstate.getAuthScheme());
162         assertEquals("value", authscheme.getParameter("param"));
163 
164         Map map2 = new HashMap(); 
165         map2.put("ntlm", "NTLM");
166         try {
167             // Basic authentication scheme expected
168             authscheme = processor.processChallenge(authstate, map2);
169             fail("AuthenticationException should have been thrown");
170         } catch (AuthenticationException e) {
171             //expected
172         }
173     }
174 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/auth/TestDigestAuth.html100644 0 0 112073 10661532627 27651 0ustar 0 0 TestDigestAuth xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestDigestAuth.java,v 1.2 2004/11/07 12:31:42 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   * 
28   */
29  
30  package org.apache.commons.httpclient.auth;
31  
32  import java.io.IOException;
33  import java.util.Map;
34  
35  import org.apache.commons.httpclient.FakeHttpMethod;
36  import org.apache.commons.httpclient.Header;
37  import org.apache.commons.httpclient.HttpClient;
38  import org.apache.commons.httpclient.HttpStatus;
39  import org.apache.commons.httpclient.HttpVersion;
40  import org.apache.commons.httpclient.UsernamePasswordCredentials;
41  import org.apache.commons.httpclient.protocol.Protocol;
42  import org.apache.commons.httpclient.server.HttpService;
43  import org.apache.commons.httpclient.server.RequestLine;
44  import org.apache.commons.httpclient.server.SimpleHttpServer;
45  import org.apache.commons.httpclient.server.SimpleRequest;
46  import org.apache.commons.httpclient.server.SimpleResponse;
47  
48  import junit.framework.Test;
49  import junit.framework.TestCase;
50  import junit.framework.TestSuite;
51  
52  /**
53   * Test Methods for DigestScheme Authentication.
54   *
55   * @author Rodney Waldhoff
56   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
57   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
58   */
59  public class TestDigestAuth extends TestCase {
60  
61      // ------------------------------------------------------------ Constructor
62      public TestDigestAuth(String testName) {
63          super(testName);
64      }
65  
66      // ------------------------------------------------------------------- Main
67      public static void main(String args[]) {
68          String[] testCaseName = { TestDigestAuth.class.getName() };
69          junit.textui.TestRunner.main(testCaseName);
70      }
71  
72      // ------------------------------------------------------- TestCase Methods
73  
74      public static Test suite() {
75          return new TestSuite(TestDigestAuth.class);
76      }
77  
78      public void testDigestAuthenticationWithNoRealm() throws Exception {
79          String challenge = "Digest";
80          try {
81              AuthScheme authscheme = new DigestScheme();
82              authscheme.processChallenge(challenge);
83              fail("Should have thrown MalformedChallengeException");
84          } catch(MalformedChallengeException e) {
85              // expected
86          }
87      }
88  
89      public void testDigestAuthenticationWithNoRealm2() throws Exception {
90          String challenge = "Digest ";
91          try {
92              AuthScheme authscheme = new DigestScheme();
93              authscheme.processChallenge(challenge);
94              fail("Should have thrown MalformedChallengeException");
95          } catch(MalformedChallengeException e) {
96              // expected
97          }
98      }
99  
100     public void testDigestAuthenticationWithDefaultCreds() throws Exception {
101         String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
102         FakeHttpMethod method = new FakeHttpMethod("/");
103         UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password");
104         AuthScheme authscheme = new DigestScheme();
105         authscheme.processChallenge(challenge);
106         String response = authscheme.authenticate(cred, method);
107         Map table = AuthChallengeParser.extractParams(response);
108         assertEquals("username", table.get("username"));
109         assertEquals("realm1", table.get("realm"));
110         assertEquals("/", table.get("uri"));
111         assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
112         assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response"));
113     }
114 
115     public void testDigestAuthentication() throws Exception {
116         String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
117         UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password");
118         FakeHttpMethod method = new FakeHttpMethod("/");
119         AuthScheme authscheme = new DigestScheme();
120         authscheme.processChallenge(challenge);
121         String response = authscheme.authenticate(cred, method);
122         Map table = AuthChallengeParser.extractParams(response);
123         assertEquals("username", table.get("username"));
124         assertEquals("realm1", table.get("realm"));
125         assertEquals("/", table.get("uri"));
126         assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
127         assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response"));
128     }
129 
130     public void testDigestAuthenticationWithQueryStringInDigestURI() throws Exception {
131         String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
132         UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password");
133         FakeHttpMethod method = new FakeHttpMethod("/");
134         method.setQueryString("param=value");
135         AuthScheme authscheme = new DigestScheme();
136         authscheme.processChallenge(challenge);
137         String response = authscheme.authenticate(cred, method);
138         Map table = AuthChallengeParser.extractParams(response);
139         assertEquals("username", table.get("username"));
140         assertEquals("realm1", table.get("realm"));
141         assertEquals("/?param=value", table.get("uri"));
142         assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
143         assertEquals("a847f58f5fef0bc087bcb9c3eb30e042", table.get("response"));
144     }
145 
146     public void testDigestAuthenticationWithMultipleRealms() throws Exception {
147         String challenge1 = "Digest realm=\"realm1\", nonce=\"abcde\"";
148         String challenge2 = "Digest realm=\"realm2\", nonce=\"123546\"";
149         UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password");
150         UsernamePasswordCredentials cred2 = new UsernamePasswordCredentials("uname2","password2");
151 
152         FakeHttpMethod method = new FakeHttpMethod("/");
153         AuthScheme authscheme1 = new DigestScheme();
154         authscheme1.processChallenge(challenge1);
155         String response1 = authscheme1.authenticate(cred, method);
156         Map table = AuthChallengeParser.extractParams(response1);
157         assertEquals("username", table.get("username"));
158         assertEquals("realm1", table.get("realm"));
159         assertEquals("/", table.get("uri"));
160         assertEquals("abcde", table.get("nonce"));
161         assertEquals("786f500303eac1478f3c2865e676ed68", table.get("response"));
162 
163         AuthScheme authscheme2 = new DigestScheme();
164         authscheme2.processChallenge(challenge2);
165         String response2 = authscheme2.authenticate(cred2, method);
166         table = AuthChallengeParser.extractParams(response2);
167         assertEquals("uname2", table.get("username"));
168         assertEquals("realm2", table.get("realm"));
169         assertEquals("/", table.get("uri"));
170         assertEquals("123546", table.get("nonce"));
171         assertEquals("0283edd9ef06a38b378b3b74661391e9", table.get("response"));
172     }
173 
174     /** 
175      * Test digest authentication using the MD5-sess algorithm.
176      */
177     public void testDigestAuthenticationMD5Sess() throws Exception {
178         // Example using Digest auth with MD5-sess
179 
180         String realm="realm";
181         String username="username";
182         String password="password";
183         String nonce="e273f1776275974f1a120d8b92c5b3cb";
184 
185         String challenge="Digest realm=\"" + realm + "\", "
186             + "nonce=\"" + nonce + "\", "
187             + "opaque=\"SomeString\", "
188             + "stale=false, "
189             + "algorithm=MD5-sess, "
190             + "qop=\"auth,auth-int\""; // we pass both but expect auth to be used
191 
192         UsernamePasswordCredentials cred =
193             new UsernamePasswordCredentials(username, password);
194         FakeHttpMethod method = new FakeHttpMethod("/");
195 
196         AuthScheme authscheme = new DigestScheme();
197         authscheme.processChallenge(challenge);
198         String response = authscheme.authenticate(cred, method);
199         assertTrue(response.indexOf("nc=00000001") > 0); // test for quotes
200         assertTrue(response.indexOf("qop=auth") > 0); // test for quotes
201         Map table = AuthChallengeParser.extractParams(response);
202         assertEquals(username, table.get("username"));
203         assertEquals(realm, table.get("realm"));
204         assertEquals("MD5-sess", table.get("algorithm"));
205         assertEquals("/", table.get("uri"));
206         assertEquals(nonce, table.get("nonce"));
207         assertEquals(1, Integer.parseInt((String) table.get("nc"),16));
208         assertTrue(null != table.get("cnonce"));
209         assertEquals("SomeString", table.get("opaque"));
210         assertEquals("auth", table.get("qop"));
211         //@TODO: add better check
212         assertTrue(null != table.get("response")); 
213     }
214 
215     /** 
216      * Test digest authentication using the MD5-sess algorithm.
217      */
218     public void testDigestAuthenticationMD5SessNoQop() throws Exception {
219         // Example using Digest auth with MD5-sess
220 
221         String realm="realm";
222         String username="username";
223         String password="password";
224         String nonce="e273f1776275974f1a120d8b92c5b3cb";
225 
226         String challenge="Digest realm=\"" + realm + "\", "
227             + "nonce=\"" + nonce + "\", "
228             + "opaque=\"SomeString\", "
229             + "stale=false, "
230             + "algorithm=MD5-sess";
231 
232         UsernamePasswordCredentials cred =
233             new UsernamePasswordCredentials(username, password);
234         FakeHttpMethod method = new FakeHttpMethod("/");
235 
236         AuthScheme authscheme = new DigestScheme();
237         authscheme.processChallenge(challenge);
238         String response = authscheme.authenticate(cred, method);
239 
240         Map table = AuthChallengeParser.extractParams(response);
241         assertEquals(username, table.get("username"));
242         assertEquals(realm, table.get("realm"));
243         assertEquals("MD5-sess", table.get("algorithm"));
244         assertEquals("/", table.get("uri"));
245         assertEquals(nonce, table.get("nonce"));
246         assertTrue(null == table.get("nc"));
247         assertEquals("SomeString", table.get("opaque"));
248         assertTrue(null == table.get("qop"));
249         //@TODO: add better check
250         assertTrue(null != table.get("response")); 
251     }
252 
253     /** 
254      * Test digest authentication with invalud qop value
255      */
256     public void testDigestAuthenticationMD5SessInvalidQop() throws Exception {
257         // Example using Digest auth with MD5-sess
258 
259         String realm="realm";
260         String username="username";
261         String password="password";
262         String nonce="e273f1776275974f1a120d8b92c5b3cb";
263 
264         String challenge="Digest realm=\"" + realm + "\", "
265             + "nonce=\"" + nonce + "\", "
266             + "opaque=\"SomeString\", "
267             + "stale=false, "
268             + "algorithm=MD5-sess, "
269             + "qop=\"jakarta\""; // jakarta is an invalid qop value
270 
271         UsernamePasswordCredentials cred =
272             new UsernamePasswordCredentials(username, password);
273         try {
274             AuthScheme authscheme = new DigestScheme();
275             authscheme.processChallenge(challenge);
276             fail("MalformedChallengeException exception expected due to invalid qop value");
277         } catch(MalformedChallengeException e) {
278         }
279     }
280 
281     private class StaleNonceService implements HttpService {
282 
283         public StaleNonceService() {
284             super();
285         }
286 
287         public boolean process(final SimpleRequest request, final SimpleResponse response)
288             throws IOException
289         {
290             RequestLine requestLine = request.getRequestLine();
291             HttpVersion ver = requestLine.getHttpVersion();
292             Header auth = request.getFirstHeader("Authorization");
293             if (auth == null) { 
294                 response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED);
295                 response.addHeader(new Header("WWW-Authenticate", 
296                         "Digest realm=\"realm1\", nonce=\"ABC123\""));
297                 response.setBodyString("Authorization required");
298                 return true;
299             } else {
300                 Map table = AuthChallengeParser.extractParams(auth.getValue());
301                 String nonce = (String)table.get("nonce");
302                 if (nonce.equals("ABC123")) {
303                     response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED);
304                     response.addHeader(new Header("WWW-Authenticate", 
305                             "Digest realm=\"realm1\", nonce=\"321CBA\", stale=\"true\""));
306                     response.setBodyString("Authorization required");
307                     return true;
308                 } else {
309                     response.setStatusLine(ver, HttpStatus.SC_OK);
310                     response.setBodyString("Authorization successful");
311                     return true;
312                 }
313             }
314         }
315     }
316 
317     
318     public void testDigestAuthenticationWithStaleNonce() throws Exception {
319         // configure the server
320         SimpleHttpServer server = new SimpleHttpServer(); // use arbitrary port
321         server.setTestname(getName());
322         server.setHttpService(new StaleNonceService());
323 
324         // configure the client
325         HttpClient client = new HttpClient();
326         client.getHostConfiguration().setHost(
327                 server.getLocalAddress(), server.getLocalPort(),
328                 Protocol.getProtocol("http"));
329         
330         client.getState().setCredentials(AuthScope.ANY, 
331                 new UsernamePasswordCredentials("username","password"));
332         
333         FakeHttpMethod httpget = new FakeHttpMethod("/");
334         try {
335             client.executeMethod(httpget);
336         } finally {
337             httpget.releaseConnection();
338         }
339         assertNotNull(httpget.getStatusLine());
340         assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
341         Map table = AuthChallengeParser.extractParams(
342                 httpget.getRequestHeader("Authorization").getValue());
343         assertEquals("username", table.get("username"));
344         assertEquals("realm1", table.get("realm"));
345         assertEquals("/", table.get("uri"));
346         assertEquals("321CBA", table.get("nonce"));
347         assertEquals("7f5948eefa115296e9279225041527b3", table.get("response"));
348         server.destroy();
349     }
350 
351 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/auth/TestNTLMAuth.html100644 0 0 60063 10661532627 27165 0ustar 0 0 TestNTLMAuth xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestNTLMAuth.java,v 1.2 2004/11/07 12:31:42 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.auth;
31  
32  import java.io.IOException;
33  
34  import junit.framework.Test;
35  import junit.framework.TestSuite;
36  
37  import org.apache.commons.httpclient.FakeHttpMethod;
38  import org.apache.commons.httpclient.Header;
39  import org.apache.commons.httpclient.HttpClientTestBase;
40  import org.apache.commons.httpclient.HttpState;
41  import org.apache.commons.httpclient.HttpStatus;
42  import org.apache.commons.httpclient.HttpVersion;
43  import org.apache.commons.httpclient.NTCredentials;
44  import org.apache.commons.httpclient.methods.GetMethod;
45  import org.apache.commons.httpclient.protocol.Protocol;
46  import org.apache.commons.httpclient.server.HttpService;
47  import org.apache.commons.httpclient.server.RequestLine;
48  import org.apache.commons.httpclient.server.SimpleRequest;
49  import org.apache.commons.httpclient.server.SimpleResponse;
50  
51  /**
52   * Test Methods for NTLM Authentication.
53   *
54   * @author Rodney Waldhoff
55   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
56   * @version $Id: TestNTLMAuth.java 480424 2006-11-29 05:56:49Z bayard $
57   */
58  public class TestNTLMAuth extends HttpClientTestBase {
59  
60      // ------------------------------------------------------------ Constructor
61      public TestNTLMAuth(String testName) throws IOException {
62          super(testName);
63      }
64  
65      // ------------------------------------------------------------------- Main
66      public static void main(String args[]) {
67          String[] testCaseName = { TestNTLMAuth.class.getName() };
68          junit.textui.TestRunner.main(testCaseName);
69      }
70  
71      // ------------------------------------------------------- TestCase Methods
72  
73      public static Test suite() {
74          return new TestSuite(TestNTLMAuth.class);
75      }
76  
77      // --------------------------------- 
78  
79      public void testNTLMAuthenticationResponse1() throws Exception {
80          String challenge = "NTLM";
81          String expected = "NTLM TlRMTVNTUAABAAAABlIAAAYABgAkAAAABAAEACAAAABIT" +
82              "1NURE9NQUlO";
83          NTCredentials cred = new NTCredentials("username","password", "host", "domain");
84          FakeHttpMethod method = new FakeHttpMethod(); 
85          AuthScheme authscheme = new NTLMScheme(challenge);
86          authscheme.processChallenge(challenge);
87          String response = authscheme.authenticate(cred, method);
88          assertEquals(expected, response);
89          assertFalse(authscheme.isComplete());
90      }
91      
92      public void testNTLMAuthenticationResponse2() throws Exception {
93          String challenge = 
94              "NTLM TlRMTVNTUAACAAAACgAKADAAAAAGgoEAPc4kP4LtCV8AAAAAAAAAAJ4AngA" +
95              "6AAAASU5UUkFFUEhPWAIAFABJAE4AVABSAEEARQBQAEgATwBYAAEAEgBCAE8AQQB" +
96              "SAEQAUgBPAE8ATQAEACgAaQBuAHQAcgBhAGUAcABoAG8AeAAuAGUAcABoAG8AeAA" +
97              "uAGMAbwBtAAMAPABCAG8AYQByAGQAcgBvAG8AbQAuAGkAbgB0AHIAYQBlAHAAaAB" +
98              "vAHgALgBlAHAAaABvAHgALgBjAG8AbQAAAAAA";
99  
100         String expected = "NTLM TlRMTVNTUAADAAAAGAAYAFIAAAAAAAAAagAAAAYABgB" +
101             "AAAAACAAIAEYAAAAEAAQATgAAAAAAAABqAAAABlIAAERPTUFJTlVTRVJOQU1FSE" +
102             "9TVAaC+vLxUEHnUtpItj9Dp4kzwQfd61Lztg==";
103         NTCredentials cred = new NTCredentials("username","password", "host", "domain");
104         FakeHttpMethod method = new FakeHttpMethod(); 
105         AuthScheme authscheme = new NTLMScheme(challenge);
106         authscheme.processChallenge(challenge);
107         String response = authscheme.authenticate(cred, method);
108         assertEquals(expected, response);
109         assertTrue(authscheme.isComplete());
110     }
111 
112     private class NTLMAuthService implements HttpService {
113 
114         public NTLMAuthService() {
115             super();
116         }
117 
118         public boolean process(final SimpleRequest request, final SimpleResponse response)
119             throws IOException
120         {
121             RequestLine requestLine = request.getRequestLine();
122             HttpVersion ver = requestLine.getHttpVersion();
123             Header auth = request.getFirstHeader("Authorization");
124             if (auth == null) { 
125                 response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED);
126                 response.addHeader(new Header("WWW-Authenticate", "NTLM"));
127                 response.setBodyString("Authorization required");
128                 return true;
129             } else {
130                 String authstr = auth.getValue();
131                 
132                 if (authstr.equals("NTLM TlRMTVNTUAABAAAABlIAAAYABgAkAAAABAAEACAAAABIT1NURE9NQUlO")) {
133                     response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED);
134                     response.addHeader(new Header("WWW-Authenticate", 
135                             "NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA=="));
136                     response.setBodyString("Authorization required");
137                     return true;
138                 } if (authstr.equals("NTLM TlRMTVNTUAADAAAAGAAYAFIAAAAAAAAAagAAAAYABgBAAAAACAAIAEYAAAAEAAQATgAAAAAAAABqAAAABlIAAERPTUFJTlVTRVJOQU1FSE9TVJxndWIt46bHm11TPrt5Z6wrz7ziq04yRA==")) {
139                     response.setStatusLine(ver, HttpStatus.SC_OK);
140                     response.setBodyString("Authorization successful");
141                     return true;
142                 } else {
143                     response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED);
144                     response.addHeader(new Header("WWW-Authenticate", "NTLM"));
145                     response.setBodyString("Authorization required");
146                     return true;
147                 }
148             }
149         }
150     }
151 
152     
153     public void testNTLMAuthenticationRetry() throws Exception {
154 
155         this.server.setHttpService(new NTLMAuthService());
156 
157         // configure the client
158         this.client.getHostConfiguration().setHost(
159                 server.getLocalAddress(), server.getLocalPort(),
160                 Protocol.getProtocol("http"));
161         
162         this.client.getState().setCredentials(AuthScope.ANY, 
163                 new NTCredentials("username", "password", "host", "domain"));
164         
165         FakeHttpMethod httpget = new FakeHttpMethod("/");
166         try {
167             client.executeMethod(httpget);
168         } finally {
169             httpget.releaseConnection();
170         }
171         assertNull(httpget.getResponseHeader("WWW-Authenticate"));
172         assertEquals(200, httpget.getStatusCode());
173     }
174 
175     private class PreemptiveNTLMAuthService implements HttpService {
176 
177         public PreemptiveNTLMAuthService() {
178             super();
179         }
180 
181         public boolean process(final SimpleRequest request, final SimpleResponse response)
182             throws IOException
183         {
184             RequestLine requestLine = request.getRequestLine();
185             HttpVersion ver = requestLine.getHttpVersion();
186             Header auth = request.getFirstHeader("Authorization");
187             if (auth == null) { 
188                 response.setStatusLine(ver, HttpStatus.SC_BAD_REQUEST);
189                 response.setBodyString("Authorization header missing");
190                 return true;
191             } else {
192                 String authstr = auth.getValue();
193                 
194                 if (authstr.indexOf("NTLM") != -1) {
195                     response.setStatusLine(ver, HttpStatus.SC_OK);
196                     return true;
197                 } else if (authstr.indexOf("Basic") != -1) {
198                     response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED);
199                     response.addHeader(new Header("WWW-Authenticate", "Negotiate"));
200                     response.addHeader(new Header("WWW-Authenticate", "NTLM"));
201                     response.setBodyString("Authorization required");
202                     return true;
203                 } else {
204                     response.setStatusLine(ver, HttpStatus.SC_BAD_REQUEST);
205                     response.setBodyString("Unknown auth type: " + authstr);
206                     return true;
207                 }
208             }
209         }
210     }
211 
212     /**
213      * Make sure preemptive authorization works when the server requires NLM.
214      * @throws Exception
215      */
216     public void testPreemptiveAuthorization() throws Exception {
217 
218         NTCredentials creds = 
219             new NTCredentials("testuser", "testpass", "host", "domain");
220         
221         HttpState state = new HttpState();
222         state.setCredentials(AuthScope.ANY, creds);
223         this.client.setState(state);
224         this.client.getParams().setAuthenticationPreemptive(true);
225 
226         this.server.setHttpService(new PreemptiveNTLMAuthService());
227 
228         GetMethod httpget = new GetMethod("/test/");
229         try {
230             this.client.executeMethod(httpget);
231         } finally {
232             httpget.releaseConnection();
233         }
234         assertNotNull(httpget.getStatusLine());
235         assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
236     }
237     
238     
239 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/auth/package-frame.html100644 0 0 2537 10661532631 27371 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.auth

org.apache.commons.httpclient.auth

Classes

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/auth/package-summary.html100644 0 0 5462 10661532631 27774 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.auth

Package org.apache.commons.httpclient.auth

Class Summary
TestAuthAll
TestBasicAuth
TestChallengeParser
TestChallengeProcessor
TestDigestAuth
TestNTLMAuth

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookie.html100644 0 0 33562 10661532627 27316 0ustar 0 0 TestCookie xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookie.java,v 1.2 2004/04/25 12:25:09 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import java.util.Iterator;
33  import java.util.SortedSet;
34  import java.util.TreeSet;
35  import java.util.Vector;
36  
37  import junit.framework.Test;
38  import junit.framework.TestSuite;
39  
40  import org.apache.commons.httpclient.Cookie;
41  import org.apache.commons.httpclient.Header;
42  
43  
44  /**
45   * Test cases for Cookie
46   *
47   * @author BC Holmes
48   * @author Rod Waldhoff
49   * @author dIon Gillard
50   * @author <a href="mailto:JEvans@Cyveillance.com">John Evans</a>
51   * @author Marc A. Saegesser
52   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
53   * @version $Revision: 480424 $
54   */
55  public class TestCookie extends TestCookieBase {
56  
57  
58      // ------------------------------------------------------------ Constructor
59  
60      public TestCookie(String name) {
61          super(name);
62      }
63  
64      // ------------------------------------------------------- TestCase Methods
65  
66      public static Test suite() {
67          return new TestSuite(TestCookie.class);
68      }
69  
70      /**
71       * Tests default constructor.
72       */
73      public void testDefaultConstuctor() {
74          Cookie dummy = new Cookie();
75          assertEquals( "noname=", dummy.toExternalForm() );
76      }
77  
78      public void testComparator() throws Exception {
79          Header setCookie = null;
80          Cookie[] parsed = null;
81          Vector cookies = new Vector();
82          // Cookie 0
83          setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons;Domain=.apache.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
84          CookieSpec cookiespec = new CookieSpecBase();
85          parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/httpclient", true, setCookie);
86          cookies.add(parsed[0]);
87          // Cookie 1
88          setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons/bif;Domain=.apache.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
89          parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/bif/httpclient", true, setCookie);
90          cookies.add(parsed[0]);
91          // Cookie 2
92          setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons;Domain=.baz.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
93          parsed = cookieParse(cookiespec, ".baz.org", 80, "/commons/httpclient", true, setCookie);
94          cookies.add(parsed[0]);
95          // Cookie 3
96          setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons/bif;Domain=.baz.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
97          parsed = cookieParse(cookiespec, ".baz.org", 80, "/commons/bif/httpclient", true, setCookie);
98          cookies.add(parsed[0]);
99          // Cookie 4
100         setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons;Domain=.baz.com;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
101         parsed = cookieParse(cookiespec, ".baz.com", 80, "/commons/httpclient", true, setCookie);
102         cookies.add(parsed[0]);
103         // The order should be:
104         // 1, 0, 3, 2, 4
105         parsed = (Cookie[])cookies.toArray(new Cookie[0]);
106         SortedSet set = new TreeSet(parsed[0]);
107         int pass = 0;
108         for (Iterator itr = set.iterator(); itr.hasNext();) {
109             Cookie cookie = (Cookie)itr.next();
110             switch (pass) {
111                 case 0:
112                     assertTrue("0th cookie should be cookie[1]", cookie == parsed[1]);
113                     break;
114                 case 1:
115                     assertTrue("1st cookie should be cookie[0]", cookie == parsed[0]);
116                     break;
117                 case 2:
118                     assertTrue("2nd cookie should be cookie[3]", cookie == parsed[3]);
119                     break;
120                 case 3:
121                     assertTrue("3rd cookie should be cookie[2]", cookie == parsed[2]);
122                     break;
123                 case 4:
124                     assertTrue("4th cookie should be cookie[4]", cookie == parsed[4]);
125                     break;
126                 default:
127                     fail("This should never happen.");
128             }
129             pass++;
130         }
131         try {
132             parsed[0].compare("foo", "bar");
133             fail("Should have thrown an exception trying to compare non-cookies");
134         }
135         catch (ClassCastException ex) {
136             // expected
137         }
138     }
139 }
140 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookie2.html100644 0 0 30020 10661532627 27362 0ustar 0 0 TestCookie2 xref

1   /*
2    * $Header: /cvsroot/httpc-cookie2/httpc-cookie2/httpcookie2SVN-patch.082805-2100.diff,v 1.1 2005/08/29 05:01:58 sjain700 Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import java.util.*;
33  
34  import junit.framework.Test;
35  import junit.framework.TestSuite;
36  
37  import org.apache.commons.httpclient.Cookie;
38  import org.apache.commons.httpclient.Header;
39  
40  
41  /**
42   * Test cases for {@link Cookie2}.
43   *
44   * @author Samit Jain (jain.samit@gmail.com)
45   */
46  public class TestCookie2 extends TestCookieBase {
47  
48  
49      // ------------------------------------------------------------ Constructor
50  
51      public TestCookie2(String name) {
52          super(name);
53      }
54  
55      // ------------------------------------------------------- TestCase Methods
56  
57      public static Test suite() {
58          return new TestSuite(TestCookie2.class);
59      }
60  
61      /**
62       * Tests default constructor.
63       */
64      public void testDefaultConstuctor() {
65          Cookie2 dummy = new Cookie2();
66          // check cookie properties (default values)
67          assertNull(dummy.getPorts());
68          assertFalse(dummy.getSecure());
69          assertFalse(dummy.isExpired());
70          assertFalse(dummy.isDomainAttributeSpecified());
71          assertFalse(dummy.isPathAttributeSpecified());
72          assertFalse(dummy.isPortAttributeSpecified());
73          assertFalse(dummy.isVersionAttributeSpecified());
74          assertFalse(dummy.isPersistent());
75  
76          Cookie2 dummy2 = new Cookie2();
77          assertEquals(dummy, dummy2);
78      }
79  
80      public void testComparator() throws Exception {
81          Header setCookie2 = null;
82          Cookie[] parsed = null;
83          List cookies = new LinkedList();
84          CookieSpec cookiespec = new RFC2965Spec();
85          // Cookie 0
86          setCookie2 = new Header("Set-Cookie2","cookie-name=Cookie0; Version=1");
87          parsed = cookieParse(cookiespec, "domain.com", 80,
88                               "/path/path1", true, setCookie2);
89          cookies.add(parsed[0]);
90          // Cookie 1
91          setCookie2 = new Header("Set-Cookie2","cookie-name=Cookie1; Version=1");
92          parsed = cookieParse(cookiespec, "domain.com", 80, "/path", true, setCookie2);
93          cookies.add(parsed[0]);
94          // Cookie 2
95          setCookie2 = new Header("Set-Cookie2","cookie-name=Cookie2; Version=1");
96          parsed = cookieParse(cookiespec, "domain.com", 80, "/", true, setCookie2);
97          cookies.add(parsed[0]);
98          // Cookie 3
99          setCookie2 = new Header("Set-Cookie2","cookie-name=Cookie3; Version=1");
100         parsed = cookieParse(cookiespec, "domain.com", 80,
101                              "/path/path1/path2", true, setCookie2);
102         cookies.add(parsed[0]);
103         // Cookie 4
104         setCookie2 = new Header("Set-Cookie2","cookie-name=Cookie4; Version=1");
105         parsed = cookieParse(cookiespec, "domain.com", 80,
106                              "/path/path1/path2/path3", true, setCookie2);
107         cookies.add(parsed[0]);
108 
109         // The ascending order should be:
110         // 2, 1, 0, 3, 4
111         int[] expectedOrder = new int[] {2, 1, 0, 3, 4};
112         Set sortedCookies = new TreeSet(parsed[0]);
113         sortedCookies.addAll(cookies);
114 
115         int pass = 0;
116         for (Iterator itr = sortedCookies.iterator(); itr.hasNext(); ++pass) {
117             Cookie2 cookie = (Cookie2) itr.next();
118             assertTrue("sortedCookies[" + pass + "] should be cookies[" + expectedOrder[pass] + "]",
119                        cookie == cookies.get(expectedOrder[pass]));
120         }
121 
122         try {
123             parsed[0].compare(parsed[0], "foo");
124             fail("Should have thrown an exception trying to compare non-cookies");
125         } catch (ClassCastException expected) {}
126     }
127 }
128 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieAll.html100644 0 0 14610 10661532627 27740 0ustar 0 0 TestCookieAll xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieAll.java,v 1.3 2004/12/24 20:36:13 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   */
28  
29  package org.apache.commons.httpclient.cookie;
30  
31  import junit.framework.*;
32  
33  /**
34   * @author oleg Kalnichevski 
35   * 
36   * @version $Id: TestCookieAll.java 480424 2006-11-29 05:56:49Z bayard $
37   */
38  public class TestCookieAll extends TestCase {
39  
40      public TestCookieAll(String testName) {
41          super(testName);
42      }
43  
44      public static Test suite() {
45          TestSuite suite = new TestSuite();
46          suite.addTest(TestCookie.suite());
47          suite.addTest(TestCookie2.suite());
48          suite.addTest(TestCookieCompatibilitySpec.suite());
49          suite.addTest(TestCookieRFC2109Spec.suite());
50          suite.addTest(TestCookieRFC2965Spec.suite());
51          suite.addTest(TestCookieNetscapeDraft.suite());
52          suite.addTest(TestCookieIgnoreSpec.suite());
53          suite.addTest(TestCookiePolicy.suite());
54          suite.addTest(TestDateParser.suite());
55          suite.addTest(TestCookiePathComparator.suite());
56          suite.addTest(TestCookieVersionSupport.suite());
57          return suite;
58      }
59  
60      public static void main(String args[]) {
61          String[] testCaseName = { TestCookieAll.class.getName() };
62          junit.textui.TestRunner.main(testCaseName);
63      }
64  
65  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieBase.html100644 0 0 15004 10661532627 30100 0ustar 0 0 TestCookieBase xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieBase.java,v 1.1 2004/04/24 19:39:24 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import junit.framework.TestCase;
33  
34  import org.apache.commons.httpclient.Cookie;
35  import org.apache.commons.httpclient.Header;
36  
37  /**
38   * Test cases for Cookie
39   *
40   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
41   * @version $Revision: 480424 $
42   */
43  public class TestCookieBase extends TestCase {
44  
45      // ------------------------------------------------------------ Constructor
46  
47      public TestCookieBase(String name) {
48          super(name);
49      }
50  
51      public static Cookie[] cookieParse(
52          final CookieSpec parser,
53          String host,
54          int port,
55          String path,
56          boolean isSecure,
57          Header setHeader)
58          throws MalformedCookieException {
59          Cookie[] cookies = parser.parse(host, port, path, isSecure, setHeader);
60          if (cookies != null) {
61              for (int i = 0; i < cookies.length; i++) {
62                  parser.validate(host, port, path, isSecure, cookies[i]);
63              }
64          }
65          return cookies;
66      }
67  }

././@LongLink100644 0 0 154 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieCompatibilitySpec.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieCompatibilitySp100644 0 0 336507 10661532627 31435 0ustar 0 0 TestCookieCompatibilitySpec xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieCompatibilitySpec.java,v 1.7 2004/09/14 20:11:32 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import java.util.Collection;
33  import java.util.Date;
34  
35  import junit.framework.Test;
36  import junit.framework.TestSuite;
37  
38  import org.apache.commons.httpclient.Cookie;
39  import org.apache.commons.httpclient.Header;
40  import org.apache.commons.httpclient.HttpException;
41  import org.apache.commons.httpclient.HttpState;
42  import org.apache.commons.httpclient.NameValuePair;
43  import org.apache.commons.httpclient.params.DefaultHttpParamsFactory;
44  import org.apache.commons.httpclient.params.HttpMethodParams;
45  import org.apache.commons.httpclient.params.HttpParams;
46  
47  
48  /**
49   * Test cases for Cookie
50   *
51   * @author BC Holmes
52   * @author Rod Waldhoff
53   * @author dIon Gillard
54   * @author <a href="mailto:JEvans@Cyveillance.com">John Evans</a>
55   * @author Marc A. Saegesser
56   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
57   * @version $Revision: 480424 $
58   */
59  public class TestCookieCompatibilitySpec extends TestCookieBase {
60  
61  
62      // ------------------------------------------------------------ Constructor
63  
64  
65      public TestCookieCompatibilitySpec(String name) {
66          super(name);
67      }
68  
69  
70      // ------------------------------------------------------- TestCase Methods
71  
72  
73      public static Test suite() {
74          return new TestSuite(TestCookieCompatibilitySpec.class);
75      }
76  
77      public void testParseAttributeInvalidAttrib() throws Exception {
78          CookieSpec cookiespec = new CookieSpecBase();
79          try {
80              cookiespec.parseAttribute(null, null);
81              fail("IllegalArgumentException must have been thrown");
82          } catch (IllegalArgumentException expected) {
83          }
84      }
85  
86      public void testParseAttributeInvalidCookie() throws Exception {
87          CookieSpec cookiespec = new CookieSpecBase();
88          try {
89              cookiespec.parseAttribute(new NameValuePair("name", "value"), null);
90              fail("IllegalArgumentException must have been thrown");
91          } catch (IllegalArgumentException expected) {
92          }
93      }
94  
95      public void testParseAttributeNullPath() throws Exception {
96          CookieSpec cookiespec = new CookieSpecBase();
97          Cookie cookie = new Cookie();
98          cookiespec.parseAttribute(new NameValuePair("path", null), cookie);
99          assertEquals("/", cookie.getPath());
100     }
101 
102     public void testParseAttributeBlankPath() throws Exception {
103         CookieSpec cookiespec = new CookieSpecBase();
104         Cookie cookie = new Cookie();
105         cookiespec.parseAttribute(new NameValuePair("path", "   "), cookie);
106         assertEquals("/", cookie.getPath());
107     }
108 
109     public void testParseAttributeNullDomain() throws Exception {
110         CookieSpec cookiespec = new CookieSpecBase();
111         Cookie cookie = new Cookie();
112         try {
113             cookiespec.parseAttribute(new NameValuePair("domain", null), cookie);
114             fail("MalformedCookieException must have been thrown");
115         } catch (MalformedCookieException expected) {
116         }
117     }
118 
119     public void testParseAttributeBlankDomain() throws Exception {
120         CookieSpec cookiespec = new CookieSpecBase();
121         Cookie cookie = new Cookie();
122         try {
123             cookiespec.parseAttribute(new NameValuePair("domain", "   "), cookie);
124             fail("MalformedCookieException must have been thrown");
125         } catch (MalformedCookieException expected) {
126         }
127     }
128 
129     public void testParseAttributeNullMaxAge() throws Exception {
130         CookieSpec cookiespec = new CookieSpecBase();
131         Cookie cookie = new Cookie();
132         try {
133             cookiespec.parseAttribute(new NameValuePair("max-age", null), cookie);
134             fail("MalformedCookieException must have been thrown");
135         } catch (MalformedCookieException expected) {
136         }
137     }
138 
139     public void testParseAttributeInvalidMaxAge() throws Exception {
140         CookieSpec cookiespec = new CookieSpecBase();
141         Cookie cookie = new Cookie();
142         try {
143             cookiespec.parseAttribute(new NameValuePair("max-age", "crap"), cookie);
144             fail("MalformedCookieException must have been thrown");
145         } catch (MalformedCookieException expected) {
146         }
147     }
148 
149     public void testParseAttributeNullExpires() throws Exception {
150         CookieSpec cookiespec = new CookieSpecBase();
151         Cookie cookie = new Cookie();
152         try {
153             cookiespec.parseAttribute(new NameValuePair("expires", null), cookie);
154             fail("MalformedCookieException must have been thrown");
155         } catch (MalformedCookieException expected) {
156         }
157     }
158 
159     public void testParseAttributeUnknownValue() throws Exception {
160         CookieSpec cookiespec = new CookieSpecBase();
161         Cookie cookie = new Cookie();
162         cookiespec.parseAttribute(new NameValuePair("nonsense", null), cookie);
163     }
164     
165     public void testValidateNullHost() throws Exception {
166         CookieSpec cookiespec = new CookieSpecBase();
167         Cookie cookie = new Cookie();
168         try {
169             cookiespec.validate(null, 80, "/", false, cookie);
170             fail("IllegalArgumentException must have been thrown");
171         } catch (IllegalArgumentException expected) {
172         }
173     }
174 
175     public void testValidateBlankHost() throws Exception {
176         CookieSpec cookiespec = new CookieSpecBase();
177         Cookie cookie = new Cookie();
178         try {
179             cookiespec.validate("   ", 80, "/", false, cookie);
180             fail("IllegalArgumentException must have been thrown");
181         } catch (IllegalArgumentException expected) {
182         }
183     }
184 
185     public void testValidateNullPath() throws Exception {
186         CookieSpec cookiespec = new CookieSpecBase();
187         Cookie cookie = new Cookie();
188         try {
189             cookiespec.validate("host", 80, null, false, cookie);
190             fail("IllegalArgumentException must have been thrown");
191         } catch (IllegalArgumentException expected) {
192         }
193     }
194 
195     public void testValidateBlankPath() throws Exception {
196         CookieSpec cookiespec = new CookieSpecBase();
197         Cookie cookie = new Cookie("host", "name", "value", "/", null, false);
198         cookiespec.validate("host", 80, "   ", false, cookie);
199     }
200 
201     public void testValidateInvalidPort() throws Exception {
202         CookieSpec cookiespec = new CookieSpecBase();
203         Cookie cookie = new Cookie();
204         try {
205             cookiespec.validate("host", -80, "/", false, cookie);
206             fail("IllegalArgumentException must have been thrown");
207         } catch (IllegalArgumentException expected) {
208         }
209     }
210 
211     public void testValidateInvalidCookieVersion() throws Exception {
212         CookieSpec cookiespec = new CookieSpecBase();
213         Cookie cookie = new Cookie();
214         cookie.setVersion(-1);
215         try {
216             cookiespec.validate("host", 80, "/", false, cookie);
217             fail("MalformedCookieException must have been thrown");
218         } catch (MalformedCookieException expected) {
219         }
220     }
221 
222     /**
223      * Tests whether domain attribute check is case-insensitive.
224      */
225     public void testDomainCaseInsensitivity() throws Exception {
226         Header header = new Header("Set-Cookie", 
227             "name=value; path=/; domain=.whatever.com");
228 
229         CookieSpec cookiespec = new CookieSpecBase();
230         Cookie[] parsed = cookieParse(cookiespec, "www.WhatEver.com", 80, "/", false, header);
231         assertNotNull(parsed);
232         assertEquals(1, parsed.length);
233         assertEquals(".whatever.com", parsed[0].getDomain());
234     }
235     
236     /**
237      * Test basic parse (with various spacings
238      */
239     public void testParse1() throws Exception {
240         String headerValue = "custno = 12345; comment=test; version=1," +
241             " name=John; version=1; max-age=600; secure; domain=.apache.org";
242 
243         Header header = new Header("set-cookie", headerValue);
244 
245         CookieSpec cookiespec = new CookieSpecBase();
246         Cookie[] cookies = cookieParse(cookiespec, "www.apache.org", 80, "/", false, header);
247         assertEquals(2, cookies.length);
248 
249         assertEquals("custno", cookies[0].getName());
250         assertEquals("12345", cookies[0].getValue());
251         assertEquals("test", cookies[0].getComment());
252         assertEquals(0, cookies[0].getVersion());
253         assertEquals("www.apache.org", cookies[0].getDomain());
254         assertEquals("/", cookies[0].getPath());
255         assertFalse(cookies[0].getSecure());
256 
257         assertEquals("name", cookies[1].getName());
258         assertEquals("John", cookies[1].getValue());
259         assertEquals(null, cookies[1].getComment());
260         assertEquals(0, cookies[1].getVersion());
261         assertEquals(".apache.org", cookies[1].getDomain());
262         assertEquals("/", cookies[1].getPath());
263         assertTrue(cookies[1].getSecure());
264     }
265 
266 
267     /**
268      * Test no spaces
269      */
270     public void testParse2() throws Exception {
271         String headerValue = "custno=12345;comment=test; version=1," +
272             "name=John;version=1;max-age=600;secure;domain=.apache.org";
273 
274         Header header = new Header("set-cookie", headerValue);
275 
276         CookieSpec cookiespec = new CookieSpecBase();
277         Cookie[] cookies = cookieParse(cookiespec, "www.apache.org", 80, "/", false, header);
278 
279         assertEquals(2, cookies.length);
280 
281         assertEquals("custno", cookies[0].getName());
282         assertEquals("12345", cookies[0].getValue());
283         assertEquals("test", cookies[0].getComment());
284         assertEquals(0, cookies[0].getVersion());
285         assertEquals("www.apache.org", cookies[0].getDomain());
286         assertEquals("/", cookies[0].getPath());
287         assertFalse(cookies[0].getSecure());
288 
289         assertEquals("name", cookies[1].getName());
290         assertEquals("John", cookies[1].getValue());
291         assertEquals(null, cookies[1].getComment());
292         assertEquals(0, cookies[1].getVersion());
293         assertEquals(".apache.org", cookies[1].getDomain());
294         assertEquals("/", cookies[1].getPath());
295         assertTrue(cookies[1].getSecure());
296     }
297 
298 
299     /**
300      * Test parse with quoted text
301      */
302     public void testParse3() throws Exception {
303         String headerValue =
304             "name=\"Doe, John\";version=1;max-age=600;secure;domain=.apache.org";
305         Header header = new Header("set-cookie", headerValue);
306 
307         CookieSpec cookiespec = new CookieSpecBase();
308         Cookie[] cookies = cookieParse(cookiespec, "www.apache.org", 80, "/", false, header);
309 
310         assertEquals(1, cookies.length);
311 
312         assertEquals("name", cookies[0].getName());
313         assertEquals("Doe, John", cookies[0].getValue());
314         assertEquals(null, cookies[0].getComment());
315         assertEquals(0, cookies[0].getVersion());
316         assertEquals(".apache.org", cookies[0].getDomain());
317         assertEquals("/", cookies[0].getPath());
318         assertTrue(cookies[0].getSecure());
319     }
320 
321 
322     // see issue #5279
323     public void testQuotedExpiresAttribute() throws Exception {
324         String headerValue = "custno=12345;Expires='Thu, 01-Jan-2070 00:00:10 GMT'";
325 
326         Header header = new Header("set-cookie", headerValue);
327 
328         CookieSpec cookiespec = new CookieSpecBase();
329         Cookie[] cookies = cookieParse(cookiespec, "www.apache.org", 80, "/", true, header);
330         assertNotNull("Expected some cookies",cookies);
331         assertEquals("Expected 1 cookie",1,cookies.length);
332         assertNotNull("Expected cookie to have getExpiryDate",cookies[0].getExpiryDate());
333     }
334 
335     public void testSecurityError() throws Exception {
336         String headerValue = "custno=12345;comment=test; version=1," +
337             "name=John;version=1;max-age=600;secure;domain=jakarta.apache.org";
338         Header header = new Header("set-cookie", headerValue);
339 
340         CookieSpec cookiespec = new CookieSpecBase();
341         try {
342             Cookie[] cookies = cookieParse(cookiespec, "www.apache.org", 80, "/", false, header);
343             fail("HttpException exception should have been thrown");
344         } catch (HttpException e) {
345             // expected
346         }
347     }
348 
349     public void testParseSimple() throws Exception {
350         Header header = new Header("Set-Cookie","cookie-name=cookie-value");
351         
352         CookieSpec cookiespec = new CookieSpecBase();
353         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/path/path", false, header);
354         assertEquals("Found 1 cookie.",1,parsed.length);
355         assertEquals("Name","cookie-name",parsed[0].getName());
356         assertEquals("Value","cookie-value",parsed[0].getValue());
357         assertTrue("Comment",null == parsed[0].getComment());
358         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
359         //assertTrue("isToBeDiscarded",parsed[0].isToBeDiscarded());
360         assertTrue("isPersistent",!parsed[0].isPersistent());
361         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
362         assertEquals("Path","/path",parsed[0].getPath());
363         assertTrue("Secure",!parsed[0].getSecure());
364         assertEquals("Version",0,parsed[0].getVersion());
365     }
366  
367     public void testParseSimple2() throws Exception {
368         Header header = new Header("Set-Cookie", "cookie-name=cookie-value");
369     
370         CookieSpec cookiespec = new CookieSpecBase();
371         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/path", false, header);
372         assertEquals("Found 1 cookie.", 1, parsed.length);
373         assertEquals("Name", "cookie-name", parsed[0].getName());
374         assertEquals("Value", "cookie-value", parsed[0].getValue());
375         assertTrue("Comment", null == parsed[0].getComment());
376         assertTrue("ExpiryDate", null == parsed[0].getExpiryDate());
377         //assertTrue("isToBeDiscarded",parsed[0].isToBeDiscarded());
378         assertTrue("isPersistent", !parsed[0].isPersistent());
379         assertEquals("Domain", "127.0.0.1", parsed[0].getDomain());
380         assertEquals("Path", "/", parsed[0].getPath());
381         assertTrue("Secure", !parsed[0].getSecure());
382         assertEquals("Version", 0, parsed[0].getVersion());
383     }
384  
385     public void testParseNoName() throws Exception {
386         Header header = new Header("Set-Cookie","=stuff; path=/");
387 
388         CookieSpec cookiespec = new CookieSpecBase();
389         try {
390             Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header);
391             fail("MalformedCookieException should have been thrown");
392         } catch (MalformedCookieException ex) {
393             // expected
394         }
395     }
396  
397     public void testParseNoValue() throws Exception {
398         Header header = new Header("Set-Cookie","cookie-name=");
399 
400         CookieSpec cookiespec = new CookieSpecBase();
401         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header);
402         assertEquals("Found 1 cookie.",1,parsed.length);
403         assertEquals("Name","cookie-name",parsed[0].getName());
404         assertEquals("Value", "", parsed[0].getValue());
405         assertTrue("Comment",null == parsed[0].getComment());
406         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
407         //assertTrue("isToBeDiscarded",parsed[0].isToBeDiscarded());
408         assertTrue("isPersistent",!parsed[0].isPersistent());
409         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
410         assertEquals("Path","/",parsed[0].getPath());
411         assertTrue("Secure",!parsed[0].getSecure());
412         assertEquals("Version",0,parsed[0].getVersion());
413     }
414 
415     public void testParseWithWhiteSpace() throws Exception {
416         Header header = new Header("Set-Cookie"," cookie-name  =    cookie-value  ");
417 
418         CookieSpec cookiespec = new CookieSpecBase();
419         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header);
420         assertEquals("Found 1 cookie.",1,parsed.length);
421         assertEquals("Name","cookie-name",parsed[0].getName());
422         assertEquals("Value","cookie-value",parsed[0].getValue());
423         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
424         assertEquals("Path","/",parsed[0].getPath());
425         assertTrue("Secure",!parsed[0].getSecure());
426         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
427         assertTrue("Comment",null == parsed[0].getComment());
428     }
429 
430     public void testParseWithQuotes() throws Exception {
431         Header header = new Header("Set-Cookie"," cookie-name  =  \" cookie-value \" ;path=/");
432 
433         CookieSpec cookiespec = new CookieSpecBase();
434         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1",80, "/", false, header);
435         assertEquals("Found 1 cookie.",1,parsed.length);
436         assertEquals("Name","cookie-name",parsed[0].getName());
437         assertEquals("Value"," cookie-value ",parsed[0].getValue());
438         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
439         assertEquals("Path","/",parsed[0].getPath());
440         assertTrue("Secure",!parsed[0].getSecure());
441         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
442         assertTrue("Comment",null == parsed[0].getComment());
443     }
444 
445     public void testParseWithPath() throws Exception {
446         Header header = new Header("Set-Cookie","cookie-name=cookie-value; Path=/path/");
447 
448         CookieSpec cookiespec = new CookieSpecBase();
449         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1",80, "/path/path", false, header);
450         assertEquals("Found 1 cookie.",1,parsed.length);
451         assertEquals("Name","cookie-name",parsed[0].getName());
452         assertEquals("Value","cookie-value",parsed[0].getValue());
453         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
454         assertEquals("Path","/path/",parsed[0].getPath());
455         assertTrue("Secure",!parsed[0].getSecure());
456         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
457         assertTrue("Comment",null == parsed[0].getComment());
458     }
459 
460     public void testParseWithDomain() throws Exception {
461         Header header = new Header("Set-Cookie","cookie-name=cookie-value; Domain=127.0.0.1");
462 
463         CookieSpec cookiespec = new CookieSpecBase();
464         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header);
465         assertEquals("Found 1 cookie.",1,parsed.length);
466         assertEquals("Name","cookie-name",parsed[0].getName());
467         assertEquals("Value","cookie-value",parsed[0].getValue());
468         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
469         assertEquals("Path","/",parsed[0].getPath());
470         assertTrue("Secure",!parsed[0].getSecure());
471         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
472         assertTrue("Comment",null == parsed[0].getComment());
473     }
474 
475     public void testParseWithSecure() throws Exception {
476         Header header = new Header("Set-Cookie","cookie-name=cookie-value; secure");
477 
478         CookieSpec cookiespec = new CookieSpecBase();
479         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", true, header);
480         assertEquals("Found 1 cookie.",1,parsed.length);
481         assertEquals("Name","cookie-name",parsed[0].getName());
482         assertEquals("Value","cookie-value",parsed[0].getValue());
483         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
484         assertEquals("Path","/",parsed[0].getPath());
485         assertTrue("Secure",parsed[0].getSecure());
486         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
487         assertTrue("Comment",null == parsed[0].getComment());
488     }
489 
490     public void testParseWithComment() throws Exception {
491         Header header = new Header("Set-Cookie",
492             "cookie-name=cookie-value; comment=\"This is a comment.\"");
493 
494         CookieSpec cookiespec = new CookieSpecBase();
495         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", true, header);
496         assertEquals("Found 1 cookie.",1,parsed.length);
497         assertEquals("Name","cookie-name",parsed[0].getName());
498         assertEquals("Value","cookie-value",parsed[0].getValue());
499         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
500         assertEquals("Path","/",parsed[0].getPath());
501         assertTrue("Secure",!parsed[0].getSecure());
502         assertTrue("ExpiryDate",null == parsed[0].getExpiryDate());
503         assertEquals("Comment","This is a comment.",parsed[0].getComment());
504     }
505 
506     public void testParseWithExpires() throws Exception {
507         Header header = new Header("Set-Cookie",
508             "cookie-name=cookie-value;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
509 
510         CookieSpec cookiespec = new CookieSpecBase();
511         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", true, header);
512         assertEquals("Found 1 cookie.",1,parsed.length);
513         assertEquals("Name","cookie-name",parsed[0].getName());
514         assertEquals("Value","cookie-value",parsed[0].getValue());
515         assertEquals("Domain","127.0.0.1",parsed[0].getDomain());
516         assertEquals("Path","/",parsed[0].getPath());
517         assertTrue("Secure",!parsed[0].getSecure());
518         assertEquals(new Date(10000L),parsed[0].getExpiryDate());
519         assertTrue("Comment",null == parsed[0].getComment());
520     }
521 
522     public void testParseWithAll() throws Exception {
523         Header header = new Header("Set-Cookie",
524             "cookie-name=cookie-value;Version=1;Path=/commons;Domain=.apache.org;" + 
525             "Comment=This is a comment.;secure;Expires=Thu, 01-Jan-1970 00:00:10 GMT");
526 
527         CookieSpec cookiespec = new CookieSpecBase();
528         Cookie[] parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/httpclient", true, header);
529         assertEquals("Found 1 cookie.",1,parsed.length);
530         assertEquals("Name","cookie-name",parsed[0].getName());
531         assertEquals("Value","cookie-value",parsed[0].getValue());
532         assertEquals("Domain",".apache.org",parsed[0].getDomain());
533         assertEquals("Path","/commons",parsed[0].getPath());
534         assertTrue("Secure",parsed[0].getSecure());
535         assertEquals(new Date(10000L),parsed[0].getExpiryDate());
536         assertEquals("Comment","This is a comment.",parsed[0].getComment());
537         assertEquals("Version",0,parsed[0].getVersion());
538     }
539 
540     public void testParseMultipleDifferentPaths() throws Exception {
541         Header header = new Header("Set-Cookie",
542             "name1=value1;Version=1;Path=/commons,name1=value2;Version=1;" +
543             "Path=/commons/httpclient;Version=1");
544 
545         CookieSpec cookiespec = new CookieSpecBase();
546         Cookie[] parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/httpclient", true, header);
547         HttpState state = new HttpState();
548         state.addCookies(parsed);
549         Cookie[] cookies = state.getCookies();
550         assertEquals("Wrong number of cookies.",2,cookies.length);
551         assertEquals("Name","name1",cookies[0].getName());
552         assertEquals("Value","value1",cookies[0].getValue());
553         assertEquals("Name","name1",cookies[1].getName());
554         assertEquals("Value","value2",cookies[1].getValue());
555     }
556 
557     public void testParseMultipleSamePaths() throws Exception {
558         Header header = new Header("Set-Cookie",
559             "name1=value1;Version=1;Path=/commons,name1=value2;Version=1;Path=/commons");
560 
561         CookieSpec cookiespec = new CookieSpecBase();
562         Cookie[] parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/httpclient", true, header);
563         HttpState state = new HttpState();
564         state.addCookies(parsed);
565         Cookie[] cookies = state.getCookies();
566         assertEquals("Found 1 cookies.",1,cookies.length);
567         assertEquals("Name","name1",cookies[0].getName());
568         assertEquals("Value","value2",cookies[0].getValue());
569     }
570 
571     public void testParseRelativePath() throws Exception {
572         Header header = new Header("Set-Cookie", "name1=value1;Path=whatever");
573 
574         CookieSpec cookiespec = new CookieSpecBase();
575         Cookie[] parsed = cookieParse(cookiespec, ".apache.org", 80, "whatever", true, header);
576         assertEquals("Found 1 cookies.",1,parsed.length);
577         assertEquals("Name","name1",parsed[0].getName());
578         assertEquals("Value","value1",parsed[0].getValue());
579         assertEquals("Path","whatever",parsed[0].getPath());
580     }
581 
582     public void testParseWithWrongDomain() throws Exception {
583         Header header = new Header("Set-Cookie",
584             "cookie-name=cookie-value; domain=127.0.0.1; version=1");
585 
586         CookieSpec cookiespec = new CookieSpecBase();
587         try {
588             Cookie[] parsed = cookieParse(cookiespec, "127.0.0.2", 80, "/", false, header);
589             fail("HttpException exception should have been thrown");
590         } catch (HttpException e) {
591             // expected
592         }
593     }
594 
595     public void testParseWithNullHost() throws Exception {
596         Header header = new Header("Set-Cookie",
597             "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
598 
599         CookieSpec cookiespec = new CookieSpecBase();
600         try {
601             Cookie[] parsed = cookieParse(cookiespec, null, 80, "/", false, header);
602             fail("IllegalArgumentException should have been thrown");
603         } catch (IllegalArgumentException e) {
604             // expected
605         }
606     }
607 
608     public void testParseWithBlankHost() throws Exception {
609         Header header = new Header("Set-Cookie",
610             "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
611 
612         CookieSpec cookiespec = new CookieSpecBase();
613         try {
614             Cookie[] parsed = cookieParse(cookiespec, "  ", 80, "/", false, header);
615             fail("IllegalArgumentException should have been thrown");
616         } catch (IllegalArgumentException e) {
617             // expected
618         }
619     }
620 
621     public void testParseWithNullPath() throws Exception {
622         Header header = new Header("Set-Cookie",
623             "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
624 
625         CookieSpec cookiespec = new CookieSpecBase();
626         try {
627             Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, null, false, header);
628             fail("IllegalArgumentException should have been thrown");
629         } catch (IllegalArgumentException e) {
630             // expected
631         }
632     }
633 
634     public void testParseWithBlankPath() throws Exception {
635         Header header = new Header("Set-Cookie",
636             "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
637 
638         CookieSpec cookiespec = new CookieSpecBase();
639         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "  ", false, header);
640         assertNotNull(parsed);
641         assertEquals(1, parsed.length);
642         assertEquals("/", parsed[0].getPath());
643     }
644 
645     public void testParseWithNegativePort() throws Exception {
646         Header header = new Header("Set-Cookie",
647             "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
648 
649         CookieSpec cookiespec = new CookieSpecBase();
650         try {
651             Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", -80, null, false, header);
652             fail("IllegalArgumentException should have been thrown");
653         } catch (IllegalArgumentException e) {
654             // expected
655         }
656     }
657 
658     public void testParseWithNullHostAndPath() throws Exception {
659         Header header = new Header("Set-Cookie",
660             "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
661 
662         CookieSpec cookiespec = new CookieSpecBase();
663         try {
664             Cookie[] parsed = cookieParse(cookiespec, null, 80, null, false, header);
665             fail("IllegalArgumentException should have been thrown");
666         } catch (IllegalArgumentException e) {
667             // expected
668         }
669     }
670 
671     public void testParseWithPathMismatch() throws Exception {
672         Header header = new Header("Set-Cookie",
673             "cookie-name=cookie-value; path=/path/path/path");
674 
675         CookieSpec cookiespec = new CookieSpecBase();
676         try {
677             Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/path", false, header);
678             fail("MalformedCookieException should have been thrown.");
679         } catch (MalformedCookieException e) {
680             // expected
681         }
682     }
683     
684     public void testParseWithPathMismatch2() throws Exception {
685         Header header = new Header("Set-Cookie",
686             "cookie-name=cookie-value; path=/foobar");
687 
688         CookieSpec cookiespec = new CookieSpecBase();
689         try {
690             Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/foo", false, header);
691             fail("MalformedCookieException should have been thrown.");
692         } catch (MalformedCookieException e) {
693             // expected
694         }
695     }
696 
697 
698     public void testParseWithInvalidHeader1() throws Exception {
699         CookieSpec cookiespec = new CookieSpecBase();
700         try {
701             Cookie[] parsed = cookiespec.parse("127.0.0.1", 80, "/foo", false, (Header)null);
702             fail("IllegalArgumentException should have been thrown.");
703         } catch (IllegalArgumentException e) {
704             // expected
705         }
706     }
707 
708     public void testParseWithInvalidHeader2() throws Exception {
709         CookieSpec cookiespec = new CookieSpecBase();
710         try {
711             Cookie[] parsed = cookiespec.parse("127.0.0.1", 80, "/foo", false, (String)null);
712             fail("IllegalArgumentException should have been thrown.");
713         } catch (IllegalArgumentException e) {
714             // expected
715         }
716     }
717 
718     /**
719      * Tests if cookie constructor rejects cookie name containing blanks.
720      */
721     public void testCookieNameWithBlanks() throws Exception {
722         Header setcookie = new Header("Set-Cookie", "invalid name=");
723         CookieSpec cookiespec = new CookieSpecBase();
724         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, setcookie);
725         assertNotNull(parsed);
726         assertEquals(1, parsed.length);
727     }
728 
729 
730     /**
731      * Tests if cookie constructor rejects cookie name starting with $.
732      */
733     public void testCookieNameStartingWithDollarSign() throws Exception {
734         Header setcookie = new Header("Set-Cookie", "$invalid_name=");
735         CookieSpec cookiespec = new CookieSpecBase();
736         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, setcookie);
737         assertNotNull(parsed);
738         assertEquals(1, parsed.length);
739     }
740 
741 
742     /**
743      * Tests if malformatted expires attribute is parsed correctly.
744      */
745     public void testCookieWithComma() throws Exception {
746         Header header = new Header("Set-Cookie", "name=value; expires=\"Thu, 01-Jan-1970 00:00:00 GMT");
747 
748         CookieSpec cookiespec = new CookieSpecBase();
749         try {
750             Cookie[] cookies = cookiespec.parse("localhost", 80, "/", false, header);
751             fail("MalformedCookieException should have been thrown");
752         } catch (MalformedCookieException expected) {
753         }
754     }
755     
756 
757     /**
758      * Tests several date formats.
759      */
760     public void testDateFormats() throws Exception {
761         //comma, dashes
762         checkDate("Thu, 01-Jan-70 00:00:10 GMT");
763         checkDate("Thu, 01-Jan-2070 00:00:10 GMT");
764         //no comma, dashes
765         checkDate("Thu 01-Jan-70 00:00:10 GMT");
766         checkDate("Thu 01-Jan-2070 00:00:10 GMT");
767         //comma, spaces
768         checkDate("Thu, 01 Jan 70 00:00:10 GMT");
769         checkDate("Thu, 01 Jan 2070 00:00:10 GMT");
770         //no comma, spaces
771         checkDate("Thu 01 Jan 70 00:00:10 GMT");
772         checkDate("Thu 01 Jan 2070 00:00:10 GMT");
773         //weird stuff
774         checkDate("Wed, 20-Nov-2002 09-38-33 GMT");
775 
776 
777         try {
778             checkDate("this aint a date");
779             fail("Date check is bogous");
780         } catch(Exception e) {
781             /* must fail */
782         }
783     }
784 
785     private void checkDate(String date) throws Exception {
786         Header header = new Header("Set-Cookie", "custno=12345;Expires='"+date+"';");
787         HttpParams params = new DefaultHttpParamsFactory().getDefaultParams();
788         CookieSpec cookiespec = new CookieSpecBase();
789         cookiespec.setValidDateFormats(
790         		(Collection)params.getParameter(HttpMethodParams.DATE_PATTERNS));
791         cookieParse(cookiespec, "localhost", 80, "/", false, header);
792     }
793 
794     /**
795      * Tests if invalid second domain level cookie gets accepted in the
796      * browser compatibility mode.
797      */
798     public void testSecondDomainLevelCookie() throws Exception {
799         Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); 
800         cookie.setDomainAttributeSpecified(true);
801         cookie.setPathAttributeSpecified(true);
802 
803         CookieSpec cookiespec = new CookieSpecBase();
804         cookiespec.validate("sourceforge.net", 80, "/", false, cookie);
805     }
806 
807     public void testSecondDomainLevelCookieMatch1() throws Exception {
808         Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); 
809         cookie.setDomainAttributeSpecified(true);
810         cookie.setPathAttributeSpecified(true);
811 
812         CookieSpec cookiespec = new CookieSpecBase();
813         assertTrue(cookiespec.match("sourceforge.net", 80, "/", false, cookie));
814     }
815 
816     public void testSecondDomainLevelCookieMatch2() throws Exception {
817         Cookie cookie = new Cookie("sourceforge.net", "name", null, "/", null, false); 
818         cookie.setDomainAttributeSpecified(true);
819         cookie.setPathAttributeSpecified(true);
820 
821         CookieSpec cookiespec = new CookieSpecBase();
822         assertTrue(cookiespec.match("www.sourceforge.net", 80, "/", false, cookie));
823     }
824 
825     public void testSecondDomainLevelCookieMatch3() throws Exception {
826         Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); 
827          cookie.setDomainAttributeSpecified(true);
828          cookie.setPathAttributeSpecified(true);
829 
830          CookieSpec cookiespec = new CookieSpecBase();
831          assertTrue(cookiespec.match("www.sourceforge.net", 80, "/", false, cookie));
832     }
833          
834     public void testInvalidSecondDomainLevelCookieMatch1() throws Exception {
835         Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); 
836         cookie.setDomainAttributeSpecified(true);
837         cookie.setPathAttributeSpecified(true);
838 
839         CookieSpec cookiespec = new CookieSpecBase();
840         assertFalse(cookiespec.match("antisourceforge.net", 80, "/", false, cookie));
841     }
842 
843     public void testInvalidSecondDomainLevelCookieMatch2() throws Exception {
844         Cookie cookie = new Cookie("sourceforge.net", "name", null, "/", null, false); 
845         cookie.setDomainAttributeSpecified(true);
846         cookie.setPathAttributeSpecified(true);
847 
848         CookieSpec cookiespec = new CookieSpecBase();
849         assertFalse(cookiespec.match("antisourceforge.net", 80, "/", false, cookie));
850     }
851 
852     public void testMatchNullHost() throws Exception {
853         CookieSpec cookiespec = new CookieSpecBase();
854         Cookie cookie = new Cookie();
855         try {
856             cookiespec.match(null, 80, "/", false, cookie);
857             fail("IllegalArgumentException must have been thrown");
858         } catch (IllegalArgumentException expected) {
859         }
860     }
861 
862     public void testMatchBlankHost() throws Exception {
863         CookieSpec cookiespec = new CookieSpecBase();
864         Cookie cookie = new Cookie();
865         try {
866             cookiespec.match("   ", 80, "/", false, cookie);
867             fail("IllegalArgumentException must have been thrown");
868         } catch (IllegalArgumentException expected) {
869         }
870     }
871 
872     public void testMatchInvalidPort() throws Exception {
873         CookieSpec cookiespec = new CookieSpecBase();
874         Cookie cookie = new Cookie();
875         try {
876             cookiespec.match("host", -80, "/", false, cookie);
877             fail("IllegalArgumentException must have been thrown");
878         } catch (IllegalArgumentException expected) {
879         }
880     }
881 
882     public void testMatchNullPath() throws Exception {
883         CookieSpec cookiespec = new CookieSpecBase();
884         Cookie cookie = new Cookie();
885         try {
886             cookiespec.match("host", 80, null, false, cookie);
887             fail("IllegalArgumentException must have been thrown");
888         } catch (IllegalArgumentException expected) {
889         }
890     }
891 
892     public void testMatchBlankPath() throws Exception {
893         CookieSpec cookiespec = new CookieSpecBase();
894         Cookie cookie = new Cookie("host", "name", "value", "/", null, false);
895         assertTrue(cookiespec.match("host", 80, "  ", false, cookie));
896     }
897 
898     public void testMatchNullCookie() throws Exception {
899         CookieSpec cookiespec = new CookieSpecBase();
900         try {
901             cookiespec.match("host", 80, "/", false, (Cookie)null);
902             fail("IllegalArgumentException must have been thrown");
903         } catch (IllegalArgumentException expected) {
904         }
905     }
906 
907     public void testMatchNullCookieDomain() throws Exception {
908         CookieSpec cookiespec = new CookieSpecBase();
909         Cookie cookie = new Cookie(null, "name", "value", "/", null, false);
910         assertFalse(cookiespec.match("host", 80, "/", false, cookie));
911     }
912 
913     public void testMatchNullCookiePath() throws Exception {
914         CookieSpec cookiespec = new CookieSpecBase();
915         Cookie cookie = new Cookie("host", "name", "value", null, null, false);
916         assertFalse(cookiespec.match("host", 80, "/", false, cookie));
917     }
918     
919     public void testCookieMatch1() throws Exception {
920         CookieSpec cookiespec = new CookieSpecBase();
921         Cookie cookie = new Cookie("host", "name", "value", "/", null, false);
922         assertTrue(cookiespec.match("host", 80, "/", false, cookie));
923     }
924     
925     public void testCookieMatch2() throws Exception {
926         CookieSpec cookiespec = new CookieSpecBase();
927         Cookie cookie = new Cookie(".whatever.com", "name", "value", "/", null, false);
928         assertTrue(cookiespec.match(".whatever.com", 80, "/", false, cookie));
929     }
930     
931     public void testCookieMatch3() throws Exception {
932         CookieSpec cookiespec = new CookieSpecBase();
933         Cookie cookie = new Cookie(".whatever.com", "name", "value", "/", null, false);
934         assertTrue(cookiespec.match(".really.whatever.com", 80, "/", false, cookie));
935     }
936     
937     public void testCookieMatch4() throws Exception {
938         CookieSpec cookiespec = new CookieSpecBase();
939         Cookie cookie = new Cookie("host", "name", "value", "/", null, false);
940         assertTrue(cookiespec.match("host", 80, "/foobar", false, cookie));
941     }
942     
943     public void testCookieMismatch1() throws Exception {
944         CookieSpec cookiespec = new CookieSpecBase();
945         Cookie cookie = new Cookie("host1", "name", "value", "/", null, false);
946         assertFalse(cookiespec.match("host2", 80, "/", false, cookie));
947     }
948     
949     public void testCookieMismatch2() throws Exception {
950         CookieSpec cookiespec = new CookieSpecBase();
951         Cookie cookie = new Cookie(".aaaaaaaaa.com", "name", "value", "/", null, false);
952         assertFalse(cookiespec.match(".bbbbbbbb.com", 80, "/", false, cookie));
953     }
954     
955     public void testCookieMismatch3() throws Exception {
956         CookieSpec cookiespec = new CookieSpecBase();
957         Cookie cookie = new Cookie("host", "name", "value", "/foobar", null, false);
958         assertFalse(cookiespec.match("host", 80, "/foo", false, cookie));
959     }
960     
961     public void testCookieMismatch4() throws Exception {
962         CookieSpec cookiespec = new CookieSpecBase();
963         Cookie cookie = new Cookie("host", "name", "value", "/foobar", null, true);
964         assertFalse(cookiespec.match("host", 80, "/foobar/", false, cookie));
965     }
966     
967     public void testCookieMatch5() throws Exception {
968         CookieSpec cookiespec = new CookieSpecBase();
969         Cookie cookie = new Cookie("host", "name", "value", "/foobar/r", null, false);
970         assertFalse(cookiespec.match("host", 80, "/foobar/", false, cookie));
971     }
972     
973     public void testCookieMismatch6() throws Exception {
974         CookieSpec cookiespec = new CookieSpecBase();
975         Cookie cookie = new Cookie("host", "name", "value", "/foobar", null, true);
976         assertFalse(cookiespec.match("host", 80, "/foobar", false, cookie));
977     }
978     
979     public void testMatchNullCookies() throws Exception {
980         CookieSpec cookiespec = new CookieSpecBase();
981         Cookie[] matched = cookiespec.match("host", 80, "/foobar", false, (Cookie[])null);
982         assertNull(matched);
983     }
984     
985     public void testMatchedCookiesOrder() throws Exception {
986         CookieSpec cookiespec = new CookieSpecBase();
987         Cookie[] cookies = {
988             new Cookie("host", "nomatch", "value", "/noway", null, false),
989             new Cookie("host", "name2", "value", "/foobar/yada", null, false),
990             new Cookie("host", "name3", "value", "/foobar", null, false),
991             new Cookie("host", "name1", "value", "/foobar/yada/yada", null, false)};
992         Cookie[] matched = cookiespec.match("host", 80, "/foobar/yada/yada", false, cookies);
993         assertNotNull(matched);
994         assertEquals(3, matched.length);
995         assertEquals("name1", matched[0].getName());
996         assertEquals("name2", matched[1].getName());
997         assertEquals("name3", matched[2].getName());
998     }
999 
1000     public void testInvalidMatchDomain() throws Exception {
1001         Cookie cookie = new Cookie("beta.gamma.com", "name", null, "/", null, false); 
1002         cookie.setDomainAttributeSpecified(true);
1003         cookie.setPathAttributeSpecified(true);
1004 
1005         CookieSpec cookiespec = new CookieSpecBase();
1006         cookiespec.validate("alpha.beta.gamma.com", 80, "/", false, cookie);
1007         assertTrue(cookiespec.match("alpha.beta.gamma.com", 80, "/", false, cookie));
1008     }
1009 
1010     public void testFormatInvalidCookie() throws Exception {
1011         CookieSpec cookiespec = new CookieSpecBase();
1012         try {
1013             String s = cookiespec.formatCookie(null);
1014             fail("IllegalArgumentException nust have been thrown");
1015         } catch (IllegalArgumentException expected) {
1016         }
1017     }    
1018 
1019     /**
1020      * Tests generic cookie formatting.
1021      */
1022     public void testGenericCookieFormatting() throws Exception {
1023         Header header = new Header("Set-Cookie", 
1024             "name=value; path=/; domain=.mydomain.com");
1025         CookieSpec cookiespec = new CookieSpecBase();
1026         Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header);
1027         cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
1028         String s = cookiespec.formatCookie(cookies[0]);
1029         assertEquals("name=value", s);
1030     }    
1031 
1032     public void testGenericCookieFormattingAsHeader() throws Exception {
1033         Header header = new Header("Set-Cookie", 
1034             "name=value; path=/; domain=.mydomain.com");
1035         CookieSpec cookiespec = new CookieSpecBase();
1036         Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header);
1037         cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
1038         Header cookieheader = cookiespec.formatCookieHeader(cookies[0]);
1039         assertEquals("name=value", cookieheader.getValue());
1040     }    
1041 
1042     /**
1043      * Tests if null cookie values are handled correctly.
1044      */
1045     public void testNullCookieValueFormatting() {
1046         Cookie cookie = new Cookie(".whatever.com", "name", null, "/", null, false); 
1047         cookie.setDomainAttributeSpecified(true);
1048         cookie.setPathAttributeSpecified(true);
1049 
1050         CookieSpec cookiespec = new CookieSpecBase();
1051         String s = cookiespec.formatCookie(cookie);
1052         assertEquals("name=", s);
1053     }
1054 
1055     public void testFormatInvalidCookies() throws Exception {
1056         CookieSpec cookiespec = new CookieSpecBase();
1057         try {
1058             String s = cookiespec.formatCookies(null);
1059             fail("IllegalArgumentException nust have been thrown");
1060         } catch (IllegalArgumentException expected) {
1061         }
1062     }    
1063 
1064     public void testFormatZeroCookies() throws Exception {
1065         CookieSpec cookiespec = new CookieSpecBase();
1066         try {
1067             String s = cookiespec.formatCookies(new Cookie[] {});
1068             fail("IllegalArgumentException nust have been thrown");
1069         } catch (IllegalArgumentException expected) {
1070         }
1071     }    
1072 
1073     /**
1074      * Tests generic cookie formatting.
1075      */
1076     public void testFormatSeveralCookies() throws Exception {
1077         Header header = new Header("Set-Cookie", 
1078             "name1=value1; path=/; domain=.mydomain.com, name2 = value2 ; path=/; domain=.mydomain.com");
1079         CookieSpec cookiespec = new CookieSpecBase();
1080         Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header);
1081         String s = cookiespec.formatCookies(cookies);
1082         assertEquals("name1=value1; name2=value2", s);
1083     }    
1084 
1085     public void testFormatOneCookie() throws Exception {
1086         Header header = new Header("Set-Cookie", 
1087             "name1=value1; path=/; domain=.mydomain.com;");
1088         CookieSpec cookiespec = new CookieSpecBase();
1089         Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header);
1090         String s = cookiespec.formatCookies(cookies);
1091         assertEquals("name1=value1", s);
1092     }    
1093 
1094     public void testFormatSeveralCookiesAsHeader() throws Exception {
1095         Header header = new Header("Set-Cookie", 
1096             "name1=value1; path=/; domain=.mydomain.com, name2 = value2 ; path=/; domain=.mydomain.com");
1097         CookieSpec cookiespec = new CookieSpecBase();
1098         Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header);
1099         Header cookieheader = cookiespec.formatCookieHeader(cookies);
1100         assertEquals("name1=value1; name2=value2", cookieheader.getValue());
1101     }    
1102 
1103     public void testKeepCloverHappy() throws Exception {
1104         MalformedCookieException ex1 = new MalformedCookieException(); 
1105         MalformedCookieException ex2 = new MalformedCookieException("whatever"); 
1106         MalformedCookieException ex3 = new MalformedCookieException("whatever", null); 
1107     }
1108 
1109 }
1110 

././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieIgnoreSpec.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieIgnoreSpec.html100644 0 0 27670 10661532627 31300 0ustar 0 0 TestCookieIgnoreSpec xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieIgnoreSpec.java,v 1.5 2004/10/31 14:42:59 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import java.io.IOException;
33  
34  import junit.framework.Test;
35  import junit.framework.TestSuite;
36  
37  import org.apache.commons.httpclient.Cookie;
38  import org.apache.commons.httpclient.Header;
39  import org.apache.commons.httpclient.HttpClientTestBase;
40  import org.apache.commons.httpclient.HttpStatus;
41  import org.apache.commons.httpclient.HttpVersion;
42  import org.apache.commons.httpclient.methods.GetMethod;
43  import org.apache.commons.httpclient.server.HttpService;
44  import org.apache.commons.httpclient.server.SimpleRequest;
45  import org.apache.commons.httpclient.server.SimpleResponse;
46  
47  
48  /**
49   * Test cases for ignore cookie apec
50   *
51   * @author Michael Becke
52   * 
53   * @version $Revision: 480424 $
54   */
55  public class TestCookieIgnoreSpec extends HttpClientTestBase {
56  
57      // ------------------------------------------------------------ Constructor
58  
59      public TestCookieIgnoreSpec(final String testName) throws IOException {
60          super(testName);
61      }
62  
63      // ------------------------------------------------------- TestCase Methods
64  
65      public static Test suite() {
66          return new TestSuite(TestCookieIgnoreSpec.class);
67      }
68  
69      private class BasicAuthService implements HttpService {
70  
71          public BasicAuthService() {
72              super();
73          }
74  
75          public boolean process(final SimpleRequest request, final SimpleResponse response)
76              throws IOException
77          {
78          	HttpVersion ver = request.getRequestLine().getHttpVersion();
79              response.setStatusLine(ver, HttpStatus.SC_OK);
80              response.addHeader(new Header("Connection", "close"));
81              response.addHeader(new Header("Set-Cookie", 
82                  "custno = 12345; comment=test; version=1," +
83                  " name=John; version=1; max-age=600; secure; domain=.apache.org"));
84              return true;
85          }
86      }
87  
88      public void testIgnoreCookies() throws Exception {
89          this.server.setHttpService(new BasicAuthService());
90  
91          GetMethod httpget = new GetMethod("/");
92          httpget.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
93          
94          try {
95              this.client.executeMethod(httpget);
96          } finally {
97              httpget.releaseConnection();
98          }
99          assertEquals("Cookie parsing should have been disabled", 
100                 0, this.client.getState().getCookies().length);
101     }
102 
103     public void testKeepCloverHappy() throws Exception {
104         CookieSpec cookiespec = new IgnoreCookiesSpec();
105         cookiespec.parseAttribute(null, null);
106         cookiespec.parse("host", 80, "/", false, (String)null);
107         cookiespec.parse("host", 80, "/", false, (Header)null);
108         cookiespec.validate("host", 80, "/", false, (Cookie)null);
109         cookiespec.match("host", 80, "/", false, (Cookie)null);
110         cookiespec.match("host", 80, "/", false, (Cookie [])null);
111         cookiespec.domainMatch(null, null);
112         cookiespec.pathMatch(null, null);
113         cookiespec.match("host", 80, "/", false, (Cookie [])null);
114         cookiespec.formatCookie(null);
115         cookiespec.formatCookies(null);
116         cookiespec.formatCookieHeader((Cookie)null);
117         cookiespec.formatCookieHeader((Cookie [])null);
118     }
119 }
120 

././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieNetscapeDraft.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieNetscapeDraft.h100644 0 0 70027 10661532627 31242 0ustar 0 0 TestCookieNetscapeDraft xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieNetscapeDraft.java,v 1.2 2004/04/24 23:28:04 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import junit.framework.Test;
33  import junit.framework.TestSuite;
34  
35  import org.apache.commons.httpclient.Cookie;
36  import org.apache.commons.httpclient.Header;
37  import org.apache.commons.httpclient.HttpException;
38  import org.apache.commons.httpclient.NameValuePair;
39  
40  
41  /**
42   * Test cases for Netscape cookie draft
43   *
44   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
45   * 
46   * @version $Revision: 480424 $
47   */
48  public class TestCookieNetscapeDraft extends TestCookieBase {
49  
50      // ------------------------------------------------------------ Constructor
51  
52      public TestCookieNetscapeDraft(String name) {
53          super(name);
54      }
55  
56  
57      // ------------------------------------------------------- TestCase Methods
58  
59  
60      public static Test suite() {
61          return new TestSuite(TestCookieNetscapeDraft.class);
62      }
63  
64      public void testParseAttributeInvalidAttrib() throws Exception {
65          CookieSpec cookiespec = new NetscapeDraftSpec();
66          try {
67              cookiespec.parseAttribute(null, null);
68              fail("IllegalArgumentException must have been thrown");
69          } catch (IllegalArgumentException expected) {
70          }
71      }
72  
73      public void testParseAttributeInvalidCookie() throws Exception {
74          CookieSpec cookiespec = new NetscapeDraftSpec();
75          try {
76              cookiespec.parseAttribute(new NameValuePair("name", "value"), null);
77              fail("IllegalArgumentException must have been thrown");
78          } catch (IllegalArgumentException expected) {
79          }
80      }
81  
82      public void testParseAttributeInvalidCookieExpires() throws Exception {
83          CookieSpec cookiespec = new NetscapeDraftSpec();
84          Cookie cookie = new Cookie();
85          try {
86              cookiespec.parseAttribute(new NameValuePair("expires", null), cookie);
87              fail("MalformedCookieException must have been thrown");
88          } catch (MalformedCookieException expected) {
89          }
90      }
91  
92      public void testParseWithNullHost() throws Exception {
93          Header header = new Header("Set-Cookie",
94              "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
95  
96          CookieSpec cookiespec = new NetscapeDraftSpec();
97          try {
98              Cookie[] parsed = cookieParse(cookiespec, null, 80, "/", false, header);
99              fail("IllegalArgumentException should have been thrown");
100         } catch (IllegalArgumentException e) {
101             // expected
102         }
103     }
104 
105     public void testParseWithBlankHost() throws Exception {
106         Header header = new Header("Set-Cookie",
107             "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
108 
109         CookieSpec cookiespec = new NetscapeDraftSpec();
110         try {
111             Cookie[] parsed = cookieParse(cookiespec, "  ", 80, "/", false, header);
112             fail("IllegalArgumentException should have been thrown");
113         } catch (IllegalArgumentException e) {
114             // expected
115         }
116     }
117 
118     public void testParseWithNullPath() throws Exception {
119         Header header = new Header("Set-Cookie",
120             "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
121 
122         CookieSpec cookiespec = new NetscapeDraftSpec();
123         try {
124             Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, null, false, header);
125             fail("IllegalArgumentException should have been thrown");
126         } catch (IllegalArgumentException e) {
127             // expected
128         }
129     }
130 
131     public void testParseWithBlankPath() throws Exception {
132         Header header = new Header("Set-Cookie",
133             "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
134 
135         CookieSpec cookiespec = new NetscapeDraftSpec();
136         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "  ", false, header);
137         assertNotNull(parsed);
138         assertEquals(1, parsed.length);
139         assertEquals("/", parsed[0].getPath());
140     }
141 
142     public void testParseWithNegativePort() throws Exception {
143         Header header = new Header("Set-Cookie",
144             "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure");
145 
146         CookieSpec cookiespec = new NetscapeDraftSpec();
147         try {
148             Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", -80, null, false, header);
149             fail("IllegalArgumentException should have been thrown");
150         } catch (IllegalArgumentException e) {
151             // expected
152         }
153     }
154 
155     public void testParseWithInvalidHeader1() throws Exception {
156         CookieSpec cookiespec = new NetscapeDraftSpec();
157         try {
158             Cookie[] parsed = cookiespec.parse("127.0.0.1", 80, "/foo", false, (String)null);
159             fail("IllegalArgumentException should have been thrown.");
160         } catch (IllegalArgumentException e) {
161             // expected
162         }
163     }
164 
165     public void testParseAbsPath() throws Exception {
166         Header header = new Header("Set-Cookie", "name1=value1;Path=/path/");
167 
168         CookieSpec cookiespec = new NetscapeDraftSpec();
169         Cookie[] parsed = cookieParse(cookiespec, "host", 80, "/path/", true, header);
170         assertEquals("Found 1 cookies.",1,parsed.length);
171         assertEquals("Name","name1",parsed[0].getName());
172         assertEquals("Value","value1",parsed[0].getValue());
173         assertEquals("Domain","host",parsed[0].getDomain());
174         assertEquals("Path","/path/",parsed[0].getPath());
175     }
176 
177     public void testParseAbsPath2() throws Exception {
178         Header header = new Header("Set-Cookie", "name1=value1;Path=/");
179 
180         CookieSpec cookiespec = new NetscapeDraftSpec();
181         Cookie[] parsed = cookieParse(cookiespec, "host", 80, "/", true, header);
182         assertEquals("Found 1 cookies.",1,parsed.length);
183         assertEquals("Name","name1",parsed[0].getName());
184         assertEquals("Value","value1",parsed[0].getValue());
185         assertEquals("Domain","host",parsed[0].getDomain());
186         assertEquals("Path","/",parsed[0].getPath());
187     }
188 
189     public void testParseRelativePath() throws Exception {
190         Header header = new Header("Set-Cookie", "name1=value1;Path=whatever");
191 
192         CookieSpec cookiespec = new NetscapeDraftSpec();
193         Cookie[] parsed = cookieParse(cookiespec, "host", 80, "whatever", true, header);
194         assertEquals("Found 1 cookies.",1,parsed.length);
195         assertEquals("Name","name1",parsed[0].getName());
196         assertEquals("Value","value1",parsed[0].getValue());
197         assertEquals("Domain","host",parsed[0].getDomain());
198         assertEquals("Path","whatever",parsed[0].getPath());
199     }
200 
201     public void testParseWithIllegalNetscapeDomain1() throws Exception {
202         Header header = new Header("Set-Cookie","cookie-name=cookie-value; domain=.com");
203 
204         CookieSpec cookiespec = new NetscapeDraftSpec();
205         try {
206             Cookie[] parsed = cookieParse(cookiespec, "a.com", 80, "/", false, header);
207             fail("HttpException exception should have been thrown");
208         } catch (HttpException e) {
209             // expected
210         }
211     }
212 
213     public void testParseWithWrongNetscapeDomain2() throws Exception {
214         Header header = new Header("Set-Cookie","cookie-name=cookie-value; domain=.y.z");
215         
216         CookieSpec cookiespec = new NetscapeDraftSpec();
217         try {
218             Cookie[] parsed = cookieParse(cookiespec, "x.y.z", 80, "/", false, header);
219             fail("HttpException exception should have been thrown");
220         } catch (HttpException e) {
221             // expected
222         }
223     }
224 
225     /**
226      * Tests Netscape specific cookie formatting.
227      */
228     
229     public void testNetscapeCookieFormatting() throws Exception {
230         Header header = new Header(
231           "Set-Cookie", "name=value; path=/; domain=.mydomain.com");
232         CookieSpec cookiespec = new NetscapeDraftSpec();
233         Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header );
234         cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
235         String s = cookiespec.formatCookie(cookies[0]);
236         assertEquals("name=value", s);
237     }
238     
239     /**
240      * Tests Netscape specific expire attribute parsing.
241      */
242     public void testNetscapeCookieExpireAttribute() throws Exception {
243         CookieSpec cookiespec = new NetscapeDraftSpec();
244         Header header = new Header("Set-Cookie", 
245             "name=value; path=/; domain=.mydomain.com; expires=Thu, 01-Jan-2070 00:00:10 GMT; comment=no_comment");
246         Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header );
247         cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
248         header = new Header("Set-Cookie", 
249             "name=value; path=/; domain=.mydomain.com; expires=Thu 01-Jan-2070 00:00:10 GMT; comment=no_comment");
250         try {
251             cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header );
252             cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
253             fail("MalformedCookieException must have been thrown");
254         }
255         catch (MalformedCookieException expected) {
256         }
257     }
258 
259     /**
260      * Tests Netscape specific expire attribute without a time zone.
261      */
262     public void testNetscapeCookieExpireAttributeNoTimeZone() throws Exception {
263         CookieSpec cookiespec = new NetscapeDraftSpec();
264         Header header = new Header("Set-Cookie", 
265             "name=value; expires=Thu, 01-Jan-2006 00:00:00 ");
266         try {
267             cookiespec.parse("myhost.mydomain.com", 80, "/", false, header );
268             fail("MalformedCookieException should have been thrown");
269         } catch (MalformedCookieException ex) {
270             // expected
271         }
272     }
273     
274     /**
275      * Tests if cookie values with embedded comma are handled correctly.
276      */
277     public void testCookieWithComma() throws Exception {
278         Header header = new Header("Set-Cookie", "a=b,c");
279 
280         CookieSpec cookiespec = new NetscapeDraftSpec();
281         Cookie[] cookies = cookiespec.parse("localhost", 80, "/", false, header);
282         assertEquals("number of cookies", 1, cookies.length);
283         assertEquals("a", cookies[0].getName());
284         assertEquals("b,c", cookies[0].getValue());
285     }
286     
287 }
288 

././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookiePathComparator.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookiePathComparator.100644 0 0 27141 10661532627 31272 0ustar 0 0 TestCookiePathComparator xref

1   /*
2    * $HeaderURL$
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import java.util.Comparator;
33  
34  import junit.framework.Test;
35  import junit.framework.TestSuite;
36  
37  import org.apache.commons.httpclient.Cookie;
38  
39  /**
40   * Test cases for {@link CookiePathComparator}.
41   */
42  public class TestCookiePathComparator extends TestCookieBase {
43  
44  
45      // ------------------------------------------------------------ Constructor
46  
47      public TestCookiePathComparator(String name) {
48          super(name);
49      }
50  
51      // ------------------------------------------------------- TestCase Methods
52  
53      public static Test suite() {
54          return new TestSuite(TestCookiePathComparator.class);
55      }
56  
57      public void testUnequality1() {
58          Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/a/b/", null, false); 
59          Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/a/", null, false);
60          Comparator comparator = new CookiePathComparator();
61          assertTrue(comparator.compare(cookie1, cookie2) < 0);
62          assertTrue(comparator.compare(cookie2, cookie1) > 0);
63      }
64  
65      public void testUnequality2() {
66          Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/a/b", null, false); 
67          Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/a", null, false);
68          Comparator comparator = new CookiePathComparator();
69          assertTrue(comparator.compare(cookie1, cookie2) < 0);
70          assertTrue(comparator.compare(cookie2, cookie1) > 0);
71      }
72  
73      public void testEquality1() {
74          Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/a", null, false); 
75          Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/a", null, false);
76          Comparator comparator = new CookiePathComparator();
77          assertTrue(comparator.compare(cookie1, cookie2) == 0);
78          assertTrue(comparator.compare(cookie2, cookie1) == 0);
79      }
80  
81      public void testEquality2() {
82          Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/a/", null, false); 
83          Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/a", null, false);
84          Comparator comparator = new CookiePathComparator();
85          assertTrue(comparator.compare(cookie1, cookie2) == 0);
86          assertTrue(comparator.compare(cookie2, cookie1) == 0);
87      }
88  
89      public void testEquality3() {
90          Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", null, null, false); 
91          Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/", null, false);
92          Comparator comparator = new CookiePathComparator();
93          assertTrue(comparator.compare(cookie1, cookie2) == 0);
94          assertTrue(comparator.compare(cookie2, cookie1) == 0);
95      }
96  
97      public void testEquality4() {
98          Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/this", null, false); 
99          Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/that", null, false);
100         Comparator comparator = new CookiePathComparator();
101         assertTrue(comparator.compare(cookie1, cookie2) == 0);
102         assertTrue(comparator.compare(cookie2, cookie1) == 0);
103     }
104     
105 }
106 

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookiePolicy.html100644 0 0 22701 10661532627 30467 0ustar 0 0 TestCookiePolicy xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookiePolicy.java,v 1.2 2004/09/14 20:11:32 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import junit.framework.Test;
33  import junit.framework.TestSuite;
34  
35  
36  /**
37   * Test cases for Cookie Policy
38   *
39   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
40   * 
41   * @version $Revision: 480424 $
42   */
43  public class TestCookiePolicy extends TestCookieBase {
44  
45      // ------------------------------------------------------------ Constructor
46  
47      public TestCookiePolicy(String name) {
48          super(name);
49      }
50  
51      // ------------------------------------------------------- TestCase Methods
52  
53      public static Test suite() {
54          return new TestSuite(TestCookiePolicy.class);
55      }
56  
57      public void testRegisterNullPolicyId() {
58          try {
59              CookiePolicy.registerCookieSpec(null, null);
60              fail("IllegalArgumentException must have been thrown");
61          } catch (IllegalArgumentException expected) {
62          }
63      }
64  
65      public void testRegisterNullPolicy() {
66          try {
67              CookiePolicy.registerCookieSpec("whatever", null);
68              fail("IllegalArgumentException must have been thrown");
69          } catch (IllegalArgumentException expected) {
70          }
71      }
72  
73      public void testUnregisterNullPolicy() {
74          try {
75              CookiePolicy.unregisterCookieSpec(null);
76              fail("IllegalArgumentException must have been thrown");
77          } catch (IllegalArgumentException expected) {
78          }
79      }
80  
81      public void testGetPolicyNullId() {
82          try {
83              CookiePolicy.getCookieSpec(null);
84              fail("IllegalArgumentException must have been thrown");
85          } catch (IllegalArgumentException expected) {
86          }
87      }
88  
89      public void testRegisterUnregister() {
90          CookiePolicy.registerCookieSpec("whatever", CookieSpecBase.class);
91          CookiePolicy.unregisterCookieSpec("whatever");
92          try {
93              CookiePolicy.getCookieSpec("whatever");
94              fail("IllegalStateException must have been thrown");
95          } catch (IllegalStateException expected) {
96          }
97      }
98  
99      public void testGetDefaultPolicy() {
100         assertNotNull(CookiePolicy.getDefaultSpec());
101     }
102 }
103 

././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieRFC2109Spec.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieRFC2109Spec.htm100644 0 0 114401 10661532627 30634 0ustar 0 0 TestCookieRFC2109Spec xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieRFC2109Spec.java,v 1.3 2004/06/05 16:49:20 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import junit.framework.Test;
33  import junit.framework.TestSuite;
34  
35  import org.apache.commons.httpclient.Cookie;
36  import org.apache.commons.httpclient.Header;
37  import org.apache.commons.httpclient.NameValuePair;
38  
39  /**
40   * Test cases for RFC2109 cookie spec
41   *
42   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
43   * 
44   * @version $Revision: 480424 $
45   */
46  public class TestCookieRFC2109Spec extends TestCookieBase {
47  
48  
49      // ------------------------------------------------------------ Constructor
50  
51      public TestCookieRFC2109Spec(String name) {
52          super(name);
53      }
54  
55      // ------------------------------------------------------- TestCase Methods
56  
57      public static Test suite() {
58          return new TestSuite(TestCookieRFC2109Spec.class);
59      }
60  
61      public void testParseAttributeInvalidAttrib() throws Exception {
62          CookieSpec cookiespec = new RFC2109Spec();
63          try {
64              cookiespec.parseAttribute(null, null);
65              fail("IllegalArgumentException must have been thrown");
66          } catch (IllegalArgumentException expected) {
67          }
68      }
69  
70      public void testParseAttributeInvalidCookie() throws Exception {
71          CookieSpec cookiespec = new RFC2109Spec();
72          try {
73              cookiespec.parseAttribute(new NameValuePair("name", "value"), null);
74              fail("IllegalArgumentException must have been thrown");
75          } catch (IllegalArgumentException expected) {
76          }
77      }
78  
79      public void testParseAttributeNullPath() throws Exception {
80          CookieSpec cookiespec = new RFC2109Spec();
81          try {
82              Cookie cookie = new Cookie();
83              cookiespec.parseAttribute(new NameValuePair("path", null), cookie);
84              fail("MalformedCookieException must have been thrown");
85          } catch (MalformedCookieException expected) {
86          }
87      }
88  
89      public void testParseAttributeBlankPath() throws Exception {
90          CookieSpec cookiespec = new RFC2109Spec();
91          try {
92              Cookie cookie = new Cookie();
93              cookiespec.parseAttribute(new NameValuePair("path", "   "), cookie);
94              fail("MalformedCookieException must have been thrown");
95          } catch (MalformedCookieException expected) {
96          }
97      }
98  
99      public void testParseAttributeNullVersion() throws Exception {
100         CookieSpec cookiespec = new RFC2109Spec();
101         try {
102             Cookie cookie = new Cookie();
103             cookiespec.parseAttribute(new NameValuePair("version", null), cookie);
104             fail("MalformedCookieException must have been thrown");
105         } catch (MalformedCookieException expected) {
106         }
107     }
108 
109     public void testParseAttributeInvalidVersion() throws Exception {
110         CookieSpec cookiespec = new RFC2109Spec();
111         try {
112             Cookie cookie = new Cookie();
113             cookiespec.parseAttribute(new NameValuePair("version", "nonsense"), cookie);
114             fail("MalformedCookieException must have been thrown");
115         } catch (MalformedCookieException expected) {
116         }
117     }
118 
119     public void testParseVersion() throws Exception {
120         Header header = new Header("Set-Cookie","cookie-name=cookie-value; version=1");
121 
122         CookieSpec cookiespec = new RFC2109Spec();
123         Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header);
124         assertEquals("Found 1 cookie.",1,parsed.length);
125         assertEquals("Name","cookie-name",parsed[0].getName());
126         assertEquals("Value","cookie-value",parsed[0].getValue());
127         assertEquals("Version",1,parsed[0].getVersion());
128     }
129 
130     /**
131      * Test domain equals host 
132      */
133     public void testParseDomainEqualsHost() throws Exception {
134         Header header = new Header("Set-Cookie",
135             "cookie-name=cookie-value; domain=www.b.com; version=1");
136 
137         CookieSpec cookiespec = new RFC2109Spec();
138         Cookie[] parsed = cookieParse(cookiespec, "www.b.com", 80, "/", false, header);
139         assertNotNull(parsed);
140         assertEquals(1, parsed.length);
141         assertEquals("www.b.com", parsed[0].getDomain());
142     }
143 
144     /**
145      * Domain does not start with a dot
146      */
147     public void testParseWithIllegalDomain1() throws Exception {
148         Header header = new Header("Set-Cookie",
149             "cookie-name=cookie-value; domain=a.b.com; version=1");
150 
151         CookieSpec cookiespec = new RFC2109Spec();
152         try {
153             Cookie[] parsed = cookieParse(cookiespec, "www.a.b.com", 80, "/", false, header);
154             fail("MalformedCookieException should have been thrown");
155         } catch (MalformedCookieException e) {
156             // expected
157         }
158     }
159 
160     /**
161      * Domain must have alt least one embedded dot
162      */
163     public void testParseWithIllegalDomain2() throws Exception {
164         Header header = new Header("Set-Cookie",
165             "cookie-name=cookie-value; domain=.com; version=1");
166 
167         CookieSpec cookiespec = new RFC2109Spec();
168         try {
169             Cookie[] parsed = cookieParse(cookiespec, "b.com", 80, "/", false, header);
170             fail("MalformedCookieException should have been thrown");
171         } catch (MalformedCookieException e) {
172             // expected
173         }
174     }
175     /**
176      * Domain must have alt least one embedded dot
177      */
178     public void testParseWithIllegalDomain3() throws Exception {
179         Header header = new Header("Set-Cookie",
180             "cookie-name=cookie-value; domain=.com.; version=1");
181 
182         CookieSpec cookiespec = new RFC2109Spec();
183         try {
184             Cookie[] parsed = cookieParse(cookiespec, "b.com", 80, "/", false, header);
185             fail("HttpException exception should have been thrown");
186         } catch (MalformedCookieException e) {
187             // expected
188         }
189     }
190 
191     /**
192      * Host minus domain may not contain any dots
193      */
194     public void testParseWithIllegalDomain4() throws Exception {
195         Header header = new Header("Set-Cookie",
196             "cookie-name=cookie-value; domain=.c.com; version=1");
197 
198         CookieSpec cookiespec = new RFC2109Spec();
199         try {
200             Cookie[] parsed = cookieParse(cookiespec, "a.b.c.com", 80, "/", false, header);
201             fail("MalformedCookieException should have been thrown");
202         } catch (MalformedCookieException e) {
203             // expected
204         }
205     }
206 
207     /**
208      * Tests if that invalid second domain level cookie gets 
209      * rejected in the strict mode, but gets accepted in the
210      * browser compatibility mode.
211      */
212     public void testSecondDomainLevelCookie() throws Exception {
213         Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); 
214         cookie.setDomainAttributeSpecified(true);
215         cookie.setPathAttributeSpecified(true);
216 
217         CookieSpec cookiespec = new RFC2109Spec();
218         try {
219             cookiespec.validate("sourceforge.net", 80, "/", false, cookie);
220             fail("MalformedCookieException should have been thrown");
221         } catch (MalformedCookieException e) {
222             // Expected
223         }
224     }    
225 
226     public void testSecondDomainLevelCookieMatch() throws Exception {
227         Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); 
228         cookie.setDomainAttributeSpecified(true);
229         cookie.setPathAttributeSpecified(true);
230 
231         CookieSpec cookiespec = new RFC2109Spec();
232         assertFalse(cookiespec.match("sourceforge.net", 80, "/", false, cookie));
233     }
234     
235     public void testParseWithWrongPath() throws Exception {
236         Header header = new Header("Set-Cookie",
237             "cookie-name=cookie-value; domain=127.0.0.1; path=/not/just/root");
238 
239         CookieSpec cookiespec = new RFC2109Spec();
240         try {
241             Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header);
242             fail("HttpException exception should have been thrown");
243         } catch (MalformedCookieException e) {
244             // expected
245         }
246     }
247 
248     /**
249      * Tests if cookie constructor rejects cookie name containing blanks.
250      */
251     public void testCookieNameWithBlanks() throws Exception {
252         Header setcookie = new Header("Set-Cookie", "invalid name=");
253         CookieSpec cookiespec = new RFC2109Spec();
254         try {
255             Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, setcookie);
256             fail("MalformedCookieException exception should have been thrown");
257         } catch (MalformedCookieException e) {
258             // expected
259         }
260     }
261 
262 
263     /**
264      * Tests if cookie constructor rejects cookie name starting with $.
265      */
266     public void testCookieNameStartingWithDollarSign() throws Exception {
267         Header setcookie = new Header("Set-Cookie", "$invalid_name=");
268         CookieSpec cookiespec = new RFC2109Spec();
269         try {
270             Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, setcookie);
271             fail("MalformedCookieException exception should have been thrown");
272         } catch (MalformedCookieException e) {
273             // expected
274         }
275     }
276 
277     /**
278      * Tests if default cookie validator rejects cookies originating from a host without domain
279      * where domain attribute does not match the host of origin 
280      */
281     public void testInvalidDomainWithSimpleHostName() throws Exception {    
282         CookieSpec cookiespec = new RFC2109Spec();
283         Header header = new Header("Set-Cookie", 
284             "name=\"value\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\"");
285         Cookie[]cookies = cookiespec.parse("host", 80, "/", false, header );
286         try {
287             cookiespec.validate("host", 80, "/", false, cookies[0]);
288             fail("MalformedCookieException must have thrown");
289         }
290         catch(MalformedCookieException expected) {
291         }
292         header = new Header("Set-Cookie", 
293             "name=\"value\"; version=\"1\"; path=\"/\"; domain=\"host1\"");
294         cookies = cookiespec.parse("host2", 80, "/", false, header );
295         try {
296             cookiespec.validate("host2", 80, "/", false, cookies[0]);
297             fail("MalformedCookieException must have thrown");
298         }
299         catch(MalformedCookieException expected) {
300         }
301     }
302 
303     /**
304      * Tests if cookie values with embedded comma are handled correctly.
305      */
306     public void testCookieWithComma() throws Exception {
307         Header header = new Header("Set-Cookie", "a=b,c");
308 
309         CookieSpec cookiespec = new RFC2109Spec();
310         Cookie[] cookies = cookiespec.parse("localhost", 80, "/", false, header);
311         assertEquals("number of cookies", 2, cookies.length);
312         assertEquals("a", cookies[0].getName());
313         assertEquals("b", cookies[0].getValue());
314         assertEquals("c", cookies[1].getName());
315         assertEquals(null, cookies[1].getValue());
316     }
317 
318     public void testFormatInvalidCookies() throws Exception {
319         CookieSpec cookiespec = new RFC2109Spec();
320         try {
321             String s = cookiespec.formatCookie(null);
322             fail("IllegalArgumentException nust have been thrown");
323         } catch (IllegalArgumentException expected) {
324         }
325     }    
326 
327     /**
328      * Tests RFC 2109 compiant cookie formatting.
329      */
330     public void testRFC2109CookieFormatting() throws Exception {
331         CookieSpec cookiespec = new RFC2109Spec();
332         Header header = new Header("Set-Cookie", 
333             "name=\"value\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\"");
334         Cookie[] cookies  = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header );
335         cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
336         String s1 = cookiespec.formatCookie(cookies[0]);
337         assertEquals(s1, "$Version=\"1\"; name=\"value\"; $Path=\"/\"; $Domain=\".mydomain.com\"");
338 
339         header = new Header( "Set-Cookie", 
340             "name=value; path=/; domain=.mydomain.com");
341         cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header );
342         cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]);
343         String s2 = cookiespec.formatCookie(cookies[0]);
344         assertEquals(s2, "$Version=0; name=value; $Path=/; $Domain=.mydomain.com");
345     }
346 
347     public void testRFC2109CookiesFormatting() throws Exception {
348         CookieSpec cookiespec = new RFC2109Spec();
349         Header header = new Header("Set-Cookie", 
350             "name1=value1; path=/; domain=.mydomain.com, " + 
351             "name2=\"value2\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\"");
352         Cookie[] cookies = cookieParse(cookiespec, "myhost.mydomain.com", 80, "/", false, header);
353         assertNotNull(cookies);
354         assertEquals(2, cookies.length);
355         String s1 = cookiespec.formatCookies(cookies);
356         assertEquals(s1, 
357             "$Version=0; name1=value1; $Path=/; $Domain=.mydomain.com; " + 
358             "name2=value2; $Path=/; $Domain=.mydomain.com");
359 
360         header = new Header("Set-Cookie", 
361             "name1=value1; version=1; path=/; domain=.mydomain.com, " + 
362             "name2=\"value2\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\"");
363         cookies = cookieParse(cookiespec, "myhost.mydomain.com", 80, "/", false, header);
364         assertNotNull(cookies);
365         assertEquals(2, cookies.length);
366         String s2 = cookiespec.formatCookies(cookies);
367         assertEquals(s2, 
368             "$Version=\"1\"; name1=\"value1\"; $Path=\"/\"; $Domain=\".mydomain.com\"; " + 
369             "name2=\"value2\"; $Path=\"/\"; $Domain=\".mydomain.com\"");
370     }
371     
372     /**
373      * Tests if null cookie values are handled correctly.
374      */
375     public void testNullCookieValueFormatting() {
376         Cookie cookie = new Cookie(".whatever.com", "name", null, "/", null, false); 
377         cookie.setDomainAttributeSpecified(true);
378         cookie.setPathAttributeSpecified(true);
379 
380         CookieSpec cookiespec = new RFC2109Spec();
381         String s = cookiespec.formatCookie(cookie);
382         assertEquals("$Version=0; name=; $Path=/; $Domain=.whatever.com", s);
383 
384         cookie.setVersion(1);
385         s = cookiespec.formatCookie(cookie);
386         assertEquals("$Version=\"1\"; name=\"\"; $Path=\"/\"; $Domain=\".whatever.com\"", s);
387     }
388 
389     public void testCookieNullDomainNullPathFormatting() {
390         Cookie cookie = new Cookie(null, "name", null, "/", null, false); 
391         cookie.setDomainAttributeSpecified(true);
392         cookie.setPathAttributeSpecified(true);
393 
394         CookieSpec cookiespec = new RFC2109Spec();
395         String s = cookiespec.formatCookie(cookie);
396         assertEquals("$Version=0; name=; $Path=/", s);
397 
398         cookie.setDomainAttributeSpecified(false);
399         cookie.setPathAttributeSpecified(false);
400         s = cookiespec.formatCookie(cookie);
401         assertEquals("$Version=0; name=", s);
402     }
403 
404 }
405 

././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieRFC2965Spec.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieRFC2965Spec.htm100644 0 0 252052 10661532627 30653 0ustar 0 0 TestCookieRFC2965Spec xref

1   /*
2    * $Header: $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import junit.framework.Test;
33  import junit.framework.TestSuite;
34  
35  import org.apache.commons.httpclient.Cookie;
36  import org.apache.commons.httpclient.Header;
37  
38  import java.util.Date;
39  
40  /**
41   * Test cases for RFC2965 cookie spec
42   *
43   * @author jain.samit@gmail.com (Samit Jain)
44   */
45  public class TestCookieRFC2965Spec extends TestCookieBase {
46  
47      // ------------------------------------------------------------ Constructor
48  
49      public TestCookieRFC2965Spec(String name) {
50          super(name);
51      }
52  
53      // ------------------------------------------------------- TestCase Methods
54  
55      public static Test suite() {
56          return new TestSuite(TestCookieRFC2965Spec.class);
57      }
58  
59  
60      // ------------------------------------------------------- Test Cookie Parsing
61  
62      /**
63       * Test <tt>parse</tt> with invalid params.
64       */
65      public void testParseInvalidParams() throws Exception {
66          CookieSpec cookiespec = new RFC2965Spec();
67          try {
68              // invalid header
69              cookiespec.parse("www.domain.com", 80, "/", false, (Header) null /* header */);
70              fail("IllegalArgumentException must have been thrown");
71          } catch (IllegalArgumentException expected) {}
72  
73          Header header = new Header("Set-Cookie2", "name=value;Version=1");
74          try {
75              // invalid request host
76              cookiespec.parse(null /* host */, 80, "/", false, header);
77              fail("IllegalArgumentException must have been thrown");
78          } catch (IllegalArgumentException expected) {}
79          try {
80              // invalid request port
81              cookiespec.parse("www.domain.com", -32 /* port */, "/", false, header);
82              fail("IllegalArgumentException must have been thrown");
83          } catch (IllegalArgumentException expected) {}
84          try {
85              // invalid request path
86              cookiespec.parse("www.domain.com", 80, null /* path */, false, header);
87              fail("IllegalArgumentException must have been thrown");
88          } catch (IllegalArgumentException expected) {}
89      }
90  
91      /**
92       * Test parsing cookie <tt>"Path"</tt> attribute.
93       */
94      public void testParsePath() throws Exception {
95          CookieSpec cookiespec = new RFC2965Spec();
96          Header header = new Header("Set-Cookie2", "name=value;Path=/;Version=1;Path=");
97          Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
98          assertNotNull(parsed);
99          assertEquals(1, parsed.length);
100         // only the first occurence of path attribute is considered, others ignored
101         Cookie2 cookie = (Cookie2) parsed[0];
102         assertEquals("/", cookie.getPath());
103         assertTrue(cookie.isPathAttributeSpecified());
104     }
105 
106     public void testParsePathDefault() throws Exception {
107         CookieSpec cookiespec = new RFC2965Spec();
108         // Path is OPTIONAL, defaults to the request path
109         Header header = new Header("Set-Cookie2", "name=value;Version=1");
110         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/path" /* request path */, false, header);
111         assertNotNull(parsed);
112         assertEquals(1, parsed.length);
113         Cookie2 cookie = (Cookie2) parsed[0];
114         assertEquals("/path", cookie.getPath());
115         assertFalse(cookie.isPathAttributeSpecified());
116     }
117 
118     public void testParseNullPath() throws Exception {
119         CookieSpec cookiespec = new RFC2965Spec();
120         Header header = new Header("Set-Cookie2", "name=value;Path=;Version=1");
121         try {
122             cookiespec.parse("www.domain.com", 80, "/", false, header);
123             fail("MalformedCookieException should have been thrown");
124         } catch (MalformedCookieException ex) {
125             // expected
126         }
127     }
128 
129     public void testParseBlankPath() throws Exception {
130         CookieSpec cookiespec = new RFC2965Spec();
131         Header header = new Header("Set-Cookie2", "name=value;Path=\"   \";Version=1");
132         try {
133             cookiespec.parse("www.domain.com", 80, "/", false, header);
134             fail("MalformedCookieException should have been thrown");
135         } catch (MalformedCookieException ex) {
136             // expected
137         }
138     }
139     /**
140      * Test parsing cookie <tt>"Domain"</tt> attribute.
141      */
142     public void testParseDomain() throws Exception {
143         CookieSpec cookiespec = new RFC2965Spec();
144         Header header = new Header("Set-Cookie2", "name=value;Domain=.domain.com;Version=1;Domain=");
145         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
146         assertNotNull(parsed);
147         assertEquals(1, parsed.length);
148         // only the first occurence of domain attribute is considered, others ignored
149         Cookie2 cookie = (Cookie2) parsed[0];
150         assertEquals(".domain.com", cookie.getDomain());
151         assertTrue(cookie.isDomainAttributeSpecified());
152 
153         // should put a leading dot if there is no dot in front of domain
154         header = new Header("Set-Cookie2", "name=value;Domain=domain.com;Version=1");
155         parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
156         assertNotNull(parsed);
157         assertEquals(1, parsed.length);
158         cookie = (Cookie2) parsed[0];
159         assertEquals(".domain.com", cookie.getDomain());
160     }
161 
162     public void testParseDomainDefault() throws Exception {
163         CookieSpec cookiespec = new RFC2965Spec();
164         // Domain is OPTIONAL, defaults to the request host
165         Header header = new Header("Set-Cookie2", "name=value;Version=1");
166         Cookie[] parsed = cookiespec.parse("www.domain.com" /* request host */, 80, "/", false, header);
167         assertNotNull(parsed);
168         assertEquals(1, parsed.length);
169         Cookie2 cookie = (Cookie2) parsed[0];
170         assertEquals("www.domain.com", cookie.getDomain());
171         assertFalse(cookie.isDomainAttributeSpecified());
172     }
173 
174     public void testParseNullDomain() throws Exception {
175         CookieSpec cookiespec = new RFC2965Spec();
176         // domain cannot be null
177         Header header = new Header("Set-Cookie2", "name=value;Domain=;Version=1");
178         try {
179             cookiespec.parse("www.domain.com", 80, "/", false, header);
180             fail("MalformedCookieException should have been thrown");
181         } catch (MalformedCookieException ex) {
182             // expected
183         }
184     }
185 
186     public void testParseBlankDomain() throws Exception {
187         CookieSpec cookiespec = new RFC2965Spec();
188         Header header = new Header("Set-Cookie2", "name=value;Domain=\"   \";Version=1");
189         try {
190             cookiespec.parse("www.domain.com", 80, "/", false, header);
191             fail("MalformedCookieException should have been thrown");
192         } catch (MalformedCookieException ex) {
193             // expected
194         }
195     }
196 
197     /**
198      * Test parsing cookie <tt>"Port"</tt> attribute.
199      */
200     public void testParsePort() throws Exception {
201         CookieSpec cookiespec = new RFC2965Spec();
202         Header header = new Header("Set-Cookie2", "name=value;Port=\"80,800,8000\";Version=1;Port=nonsense");
203         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
204         assertNotNull(parsed);
205         assertEquals(1, parsed.length);
206         // only the first occurence of port attribute is considered, others ignored
207         Cookie2 cookie = (Cookie2) parsed[0];
208         int[] ports = cookie.getPorts();
209         assertNotNull(ports);
210         assertEquals(3, ports.length);
211         assertEquals(80, ports[0]);
212         assertEquals(800, ports[1]);
213         assertEquals(8000, ports[2]);
214         assertTrue(cookie.isPortAttributeSpecified());
215     }
216 
217     public void testParsePortDefault() throws Exception {
218         CookieSpec cookiespec = new RFC2965Spec();
219         // Port is OPTIONAL, cookie can be accepted from any port
220         Header header = new Header("Set-Cookie2", "name=value;Version=1");
221         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
222         assertNotNull(parsed);
223         assertEquals(1, parsed.length);
224         Cookie2 cookie = (Cookie2) parsed[0];
225         assertFalse(cookie.isPortAttributeSpecified());
226     }
227 
228     public void testParseNullPort() throws Exception {
229         CookieSpec cookiespec = new RFC2965Spec();
230         // null port defaults to request port
231         Header header = new Header("Set-Cookie2", "name=value;Port=;Version=1");
232         Cookie[] parsed = cookiespec.parse("www.domain.com", 80 /* request port */, "/", false, header);
233         assertNotNull(parsed);
234         assertEquals(1, parsed.length);
235         Cookie2 cookie = (Cookie2) parsed[0];
236         int[] ports = cookie.getPorts();
237         assertNotNull(ports);
238         assertEquals(1, ports.length);
239         assertEquals(80, ports[0]);
240         assertTrue(cookie.isPortAttributeSpecified() && cookie.isPortAttributeBlank());
241     }
242 
243     public void testParseBlankPort() throws Exception {
244         CookieSpec cookiespec = new RFC2965Spec();
245         // blank port defaults to request port
246         Header header = new Header("Set-Cookie2", "name=value;Port=\"  \";Version=1");
247         Cookie[] parsed = cookiespec.parse("www.domain.com", 80 /* request port */, "/", false, header);
248         assertNotNull(parsed);
249         assertEquals(1, parsed.length);
250         Cookie2 cookie = (Cookie2) parsed[0];
251         int[] ports = cookie.getPorts();
252         assertNotNull(ports);
253         assertEquals(1, ports.length);
254         assertEquals(80, ports[0]);
255         assertTrue(cookie.isPortAttributeSpecified() && cookie.isPortAttributeBlank());
256     }
257 
258     public void testParseInvalidPort() throws Exception {
259         CookieSpec cookiespec = new RFC2965Spec();
260         Header header = new Header("Set-Cookie2", "name=value;Port=nonsense;Version=1");
261         try {
262             cookiespec.parse("www.domain.com", 80, "/", false, header);
263             fail("MalformedCookieException should have been thrown");
264         } catch (MalformedCookieException ex) {
265             // expected
266         }
267     }
268 
269     public void testParseNegativePort() throws Exception {
270         CookieSpec cookiespec = new RFC2965Spec();
271         Header header = new Header("Set-Cookie2", "name=value;Port=\"80,-800,8000\";Version=1");
272         try {
273             cookiespec.parse("www.domain.com", 80, "/", false, header);
274             fail("MalformedCookieException should have been thrown");
275         } catch (MalformedCookieException ex) {
276             // expected
277         }
278     }
279 
280     /**
281      * test parsing cookie name/value.
282      */
283     public void testParseNameValue() throws Exception {
284         CookieSpec cookiespec = new RFC2965Spec();
285         Header header = new Header("Set-Cookie2", "name=value;Version=1;");
286         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
287         assertNotNull(parsed);
288         assertEquals(1, parsed.length);
289         Cookie2 cookie = (Cookie2) parsed[0];
290         assertEquals("name", cookie.getName());
291         assertEquals("value", cookie.getValue());
292     }
293 
294     /**
295      * test parsing cookie <tt>"Version"</tt> attribute.
296      */
297     public void testParseVersion() throws Exception {
298         CookieSpec cookiespec = new RFC2965Spec();
299         Header header = new Header("Set-Cookie2", "name=value;Version=1;");
300         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
301         assertNotNull(parsed);
302         assertEquals(1, parsed.length);
303         Cookie2 cookie = (Cookie2) parsed[0];
304         assertEquals(1, cookie.getVersion());
305         assertTrue(cookie.isVersionAttributeSpecified());
306     }
307 
308     public void testParseNullVersion() throws Exception {
309         CookieSpec cookiespec = new RFC2965Spec();
310         // version cannot ne null
311         Header header = new Header("Set-Cookie2", "name=value;Version=;");
312         try {
313             cookiespec.parse("www.domain.com", 80, "/", false, header);
314             fail("MalformedCookieException should have been thrown");
315         } catch (MalformedCookieException ex) {
316             // expected
317         }
318     }
319     
320     public void testParseNegativeVersion() throws Exception {
321         CookieSpec cookiespec = new RFC2965Spec();
322         Header header = new Header("Set-Cookie2", "name=value;Version=-1;");
323         try {
324             cookiespec.parse("www.domain.com", 80, "/", false, header);
325             fail("MalformedCookieException should have been thrown");
326         } catch (MalformedCookieException ex) {
327             // expected
328         }
329     }
330     /**
331      * test parsing cookie <tt>"Max-age"</tt> attribute.
332      */
333     public void testParseMaxage() throws Exception {
334         CookieSpec cookiespec = new RFC2965Spec();
335         Header header = new Header("Set-Cookie2", "name=value;Max-age=3600;Version=1;Max-age=nonsense");
336         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
337         assertNotNull(parsed);
338         assertEquals(1, parsed.length);
339         // only the first occurence of max-age attribute is considered, others ignored
340         Cookie2 cookie = (Cookie2) parsed[0];
341         assertFalse(cookie.isExpired());
342     }
343 
344     public void testParseMaxageDefault() throws Exception {
345         CookieSpec cookiespec = new RFC2965Spec();
346         // Max-age is OPTIONAL, defaults to session cookie
347         Header header = new Header("Set-Cookie2", "name=value;Version=1");
348         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
349         assertNotNull(parsed);
350         assertEquals(1, parsed.length);
351         Cookie2 cookie = (Cookie2) parsed[0];
352         assertFalse(cookie.isPersistent());
353     }
354 
355     public void testParseNullMaxage() throws Exception {
356         CookieSpec cookiespec = new RFC2965Spec();
357         Header header = new Header("Set-Cookie2", "name=value;Max-age=;Version=1");
358         try {
359             cookiespec.parse("www.domain.com", 80, "/", false, header);
360             fail("MalformedCookieException should have been thrown");
361         } catch (MalformedCookieException ex) {
362             // expected
363         }
364     }
365 
366     public void testParseNegativeMaxage() throws Exception {
367         CookieSpec cookiespec = new RFC2965Spec();
368         Header header = new Header("Set-Cookie2", "name=value;Max-age=-3600;Version=1;");
369         try {
370             cookiespec.parse("www.domain.com", 80, "/", false, header);
371             fail("MalformedCookieException should have been thrown");
372         } catch (MalformedCookieException ex) {
373             // expected
374         }
375     }
376 
377     /**
378      * test parsing <tt>"Secure"</tt> attribute.
379      */
380     public void testParseSecure() throws Exception {
381         CookieSpec cookiespec = new RFC2965Spec();
382         Header header = new Header("Set-Cookie2", "name=value;Secure;Version=1");
383         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
384         assertNotNull(parsed);
385         assertEquals(1, parsed.length);
386         Cookie2 cookie = (Cookie2) parsed[0];
387         assertTrue(cookie.getSecure());
388     }
389 
390     /**
391      * test parsing <tt>"Discard"</tt> attribute.
392      */
393     public void testParseDiscard() throws Exception {
394         CookieSpec cookiespec = new RFC2965Spec();
395         Header header = new Header("Set-Cookie2", "name=value;Discard;Max-age=36000;Version=1");
396         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
397         assertNotNull(parsed);
398         assertEquals(1, parsed.length);
399         Cookie2 cookie = (Cookie2) parsed[0];
400         // discard overrides max-age
401         assertFalse(cookie.isPersistent());
402 
403         // Discard is OPTIONAL, default behavior is dictated by max-age
404         header = new Header("Set-Cookie2", "name=value;Max-age=36000;Version=1");
405         parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
406         assertNotNull(parsed);
407         assertEquals(1, parsed.length);
408         cookie = (Cookie2) parsed[0];
409         assertTrue(cookie.isPersistent());
410     }
411 
412     /**
413      * test parsing <tt>"Comment"</tt>, <tt>"CommentURL"</tt> and
414      * <tt>"Secure"</tt> attributes.
415      */
416     public void testParseOtherAttributes() throws Exception {
417         CookieSpec cookiespec = new RFC2965Spec();
418         Header header = new Header("Set-Cookie2", "name=value;Comment=\"good cookie\";" +
419                 "CommentURL=\"www.domain.com/goodcookie/\";Secure;Version=1");
420         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
421         assertNotNull(parsed);
422         assertEquals(1, parsed.length);
423         Cookie2 cookie = (Cookie2) parsed[0];
424         assertEquals("good cookie", cookie.getComment());
425         assertEquals("www.domain.com/goodcookie/", cookie.getCommentURL());
426         assertTrue(cookie.getSecure());
427 
428         // Comment, CommentURL, Secure are OPTIONAL
429         header = new Header("Set-Cookie2", "name=value;Version=1");
430         parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
431         assertNotNull(parsed);
432         assertEquals(1, parsed.length);
433         cookie = (Cookie2) parsed[0];
434         assertFalse(cookie.getSecure());
435     }
436 
437     /**
438      * Test parsing header with 2 cookies (separated by comma)
439      */
440     public void testCookiesWithComma() throws Exception {
441         CookieSpec cookiespec = new RFC2965Spec();
442         Header header = new Header("Set-Cookie2", "a=b,c");
443         Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header);
444         assertNotNull(parsed);
445         assertEquals(2, parsed.length);
446         assertEquals("a", parsed[0].getName());
447         assertEquals("b", parsed[0].getValue());
448         assertEquals("c", parsed[1].getName());
449         assertEquals(null, parsed[1].getValue());
450     }
451 
452     // ------------------------------------------------------- Test Cookie Validation
453 
454     /**
455      * Test <tt>Domain</tt> validation when domain is not specified
456      * in <tt>Set-Cookie2</tt> header.
457      */
458     public void testValidateNoDomain() throws Exception {
459         CookieSpec cookiespec = new RFC2965Spec();
460         Header header = new Header("Set-Cookie2", "name=value;Version=1");
461         Cookie[] parsed = cookieParse(cookiespec, "www.domain.com" /* request host */, 80, "/", false, header);
462         assertNotNull(parsed);
463         assertEquals(1, parsed.length);
464         Cookie2 cookie = (Cookie2) parsed[0];
465         // cookie domain must string match request host
466         assertEquals("www.domain.com", cookie.getDomain());
467     }
468 
469     /**
470      * Test <tt>Domain</tt> validation. Cookie domain attribute must have a
471      * leading dot.
472      */
473     public void testValidateDomainLeadingDot() throws Exception {
474         CookieSpec cookiespec = new RFC2965Spec();
475         Header header = new Header("Set-Cookie2", "name=value;Domain=domain.com;Version=1");
476         Cookie[] parsed = cookieParse(cookiespec, "www.domain.com", 80, "/", false, header);
477         assertNotNull(parsed);
478         assertEquals(1, parsed.length);
479         Cookie2 cookie = (Cookie2) parsed[0];
480         assertEquals(".domain.com", cookie.getDomain());
481     }
482 
483     /**
484      * Test <tt>Domain</tt> validation. Domain must have atleast one embedded dot.
485      */
486     public void testValidateDomainEmbeddedDot() throws Exception {
487         CookieSpec cookiespec = new RFC2965Spec();
488         Header header = new Header("Set-Cookie2", "name=value; domain=.com; version=1");
489         try {
490             cookieParse(cookiespec, "b.com", 80, "/", false, header);
491             fail("MalformedCookieException should have been thrown");
492         } catch (MalformedCookieException expected) {}
493 
494         header = new Header("Set-Cookie2", "name=value;Domain=domain.com;Version=1");
495         Cookie[] parsed = cookieParse(cookiespec, "www.domain.com", 80, "/", false, header);
496         assertNotNull(parsed);
497         assertEquals(1, parsed.length);
498     }
499 
500     /**
501      * Test local <tt>Domain</tt> validation. Simple host names
502      * (without any dots) are valid only when cookie domain is specified
503      * as ".local".
504      */
505     public void testValidateDomainLocal() throws Exception {
506         CookieSpec cookiespec = new RFC2965Spec();
507         // when domain is specified as .local, simple host names are valid
508         Header header = new Header("Set-Cookie2", "name=value; domain=.local; version=1");
509         Cookie[] parsed = cookieParse(cookiespec, "simplehost" /* request host */, 80, "/", false, header);
510         assertNotNull(parsed);
511         assertEquals(1, parsed.length);
512         Cookie2 cookie = (Cookie2) parsed[0];
513         assertEquals(".local", cookie.getDomain());
514 
515         // when domain is NOT specified as .local, simple host names are invalid
516         header = new Header("Set-Cookie2", "name=value; domain=domain.com; version=1");
517         try {
518             // since domain is not .local, this must fail
519             parsed = cookieParse(cookiespec, "simplehost" /* request host */, 80, "/", false, header);
520             fail("MalformedCookieException should have been thrown");
521         } catch (MalformedCookieException expected) {}
522     }
523 
524 
525     /**
526      * Test <tt>Domain</tt> validation. Effective host name
527      * must domain-match domain attribute.
528      */
529     public void testValidateDomainEffectiveHost() throws Exception {
530         CookieSpec cookiespec = new RFC2965Spec();
531 
532         // cookie domain does not domain-match request host
533         Header header = new Header("Set-Cookie2", "name=value; domain=.domain.com; version=1");
534         try {
535             cookieParse(cookiespec, "www.domain.org" /* request host */, 80, "/", false, header);
536             fail("MalformedCookieException should have been thrown");
537         } catch (MalformedCookieException expected) {}
538 
539         // cookie domain domain-matches request host
540         header = new Header("Set-Cookie2", "name=value; domain=.domain.com; version=1");
541         Cookie[] parsed = cookieParse(cookiespec, "www.domain.com" /* request host */, 80, "/", false, header);
542         assertNotNull(parsed);
543         assertEquals(1, parsed.length);
544     }
545 
546     /**
547      * Test local <tt>Domain</tt> validation.
548      * Effective host name minus domain must not contain any dots.
549      */
550     public void testValidateDomainIllegal() throws Exception {
551         CookieSpec cookiespec = new RFC2965Spec();
552         Header header = new Header("Set-Cookie2", "name=value; domain=.domain.com; version=1");
553         try {
554             cookieParse(cookiespec, "a.b.domain.com" /* request host */, 80, "/", false, header);
555             fail("MalformedCookieException should have been thrown");
556         } catch (MalformedCookieException expected) {}
557     }
558 
559     /**
560      * Test cookie <tt>Path</tt> validation. Cookie path attribute must path-match
561      * request path.
562      */
563     public void testValidatePath() throws Exception {
564         CookieSpec cookiespec = new RFC2965Spec();
565         Header header = new Header("Set-Cookie2", "name=value;path=/path;version=1");
566         try {
567             cookieParse(cookiespec, "www.domain.com", 80, "/" /* request path */, false, header);
568             fail("MalformedCookieException exception should have been thrown");
569         } catch (MalformedCookieException expected) {}
570 
571         // path-matching is case-sensitive
572         header = new Header("Set-Cookie2", "name=value;path=/Path;version=1");
573         try {
574             cookieParse(cookiespec, "www.domain.com", 80, "/path" /* request path */, false, header);
575             fail("MalformedCookieException exception should have been thrown");
576         } catch (MalformedCookieException expected) {}
577 
578         header = new Header("Set-Cookie2", "name=value;path=/path;version=1");
579         Cookie[] parsed = cookieParse(cookiespec, "www.domain.com",
580                                       80, "/path/path1" /* request path */, false, header);
581         assertNotNull(parsed);
582         assertEquals(1, parsed.length);
583         assertEquals("/path", parsed[0].getPath());
584     }
585 
586     /**
587      * Test cookie name validation.
588      */
589     public void testValidateCookieName() throws Exception {
590         CookieSpec cookiespec = new RFC2965Spec();
591         // cookie name must not contain blanks
592         Header header = new Header("Set-Cookie2", "invalid name=value; version=1");
593         try {
594             cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header);
595             fail("MalformedCookieException exception should have been thrown");
596         } catch (MalformedCookieException expected) {}
597 
598         // cookie name must not start with '$'.
599         header = new Header("Set-Cookie2", "$invalid_name=value; version=1");
600         try {
601             cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header);
602             fail("MalformedCookieException exception should have been thrown");
603         } catch (MalformedCookieException expected) {}
604 
605         // valid name
606         header = new Header("Set-Cookie2", "name=value; version=1");
607         Cookie[] parsed = cookieParse(cookiespec, "www.domain.com", 80, "/", false, header);
608         assertNotNull(parsed);
609         assertEquals(1, parsed.length);
610         Cookie2 cookie = (Cookie2) parsed[0];
611         assertEquals("name", cookie.getName());
612         assertEquals("value", cookie.getValue());
613     }
614 
615     /**
616      * Test cookie <tt>Port</tt> validation. Request port must be in the
617      * port attribute list.
618      */
619     public void testValidatePort() throws Exception {
620         Header header = new Header("Set-Cookie2", "name=value; Port=\"80,800\"; version=1");
621         CookieSpec cookiespec = new RFC2965Spec();
622         try {
623             cookieParse(cookiespec, "www.domain.com", 8000 /* request port */, "/", false, header);
624             fail("MalformedCookieException should have been thrown");
625         } catch (MalformedCookieException e) {}
626 
627         // valid port list
628         Cookie[] parsed = cookieParse(cookiespec, "www.domain.com", 80 /* request port */, "/", false, header);
629         assertNotNull(parsed);
630         assertEquals(1, parsed.length);
631         Cookie2 cookie = (Cookie2) parsed[0];
632         int[] ports = cookie.getPorts();
633         assertNotNull(ports);
634         assertEquals(2, ports.length);
635         assertEquals(80, ports[0]);
636         assertEquals(800, ports[1]);
637     }
638 
639     /**
640      * Test cookie <tt>Version</tt> validation.
641      */
642     public void testValidateVersion() throws Exception {
643         CookieSpec cookiespec = new RFC2965Spec();
644         // version attribute is REQUIRED
645         Header header = new Header("Set-Cookie2", "name=value");
646         try {
647             cookieParse(cookiespec, "www.domain.com", 8000, "/", false, header);
648             fail("MalformedCookieException should have been thrown");
649         } catch (MalformedCookieException e) {}
650     }
651 
652     // ------------------------------------------------------- Test Cookie Matching
653 
654     /**
655      * test cookie <tt>Path</tt> matching. Cookie path attribute must path-match
656      * path of the request URI.
657      */
658     public void testMatchPath() throws Exception {
659         Cookie2 cookie = new Cookie2(".domain.com", "name",
660                                      "value", "/path" /* path */, null, false, new int[] {80});
661         CookieSpec cookiespec = new RFC2965Spec();
662         assertFalse(cookiespec.match("www.domain.com", 80, "/" /* request path */, false, cookie));
663         assertTrue(cookiespec.match("www.domain.com", 80, "/path/path1" /* request path */, false, cookie));
664     }
665 
666     /**
667      * test cookie <tt>Domain</tt> matching.
668      */
669     public void testMatchDomain() throws Exception {
670         Cookie2 cookie = new Cookie2(".domain.com" /* domain */, "name",
671                                      "value", "/", null, false, new int[] {80});
672         CookieSpec cookiespec = new RFC2965Spec();
673         // effective host name minus domain must not contain any dots
674         assertFalse(cookiespec.match("a.b.domain.com" /* request host */, 80, "/", false, cookie));
675         // The effective host name MUST domain-match the Domain
676         // attribute of the cookie.
677         assertFalse(cookiespec.match("www.domain.org" /* request host */, 80, "/", false, cookie));
678         assertTrue(cookiespec.match("www.domain.com" /* request host */, 80, "/", false, cookie));
679     }
680 
681     /**
682      * test cookie local <tt>Domain</tt> matching.
683      */
684     public void testMatchDomainLocal() throws Exception {
685         Cookie2 cookie = new Cookie2(".local" /* domain */, "name",
686                                      "value", "/", null, false, new int[] {80});
687         CookieSpec cookiespec = new RFC2965Spec();
688         assertTrue(cookiespec.match("host" /* request host */, 80, "/", false, cookie));
689         assertFalse(cookiespec.match("host.com" /* request host */, 80, "/", false, cookie));
690     }
691 
692     /**
693      * test cookie <tt>Port</tt> matching.
694      */
695     public void testMatchPort() throws Exception {
696         // cookie can be sent to any port if port attribute not specified
697         Cookie2 cookie = new Cookie2(".domain.com", "name",
698                                      "value", "/", null, false, null /* ports */);
699         CookieSpec cookiespec = new RFC2965Spec();
700         cookie.setPortAttributeSpecified(false);
701         assertTrue(cookiespec.match("www.domain.com", 8080 /* request port */, "/", false, cookie));
702         assertTrue(cookiespec.match("www.domain.com", 323  /* request port */, "/", false, cookie));
703 
704         // otherwise, request port must be in cookie's port list
705         cookie = new Cookie2(".domain.com", "name",
706                              "value", "/", null, false, new int[] {80, 8080} /* ports */);
707         cookie.setPortAttributeSpecified(true);
708         assertFalse(cookiespec.match("www.domain.com", 434 /* request port */, "/", false, cookie));
709         assertTrue(cookiespec.match("www.domain.com", 8080 /* request port */, "/", false, cookie));
710     }
711 
712     /**
713      * test cookie expiration.
714      */
715     public void testCookieExpiration() throws Exception {
716         Date afterOneHour = new Date(System.currentTimeMillis() + 3600 * 1000L);
717         Cookie2 cookie = new Cookie2(".domain.com", "name",
718                                      "value", "/", afterOneHour /* expiry */, false, null);
719         CookieSpec cookiespec = new RFC2965Spec();
720         assertTrue(cookiespec.match("www.domain.com", 80, "/", false, cookie));
721 
722         Date beforeOneHour = new Date(System.currentTimeMillis() - 3600 * 1000L);
723         cookie = new Cookie2(".domain.com", "name",
724                              "value", "/", beforeOneHour /* expiry */, false, null);
725         assertFalse(cookiespec.match("www.domain.com", 80, "/", false, cookie));
726 
727         // discard attributes overrides cookie age, makes it a session cookie.
728         cookie.setDiscard(true);
729         assertFalse(cookie.isPersistent());
730         assertTrue(cookiespec.match("www.domain.com", 80, "/", false, cookie));
731     }
732 
733     /**
734      * test cookie <tt>Secure</tt> attribute.
735      */
736     public void testCookieSecure() throws Exception {
737         CookieSpec cookiespec = new RFC2965Spec();
738         // secure cookie can only be sent over a secure connection
739         Cookie2 cookie = new Cookie2(".domain.com", "name",
740                                      "value", "/", null, true /* secure */, null);
741         assertFalse(cookiespec.match("www.domain.com", 80, "/", false /* request secure */, cookie));
742         assertTrue(cookiespec.match("www.domain.com", 80, "/", true /* request secure */, cookie));
743     }
744 
745     // ------------------------------------------------------- Test Cookie Formatting
746 
747     public void testFormatInvalidCookie() throws Exception {
748         CookieSpec cookiespec = new RFC2965Spec();
749         try {
750             cookiespec.formatCookie(null);
751             fail("IllegalArgumentException nust have been thrown");
752         } catch (IllegalArgumentException expected) {}
753     }
754 
755     /**
756      * Tests RFC 2965 compliant cookie formatting.
757      */
758     public void testRFC2965CookieFormatting() throws Exception {
759         CookieSpec cookiespec = new RFC2965Spec();
760         Cookie2 cookie1 = new Cookie2(".domain.com", "name1",
761                                      "value", "/", null, false, new int[] {80,8080});
762         cookie1.setVersion(1);
763         // domain, path, port specified
764         cookie1.setDomainAttributeSpecified(true);
765         cookie1.setPathAttributeSpecified(true);
766         cookie1.setPortAttributeSpecified(true);
767         assertEquals("$Version=\"1\"; name1=\"value\"; $Domain=\".domain.com\"; $Path=\"/\"; $Port=\"80,8080\"",
768                      cookiespec.formatCookie(cookie1));
769 
770         Cookie2 cookie2 = new Cookie2(".domain.com", "name2",
771                 "value", "/a/", null, false, new int[] {80,8080});
772         cookie2.setVersion(2);
773         // domain, path specified  but port unspecified
774         cookie2.setDomainAttributeSpecified(true);
775         cookie2.setPathAttributeSpecified(true);
776         cookie2.setPortAttributeSpecified(false);
777         assertEquals("$Version=\"2\"; name2=\"value\"; $Domain=\".domain.com\"; $Path=\"/a/\"",
778                      cookiespec.formatCookie(cookie2));
779 
780         Cookie2 cookie3 = new Cookie2(".domain.com", "name3",
781                 "value", "/a/b/", null, false, new int[] {80,8080});
782         cookie3.setVersion(1);
783         // path specified, port specified but blank, domain unspecified
784         cookie3.setDomainAttributeSpecified(false);
785         cookie3.setPathAttributeSpecified(true);
786         cookie3.setPortAttributeSpecified(true);
787         cookie3.setPortAttributeBlank(true);
788         assertEquals("$Version=\"1\"; name3=\"value\"; $Path=\"/a/b/\"; $Port=\"\"",
789                      cookiespec.formatCookie(cookie3));
790 
791         assertEquals("$Version=\"2\"; " +
792                 "name3=\"value\"; $Path=\"/a/b/\"; $Port=\"\"; " +
793                 "name2=\"value\"; $Domain=\".domain.com\"; $Path=\"/a/\"; " +
794                 "name1=\"value\"; $Domain=\".domain.com\"; $Path=\"/\"; $Port=\"80,8080\"",
795                 cookiespec.formatCookies(new Cookie[] {cookie3, cookie2, cookie1}));
796     }
797 
798     /**
799      * Tests RFC 2965 compliant cookies formatting.
800      */
801     public void testRFC2965CookiesFormatting() throws Exception {
802         CookieSpec cookiespec = new RFC2965Spec();
803         Cookie2 cookie1 = new Cookie2(".domain.com", "name1",
804                                       "value1", "/", null, false, new int[] {80,8080});
805         cookie1.setVersion(1);
806         // domain, path, port specified
807         cookie1.setDomainAttributeSpecified(true);
808         cookie1.setPathAttributeSpecified(true);
809         cookie1.setPortAttributeSpecified(true);
810         Cookie2 cookie2 = new Cookie2(".domain.com", "name2",
811                                       null, "/", null, false, null);
812         cookie2.setVersion(1);
813         // value null, domain, path, port specified
814         cookie2.setDomainAttributeSpecified(true);
815         cookie2.setPathAttributeSpecified(true);
816         cookie2.setPortAttributeSpecified(false);
817         Cookie[] cookies = new Cookie[] {cookie1, cookie2};
818         assertEquals("$Version=\"1\"; name1=\"value1\"; $Domain=\".domain.com\"; $Path=\"/\"; $Port=\"80,8080\"; " +
819             "name2=\"\"; $Domain=\".domain.com\"; $Path=\"/\"", cookiespec.formatCookies(cookies));
820     }
821 
822     // ------------------------------------------------------- Backward compatibility tests
823 
824     /**
825      * Test backward compatibility with <tt>Set-Cookie</tt> header.
826      */
827     public void testCompatibilityWithSetCookie() throws Exception {
828         CookieSpec cookiespec = new RFC2965Spec();
829         Header header = new Header("Set-Cookie", "name=value; domain=.domain.com; version=1");
830         Cookie[] parsed = cookieParse(cookiespec, "www.domain.com", 80, "/", false, header);
831         assertNotNull(parsed);
832         assertEquals(1, parsed.length);
833         assertEquals("name", parsed[0].getName());
834         assertEquals("value", parsed[0].getValue());
835         assertEquals(".domain.com", parsed[0].getDomain());
836         assertEquals("/", parsed[0].getPath());
837     }
838 
839 }
840 

././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieVersionSupport.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestCookieVersionSupport.100644 0 0 54726 10661532627 31401 0ustar 0 0 TestCookieVersionSupport xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/cookie/TestCookieVersionSupport.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   */
28  
29  package org.apache.commons.httpclient.cookie;
30  
31  import java.io.IOException;
32  
33  import junit.framework.Test;
34  import junit.framework.TestSuite;
35  
36  import org.apache.commons.httpclient.Cookie;
37  import org.apache.commons.httpclient.Header;
38  import org.apache.commons.httpclient.HttpClientTestBase;
39  import org.apache.commons.httpclient.HttpState;
40  import org.apache.commons.httpclient.HttpStatus;
41  import org.apache.commons.httpclient.HttpVersion;
42  import org.apache.commons.httpclient.methods.GetMethod;
43  import org.apache.commons.httpclient.server.HttpService;
44  import org.apache.commons.httpclient.server.SimpleRequest;
45  import org.apache.commons.httpclient.server.SimpleResponse;
46  
47  /**
48   * Cookie version support tests.
49   *
50   * @author Oleg Kalnichevski
51   * 
52   * @version $Revision: 480424 $
53   */
54  public class TestCookieVersionSupport extends HttpClientTestBase {
55  
56      // ------------------------------------------------------------ Constructor
57      public TestCookieVersionSupport(final String testName) throws IOException {
58          super(testName);
59      }
60  
61      // ------------------------------------------------------------------- Main
62      public static void main(String args[]) {
63          String[] testCaseName = { TestCookieVersionSupport.class.getName() };
64          junit.textui.TestRunner.main(testCaseName);
65      }
66  
67      // ------------------------------------------------------- TestCase Methods
68  
69      public static Test suite() {
70          return new TestSuite(TestCookieVersionSupport.class);
71      }
72  
73      private static class CookieVer0Service implements HttpService {
74  
75          public CookieVer0Service() {
76              super();
77          }
78  
79          public boolean process(final SimpleRequest request, final SimpleResponse response)
80              throws IOException
81          {
82              HttpVersion httpversion = request.getRequestLine().getHttpVersion();
83              response.setStatusLine(httpversion, HttpStatus.SC_OK);
84              response.addHeader(new Header("Set-Cookie", "name1=value1; path=/test"));
85              response.setBodyString("whatever");
86              return true;
87          }
88      }
89      
90      
91      public void testCookieVersionSupportHeader1() throws IOException {
92          this.server.setHttpService(new CookieVer0Service());
93          this.client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
94          GetMethod httpget1 = new GetMethod("/test/");
95          try {
96              this.client.executeMethod(httpget1);
97          } finally {
98              httpget1.releaseConnection();
99          }
100         GetMethod httpget2 = new GetMethod("/test/");
101         try {
102             this.client.executeMethod(httpget2);
103         } finally {
104             httpget2.releaseConnection();
105         }
106         Header cookiesupport = httpget2.getRequestHeader("Cookie2");
107         assertNotNull(cookiesupport);
108         assertEquals("$Version=\"1\"", cookiesupport.getValue());
109     }
110     
111     private static class CookieVer1Service implements HttpService {
112 
113         public CookieVer1Service() {
114             super();
115         }
116 
117         public boolean process(final SimpleRequest request, final SimpleResponse response)
118             throws IOException
119         {
120             HttpVersion httpversion = request.getRequestLine().getHttpVersion();
121             response.setStatusLine(httpversion, HttpStatus.SC_OK);
122             response.addHeader(new Header("Set-Cookie", "name1=value1; Path=\"/test\"; Version=\"1\""));
123             response.addHeader(new Header("Set-Cookie2", "name2=value2; Path=\"/test\"; Version=\"1\""));
124             response.setBodyString("whatever");
125             return true;
126         }
127     }
128     
129     
130     public void testCookieVersionSupportHeader2() throws IOException {
131         this.server.setHttpService(new CookieVer1Service());
132         this.client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
133         GetMethod httpget1 = new GetMethod("/test/");
134         try {
135             this.client.executeMethod(httpget1);
136         } finally {
137             httpget1.releaseConnection();
138         }
139         GetMethod httpget2 = new GetMethod("/test/");
140         try {
141             this.client.executeMethod(httpget2);
142         } finally {
143             httpget2.releaseConnection();
144         }
145         Header cookiesupport = httpget2.getRequestHeader("Cookie2");
146         assertNull(cookiesupport);
147     }
148 
149     private static class CookieVer2Service implements HttpService {
150 
151         public CookieVer2Service() {
152             super();
153         }
154 
155         public boolean process(final SimpleRequest request, final SimpleResponse response)
156             throws IOException
157         {
158             HttpVersion httpversion = request.getRequestLine().getHttpVersion();
159             response.setStatusLine(httpversion, HttpStatus.SC_OK);
160             response.addHeader(new Header("Set-Cookie2", "name2=value2; Path=\"/test\"; Version=\"2\""));
161             response.setBodyString("whatever");
162             return true;
163         }
164     }
165     
166     
167     public void testCookieVersionSupportHeader3() throws IOException {
168         this.server.setHttpService(new CookieVer2Service());
169         this.client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
170         GetMethod httpget1 = new GetMethod("/test/");
171         try {
172             this.client.executeMethod(httpget1);
173         } finally {
174             httpget1.releaseConnection();
175         }
176         GetMethod httpget2 = new GetMethod("/test/");
177         try {
178             this.client.executeMethod(httpget2);
179         } finally {
180             httpget2.releaseConnection();
181         }
182         Header cookiesupport = httpget2.getRequestHeader("Cookie2");
183         assertNotNull(cookiesupport);
184         assertEquals("$Version=\"1\"", cookiesupport.getValue());
185     }
186 
187     private static class SetCookieVersionMixService implements HttpService {
188 
189         public SetCookieVersionMixService() {
190             super();
191         }
192 
193         public boolean process(final SimpleRequest request, final SimpleResponse response)
194             throws IOException
195         {
196             HttpVersion httpversion = request.getRequestLine().getHttpVersion();
197             response.setStatusLine(httpversion, HttpStatus.SC_OK);
198             response.addHeader(new Header("Set-Cookie", "name=wrong; Path=/test"));
199             response.addHeader(new Header("Set-Cookie2", "name=right; Path=\"/test\"; Version=\"1\""));
200             response.setBodyString("whatever");
201             return true;
202         }
203     }
204     
205     public static class TestHttpState extends HttpState {
206         
207         public synchronized void addCookie(Cookie cookie) {
208             if (cookie != null) {
209                 if ("localhost.local".equals(cookie.getDomain())) {
210                     cookie.setDomain("localhost");
211                 }
212                 super.addCookie(cookie);
213             }
214         }
215     }
216     
217     public void testSetCookieVersionMix() throws IOException {
218         this.server.setHttpService(new SetCookieVersionMixService());
219         this.client.setState(new TestHttpState());
220         this.client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
221         GetMethod httpget1 = new GetMethod("/test/");
222         try {
223             this.client.executeMethod(httpget1);
224         } finally {
225             httpget1.releaseConnection();
226         }
227         Cookie[] cookies = this.client.getState().getCookies();
228         assertNotNull(cookies);
229         assertEquals(1, cookies.length);
230         assertEquals("right", cookies[0].getValue());
231         assertTrue(cookies[0] instanceof Cookie2);
232     }
233 
234     
235 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/TestDateParser.html100644 0 0 21077 10661532627 30135 0ustar 0 0 TestDateParser xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestDateParser.java,v 1.1 2004/12/24 20:36:13 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import java.util.ArrayList;
33  import java.util.Calendar;
34  import java.util.List;
35  
36  import org.apache.commons.httpclient.util.DateUtil;
37  
38  import junit.framework.Test;
39  import junit.framework.TestCase;
40  import junit.framework.TestSuite;
41  
42  
43  /**
44   * Test cases for expiry date parsing
45   *
46   * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
47   * 
48   * @version $Revision: 480424 $
49   */
50  public class TestDateParser extends TestCase {
51  
52      // ------------------------------------------------------------ Constructor
53  
54      public TestDateParser(String name) {
55          super(name);
56      }
57  
58      // ------------------------------------------------------- TestCase Methods
59  
60      public static Test suite() {
61          return new TestSuite(TestDateParser.class);
62      }
63  
64      private static final String PATTERN = "EEE, dd-MMM-yy HH:mm:ss zzz";
65      private static final List PATTERNS = new ArrayList();
66      
67      static {
68          PATTERNS.add(PATTERN);
69      }
70      
71      public void testFourDigitYear() throws Exception {
72          Calendar calendar = Calendar.getInstance();
73          calendar.setTime(DateUtil.parseDate("Thu, 23-Dec-2004 24:00:00 CET", PATTERNS));
74          assertEquals(2004, calendar.get(Calendar.YEAR));
75      }
76  
77      public void testThreeDigitYear() throws Exception {
78          Calendar calendar = Calendar.getInstance();
79          calendar.setTime(DateUtil.parseDate("Thu, 23-Dec-994 24:00:00 CET", PATTERNS));
80          assertEquals(994, calendar.get(Calendar.YEAR));
81      }
82  
83      public void testTwoDigitYear() throws Exception {
84          Calendar calendar = Calendar.getInstance();
85          calendar.setTime(DateUtil.parseDate("Thu, 23-Dec-04 24:00:00 CET", PATTERNS));
86          assertEquals(2004, calendar.get(Calendar.YEAR));
87  
88          calendar.setTime(DateUtil.parseDate("Thu, 23-Dec-94 24:00:00 CET", PATTERNS));
89          assertEquals(2094, calendar.get(Calendar.YEAR));
90      }
91  
92  }
93  

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/package-frame.html100644 0 0 4467 10661532631 27705 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.cookie

org.apache.commons.httpclient.cookie

Classes

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/cookie/package-summary.html100644 0 0 10105 10661532631 30312 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.cookie

Package org.apache.commons.httpclient.cookie

Class Summary
TestCookie
TestCookie2
TestCookieAll
TestCookieBase
TestCookieCompatibilitySpec
TestCookieIgnoreSpec
TestCookieNetscapeDraft
TestCookiePathComparator
TestCookiePolicy
TestCookieRFC2109Spec
TestCookieRFC2965Spec
TestCookieVersionSupport
TestDateParser

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/package-frame.html100644 0 0 17224 10661532631 26447 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient

org.apache.commons.httpclient

Classes

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/package-summary.html100644 0 0 26370 10661532631 27054 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient

Package org.apache.commons.httpclient

Class Summary
AccessibleHttpConnectionManager
EchoService
ExecuteMethodThread
FakeHttpMethod
FeedbackService
HttpClientTestBase
NoHostHttpConnectionManager
NoncompliantHeadMethod
NoncompliantPostMethod
ProxyTestDecorator
TestAll
TestBadContentLength
TestConnectionPersistence
TestCredentials
TestEffectiveHttpVersion
TestEntityEnclosingMethod
TestEquals
TestExceptions
TestHeader
TestHeaderElement
TestHeaderOps
TestHostConfiguration
TestHttpConnection
TestHttpConnectionManager
TestHttpMethodFundamentals
TestHttpParser
TestHttpState
TestHttpStatus
TestHttpVersion
TestHttps
TestIdleConnectionTimeout
TestMethodAbort
TestMethodCharEncoding
TestMultipartPost
TestNVP
TestNoHost
TestNoncompliant
TestParameterFormatter
TestParameterParser
TestPartsNoHost
TestPostMethod
TestPostParameterEncoding
TestProxy
TestProxyWithRedirect
TestQueryParameters
TestRedirects
TestRequestHeaders
TestRequestLine
TestResponseHeaders
TestStatusLine
TestStreams
TestURI
TestURIUtil
TestURIUtil2
TestVirtualHost

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/params/TestHttpParams.html100644 0 0 36552 10661532627 30204 0ustar 0 0 TestHttpParams xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/params/TestHttpParams.java,v 1.4 2004/10/31 14:42:59 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.params;
31  
32  import java.io.IOException;
33  import java.util.ArrayList;
34  
35  import junit.framework.Test;
36  import junit.framework.TestSuite;
37  
38  import org.apache.commons.httpclient.Header;
39  import org.apache.commons.httpclient.HostConfiguration;
40  import org.apache.commons.httpclient.HttpClientTestBase;
41  import org.apache.commons.httpclient.HttpStatus;
42  import org.apache.commons.httpclient.HttpVersion;
43  import org.apache.commons.httpclient.methods.GetMethod;
44  import org.apache.commons.httpclient.params.HostParams;
45  import org.apache.commons.httpclient.protocol.Protocol;
46  import org.apache.commons.httpclient.server.HttpService;
47  import org.apache.commons.httpclient.server.SimpleRequest;
48  import org.apache.commons.httpclient.server.SimpleResponse;
49  
50  /**
51   * HTTP preference framework tests.
52   *
53   * @author Oleg Kalnichevski
54   * 
55   * @version $Revision: 480424 $
56   */
57  public class TestHttpParams extends HttpClientTestBase {
58  
59      // ------------------------------------------------------------ Constructor
60      public TestHttpParams(final String testName) throws IOException {
61          super(testName);
62      }
63  
64      // ------------------------------------------------------------------- Main
65      public static void main(String args[]) {
66          String[] testCaseName = { TestHttpParams.class.getName() };
67          junit.textui.TestRunner.main(testCaseName);
68      }
69  
70      // ------------------------------------------------------- TestCase Methods
71  
72      public static Test suite() {
73          return new TestSuite(TestHttpParams.class);
74      }
75  
76      private class SimpleService implements HttpService {
77  
78          public SimpleService() {
79              super();
80          }
81  
82          public boolean process(final SimpleRequest request, final SimpleResponse response)
83              throws IOException
84          {
85              String uri = request.getRequestLine().getUri();  
86          	HttpVersion httpversion = request.getRequestLine().getHttpVersion();
87          	
88          	if ("/miss/".equals(uri)) {
89                  response.setStatusLine(httpversion, HttpStatus.SC_MOVED_TEMPORARILY);
90                  response.addHeader(new Header("Location", "/hit/"));
91                  response.setBodyString("Missed!");
92          	} else if ("/hit/".equals(uri)) {
93                  response.setStatusLine(httpversion, HttpStatus.SC_OK);
94                  response.setBodyString("Hit!");
95          	} else {
96                  response.setStatusLine(httpversion, HttpStatus.SC_NOT_FOUND);
97                  response.setBodyString(uri + " not found");
98          	}
99              return true;
100         }
101     }
102 
103     public void testDefaultHeaders() throws IOException {
104         this.server.setHttpService(new SimpleService());
105 
106         ArrayList defaults = new ArrayList();
107         defaults.add(new Header("this-header", "value1"));
108         defaults.add(new Header("that-header", "value1"));
109         defaults.add(new Header("that-header", "value2"));
110         defaults.add(new Header("User-Agent", "test"));
111 
112         HostConfiguration hostconfig = new HostConfiguration();
113         hostconfig.setHost(
114                 this.server.getLocalAddress(), 
115 	            this.server.getLocalPort(),
116 	            Protocol.getProtocol("http"));
117         hostconfig.getParams().setParameter(HostParams.DEFAULT_HEADERS, defaults);
118         
119         GetMethod httpget = new GetMethod("/miss/");
120         try {
121             this.client.executeMethod(hostconfig, httpget);
122         } finally {
123             httpget.releaseConnection();
124         }
125         assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
126         Header[] thisheader = httpget.getRequestHeaders("this-header");
127         assertEquals(1, thisheader.length);
128         Header[] thatheader = httpget.getRequestHeaders("that-header");
129         assertEquals(2, thatheader.length);
130         assertEquals("test", httpget.getRequestHeader("User-Agent").getValue());
131     }
132 
133     public void testDefaults() throws IOException {
134         this.server.setHttpService(new SimpleService());
135 
136         this.client.getParams().setParameter(HttpMethodParams.USER_AGENT, "test");
137         HostConfiguration hostconfig = new HostConfiguration();
138         hostconfig.setHost(
139                 this.server.getLocalAddress(), 
140                 this.server.getLocalPort(),
141                 Protocol.getProtocol("http"));
142         
143         GetMethod httpget = new GetMethod("/miss/");
144         try {
145             this.client.executeMethod(hostconfig, httpget);
146         } finally {
147             httpget.releaseConnection();
148         }
149         assertEquals(HttpStatus.SC_OK, httpget.getStatusCode());
150         assertEquals("test", httpget.getRequestHeader("User-Agent").getValue());
151         assertEquals("test", httpget.getParams().
152                 getParameter(HttpMethodParams.USER_AGENT));
153         assertEquals("test", hostconfig.getParams().
154                 getParameter(HttpMethodParams.USER_AGENT));
155         assertEquals("test", client.getParams().
156                 getParameter(HttpMethodParams.USER_AGENT));
157     }
158 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/params/TestParamsAll.html100644 0 0 12715 10661532627 27770 0ustar 0 0 TestParamsAll xref

1   /*
2    * $Header$
3    * $Revision: 515317 $
4    * $Date: 2007-03-06 22:41:04 +0100 (Tue, 06 Mar 2007) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   */
28  
29  package org.apache.commons.httpclient.params;
30  
31  import junit.framework.*;
32  
33  /**
34   * @author Oleg Kalnichevski 
35   * 
36   * @version $Id: TestParamsAll.java 515317 2007-03-06 21:41:04Z sebb $
37   */
38  public class TestParamsAll extends TestCase {
39  
40      public TestParamsAll(String testName) {
41          super(testName);
42      }
43  
44      public static Test suite() {
45          TestSuite suite = new TestSuite();
46          suite.addTest(TestHttpParams.suite());
47          suite.addTest(TestSSLTunnelParams.suite());
48          return suite;
49      }
50  
51      public static void main(String args[]) {
52          String[] testCaseName = { TestParamsAll.class.getName() };
53          junit.textui.TestRunner.main(testCaseName);
54      }
55  
56  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/params/TestSSLTunnelParams.html100644 0 0 43174 10661532627 31112 0ustar 0 0 TestSSLTunnelParams xref

1   /*
2    * $Header$
3    * $Revision: 515317 $
4    * $Date: 2007-03-06 22:41:04 +0100 (Tue, 06 Mar 2007) $
5    * ====================================================================
6    *
7    *  Licensed to the Apache Software Foundation (ASF) under one or more
8    *  contributor license agreements.  See the NOTICE file distributed with
9    *  this work for additional information regarding copyright ownership.
10   *  The ASF licenses this file to You under the Apache License, Version 2.0
11   *  (the "License"); you may not use this file except in compliance with
12   *  the License.  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.params;
31  
32  import java.io.IOException;
33  
34  import junit.framework.Test;
35  import junit.framework.TestSuite;
36  
37  import org.apache.commons.httpclient.FeedbackService;
38  import org.apache.commons.httpclient.Header;
39  import org.apache.commons.httpclient.HttpClientTestBase;
40  import org.apache.commons.httpclient.HttpStatus;
41  import org.apache.commons.httpclient.HttpVersion;
42  import org.apache.commons.httpclient.methods.GetMethod;
43  import org.apache.commons.httpclient.server.HttpRequestHandler;
44  import org.apache.commons.httpclient.server.SimpleHttpServerConnection;
45  import org.apache.commons.httpclient.server.SimpleRequest;
46  import org.apache.commons.httpclient.server.SimpleResponse;
47  
48  /**
49   * Tunnelling proxy configuration.
50   *
51   * @author Oleg Kalnichevski
52   * 
53   * @version $Id: TestSSLTunnelParams.java 515317 2007-03-06 21:41:04Z sebb $
54   */
55  public class TestSSLTunnelParams extends HttpClientTestBase {
56  
57      // ------------------------------------------------------------ Constructor
58      public TestSSLTunnelParams(final String testName) throws IOException {
59          super(testName);
60          setUseProxy(true);
61          setUseSSL(true);
62      }
63  
64      // ------------------------------------------------------------------- Main
65      public static void main(String args[]) {
66          String[] testCaseName = { TestSSLTunnelParams.class.getName() };
67          junit.textui.TestRunner.main(testCaseName);
68      }
69  
70      // ------------------------------------------------------- TestCase Methods
71  
72      public static Test suite() {
73          TestSuite suite = new TestSuite(TestSSLTunnelParams.class);
74          return suite;
75      }
76  
77      
78      static class HttpVersionHandler implements HttpRequestHandler {
79          
80          public HttpVersionHandler() {
81              super();
82          }
83  
84          public boolean processRequest(
85                  final SimpleHttpServerConnection conn,
86                  final SimpleRequest request) throws IOException
87              {
88                  HttpVersion ver = request.getRequestLine().getHttpVersion();
89                  if (ver.equals(HttpVersion.HTTP_1_0)) {
90                      return false;
91                  } else {
92                      SimpleResponse response = new SimpleResponse();
93                      response.setStatusLine(ver, HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED);
94                      response.addHeader(new Header("Proxy-Connection", "close"));
95                      conn.setKeepAlive(false);
96                      // Make sure the request body is fully consumed
97                      request.getBodyBytes();
98                      conn.writeResponse(response);
99                      return true;
100                 }
101             }
102         
103     }
104    
105     /**
106      * Tests correct proparation of HTTP params from the client to
107      * CONNECT method.
108      */
109     public void testTunnellingParamsAgentLevel() throws IOException {
110         this.proxy.addHandler(new HttpVersionHandler());
111         this.server.setHttpService(new FeedbackService());
112 
113         this.client.getParams().setVersion(HttpVersion.HTTP_1_1);
114         GetMethod httpget = new GetMethod("/test/");
115         try {
116             this.client.executeMethod(httpget);
117             assertNotNull(httpget.getStatusLine());
118             assertEquals(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED, 
119                     httpget.getStatusLine().getStatusCode());
120         } finally {
121             httpget.releaseConnection();
122         }
123 
124         this.client.getParams().setVersion(HttpVersion.HTTP_1_0);
125         httpget = new GetMethod("/test/");
126         try {
127             this.client.executeMethod(httpget);
128             assertNotNull(httpget.getStatusLine());
129             assertEquals(HttpStatus.SC_OK, 
130                     httpget.getStatusLine().getStatusCode());
131         } finally {
132             httpget.releaseConnection();
133         }
134     }
135 
136     /**
137      * Tests correct proparation of HTTP params from the host config to
138      * CONNECT method.
139      */
140     public void testTunnellingParamsHostLevel() throws IOException {
141         this.proxy.addHandler(new HttpVersionHandler());
142         this.server.setHttpService(new FeedbackService());
143 
144         this.client.getHostConfiguration().getParams().setParameter(
145                 HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
146         GetMethod httpget = new GetMethod("/test/");
147         try {
148             this.client.executeMethod(httpget);
149             assertNotNull(httpget.getStatusLine());
150             assertEquals(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED, 
151                     httpget.getStatusLine().getStatusCode());
152         } finally {
153             httpget.releaseConnection();
154         }
155 
156         this.client.getHostConfiguration().getParams().setParameter(
157                 HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
158         httpget = new GetMethod("/test/");
159         try {
160             this.client.executeMethod(httpget);
161             assertNotNull(httpget.getStatusLine());
162             assertEquals(HttpStatus.SC_OK, 
163                     httpget.getStatusLine().getStatusCode());
164         } finally {
165             httpget.releaseConnection();
166         }
167     }
168 
169     /**
170      * Tests ability to use HTTP/1.0 to execute CONNECT method and HTTP/1.1 to
171      * execute methods once the tunnel is established.
172      */
173     public void testTunnellingParamsHostHTTP10AndMethodHTTP11() throws IOException {
174         this.proxy.addHandler(new HttpVersionHandler());
175         this.server.setHttpService(new FeedbackService());
176 
177         this.client.getHostConfiguration().getParams().setParameter(
178                 HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
179         GetMethod httpget = new GetMethod("/test/");
180         httpget.getParams().setVersion(HttpVersion.HTTP_1_1);
181         try {
182             this.client.executeMethod(httpget);
183             assertNotNull(httpget.getStatusLine());
184             assertEquals(HttpStatus.SC_OK, 
185                     httpget.getStatusLine().getStatusCode());
186             assertEquals(HttpVersion.HTTP_1_1, 
187                     httpget.getEffectiveVersion());
188         } finally {
189             httpget.releaseConnection();
190         }
191     }
192 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/params/package-frame.html100644 0 0 1743 10661532631 27711 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.params

org.apache.commons.httpclient.params

Classes

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/params/package-summary.html100644 0 0 4457 10661532631 30321 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.params

Package org.apache.commons.httpclient.params

Class Summary
TestHttpParams
TestParamsAll
TestSSLTunnelParams

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/AuthRequestHandler.html100644 0 0 33531 10661532627 31046 0ustar 0 0 AuthRequestHandler xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/AuthRequestHandler.java,v 1.1 2004/11/20 17:56:40 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  
35  import org.apache.commons.httpclient.Credentials;
36  import org.apache.commons.httpclient.Header;
37  import org.apache.commons.httpclient.HttpStatus;
38  import org.apache.commons.httpclient.UsernamePasswordCredentials;
39  import org.apache.commons.httpclient.auth.BasicScheme;
40  
41  /**
42   * This request handler guards access to the http server when used in a request handler
43   * chain. It checks the headers for valid credentials and performs the
44   * authentication handshake if necessary.
45   * 
46   * @author Ortwin Glueck
47   * @author Oleg Kalnichevski
48   */
49  public class AuthRequestHandler implements HttpRequestHandler {
50      
51      private Credentials credentials = null;
52      private String realm = null;
53      private boolean keepalive = true;
54  
55      /**
56       * The authenticate response header.
57       */
58      public static final String AUTH_RESP = "Authorization";
59  
60      /**
61       * TODO replace creds parameter with a class specific to an auth scheme
62       * encapsulating all required information for a specific scheme
63       * 
64       * @param creds
65       */
66      public AuthRequestHandler(final Credentials creds, final String realm, boolean keepalive) {
67          if (creds == null)
68              throw new IllegalArgumentException("Credentials may not be null");
69          this.credentials = creds;
70          this.keepalive = keepalive;
71          if (realm != null) {
72              this.realm = realm;
73          } else {
74              this.realm = "test";
75          }
76      }
77  
78      public AuthRequestHandler(final Credentials creds, final String realm) {
79          this(creds, realm, true);
80      }
81      
82      public AuthRequestHandler(final Credentials creds) {
83          this(creds, null, true);
84      }
85      
86      public boolean processRequest(
87          final SimpleHttpServerConnection conn,
88          final SimpleRequest request) throws IOException
89      {
90          Header clientAuth = request.getFirstHeader(AUTH_RESP);
91          if (clientAuth != null && checkAuthorization(clientAuth)) {
92              return false;
93          } else {
94              SimpleResponse response = performBasicHandshake(conn, request);
95              // Make sure the request body is fully consumed
96              request.getBodyBytes();
97              conn.writeResponse(response);
98              return true;
99          }
100     }
101 
102     //TODO add more auth schemes
103     private SimpleResponse performBasicHandshake(
104             final SimpleHttpServerConnection conn,
105             final SimpleRequest request) throws IOException 
106     { 
107         SimpleResponse response = new SimpleResponse();
108         response.setStatusLine(
109                 request.getRequestLine().getHttpVersion(),
110                 HttpStatus.SC_UNAUTHORIZED);
111         if (!request.getRequestLine().getMethod().equalsIgnoreCase("HEAD")) {
112             response.setBodyString("unauthorized");
113         }
114         response.addHeader(new Header("WWW-Authenticate", "basic realm=\"" + this.realm + "\""));
115         if (this.keepalive) {
116             response.addHeader(new Header("Connection", "keep-alive"));
117             conn.setKeepAlive(true);
118         } else {
119             response.addHeader(new Header("Connection", "close"));
120             conn.setKeepAlive(false);
121         }
122         return response;
123     }
124 
125     /**
126      * Checks if the credentials provided by the client match the required
127      * credentials
128      * 
129      * @return true if the client is authorized, false if not.
130      * @param clientAuth
131      */
132     private boolean checkAuthorization(final Header clientAuth) {
133         String expectedAuthString = BasicScheme.authenticate(
134             (UsernamePasswordCredentials)credentials,
135             "ISO-8859-1");
136         return expectedAuthString.equals(clientAuth.getValue());
137     }
138 
139 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/ErrorResponse.html100644 0 0 17051 10661532627 30105 0ustar 0 0 ErrorResponse xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/ErrorResponse.java,v 1.6 2004/11/13 12:21:28 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32  
33  package org.apache.commons.httpclient.server;
34  
35  import java.util.HashMap;
36  
37  import org.apache.commons.httpclient.Header;
38  import org.apache.commons.httpclient.HttpStatus;
39  import org.apache.commons.httpclient.HttpVersion;
40  
41  /**
42   * Default error responses.
43   * 
44   * @author Christian Kohlschuetter
45   */
46  public class ErrorResponse {
47      
48      private static final HashMap responses = new HashMap();
49      
50      private ErrorResponse() {
51          super();
52      }
53      
54      public static SimpleResponse getResponse(int statusCode) {
55          Integer code = new Integer(statusCode);
56          SimpleResponse response = (SimpleResponse)responses.get(code);
57          if (response == null) {
58              response = new SimpleResponse();
59              response.setStatusLine(HttpVersion.HTTP_1_0, statusCode);
60              response.setHeader(new Header("Content-Type", "text/plain; charset=US-ASCII"));
61  
62              String s = HttpStatus.getStatusText(statusCode);
63              if (s == null) {
64                  s = "Error " + statusCode;
65              }
66              response.setBodyString(s);
67              response.addHeader(new Header("Connection", "close"));
68              response.addHeader(new Header("Content-Lenght", Integer.toString(s.length())));
69              responses.put(code, response);
70          }
71          return response;
72      }
73  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/HttpRequestHandler.html100644 0 0 15471 10661532627 31067 0ustar 0 0 HttpRequestHandler xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/HttpRequestHandler.java,v 1.4 2004/02/27 19:01:33 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32  
33  package org.apache.commons.httpclient.server;
34  
35  import java.io.IOException;
36  
37  /**
38   * Defines an HTTP request handler for the SimpleHttpServer
39   * 
40   * @author Christian Kohlschuetter
41   * @author Oleg Kalnichevski
42   */
43  public interface HttpRequestHandler {
44      /**
45       * The request handler is asked to process this request.
46       * 
47       * If it is not capable/interested in processing it, this call should
48       * be simply ignored.
49       * 
50       * Any modification of the output stream (via <code>conn.getWriter()</code>)
51       * by this request handler will stop the execution chain and return the output
52       * to the client.
53       * 
54       * The handler may also rewrite the request parameters (this is useful in
55       * {@link HttpRequestHandlerChain} structures).
56       * 
57       * @param conn          The Connection object to which this request belongs to.
58       * @param request       The request object.
59       * @return true if this handler handled the request and no other handlers in the 
60       * chain should be called, false otherwise.
61       * @throws IOException
62       */
63      public boolean processRequest(
64          final SimpleHttpServerConnection conn,
65          final SimpleRequest request) throws IOException;
66  }

././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/HttpRequestHandlerChain.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/HttpRequestHandlerChain.h100644 0 0 22152 10661532627 31307 0ustar 0 0 HttpRequestHandlerChain xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/HttpRequestHandlerChain.java,v 1.6 2004/11/28 15:44:39 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32  
33  package org.apache.commons.httpclient.server;
34  
35  import java.io.IOException;
36  import java.util.ArrayList;
37  import java.util.Iterator;
38  import java.util.List;
39  
40  /**
41   * Maintains a chain of {@link HttpRequestHandler}s where new request-handlers
42   * can be prepended/appended.
43   * 
44   * For each call to {@link #processRequest(ResponseWriter,SimpleHttpServerConnection,RequestLine,Header[])}
45   * we iterate over the chain from the start to the end, stopping as soon as a handler
46   * has claimed the output.
47   * 
48   * @author Christian Kohlschuetter
49   */
50  public class HttpRequestHandlerChain implements HttpRequestHandler {
51      
52      private List subhandlers = new ArrayList();
53      
54      public HttpRequestHandlerChain(final HttpRequestHandlerChain chain) {
55          super();
56          if (chain != null) {
57              this.subhandlers.clear();
58              this.subhandlers.addAll(chain.subhandlers);
59          }
60      }
61      
62      public HttpRequestHandlerChain() {
63          super();
64      }
65      
66      public synchronized void clear() {
67          subhandlers.clear();
68      }
69      
70      public synchronized void prependHandler(HttpRequestHandler handler) {
71          subhandlers.add(0,handler);
72      }
73      
74      public synchronized void appendHandler(HttpRequestHandler handler) {
75          subhandlers.add(handler);
76      }
77  
78      public synchronized boolean processRequest(
79          final SimpleHttpServerConnection conn,
80          final SimpleRequest request) throws IOException 
81      {
82          for(Iterator it=subhandlers.iterator();it.hasNext();) {
83              HttpRequestHandler h = (HttpRequestHandler)it.next();
84              boolean stop = h.processRequest(conn, request);
85              if (stop) {
86                  return true;
87              }
88          }
89          return false;
90      }
91  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/HttpService.html100644 0 0 13461 10661532627 27536 0ustar 0 0 HttpService xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/HttpService.java,v 1.1 2004/02/27 19:04:32 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32  
33  package org.apache.commons.httpclient.server;
34  
35  import java.io.IOException;
36  
37  /**
38   * Defines an HTTP request/response service for the SimpleHttpServer
39   * 
40   * @author Oleg Kalnichevski
41   */
42  public interface HttpService {
43      /**
44       * This interface represents a serice to process HTTP requests.
45       * 
46       * @param request       The HTTP request object.
47       * @param response      The HTTP response object.
48       * @return true if this service was able to handle the request, false otherwise.
49       * 
50       * @throws IOException
51       */
52      public boolean process(
53          final SimpleRequest request, final SimpleResponse response) 
54              throws IOException;
55  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/HttpServiceHandler.html100644 0 0 32702 10661532627 31033 0ustar 0 0 HttpServiceHandler xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/HttpServiceHandler.java,v 1.9 2004/11/13 22:38:27 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  
36  import org.apache.commons.httpclient.Header;
37  import org.apache.commons.httpclient.HttpVersion;
38  
39  /**
40   * This request handler provides service interface similar to that of Servlet API.
41   * 
42   * @author Oleg Kalnichevski
43   */
44  public class HttpServiceHandler implements HttpRequestHandler {
45  
46      private HttpService service = null;
47      
48      public HttpServiceHandler(final HttpService service) {
49          super();
50          if (service == null) {
51              throw new IllegalArgumentException("Service may not be null");
52          }
53          this.service = service;
54      }
55      
56      public boolean processRequest(
57          final SimpleHttpServerConnection conn,
58          final SimpleRequest request) throws IOException {
59          if (conn == null) {
60              throw new IllegalArgumentException("Connection may not be null");
61          }
62          if (request == null) {
63              throw new IllegalArgumentException("Request may not be null");
64          }
65          boolean complete = false;
66          SimpleResponse response = new SimpleResponse();
67          this.service.process(request, response);
68          
69          // Nake sure the request if fully consumed
70          request.getBodyBytes();
71          
72          // Ensure there's a content type header
73          if (!response.containsHeader("Content-Type")) {
74              response.addHeader(new Header("Content-Type", "text/plain"));
75          }
76          
77          // Ensure there's a content length or transfer encoding header
78          if (!response.containsHeader("Content-Length") && !response.containsHeader("Transfer-Encoding")) {
79              InputStream content = response.getBody();
80              if (content != null) {
81                  long len = response.getContentLength();
82                  if (len < 0) {
83                      if (response.getHttpVersion().lessEquals(HttpVersion.HTTP_1_0)) {
84                          throw new IOException("Chunked encoding not supported for HTTP version " 
85                                  + response.getHttpVersion());
86                      }
87                      Header header = new Header("Transfer-Encoding", "chunked"); 
88                      response.addHeader(header);                
89                  } else {
90                      Header header = new Header("Content-Length", Long.toString(len)); 
91                      response.setHeader(header);
92                  }
93              } else {
94                  Header header = new Header("Content-Length", "0"); 
95                  response.addHeader(header);
96              }
97          }
98  
99          if (!response.containsHeader("Connection")) {
100             // See if the the client explicitly handles connection persistence
101             Header connheader = request.getFirstHeader("Connection");
102             if (connheader != null) {
103                 if (connheader.getValue().equalsIgnoreCase("keep-alive")) {
104                     Header header = new Header("Connection", "keep-alive"); 
105                     response.addHeader(header);
106                     conn.setKeepAlive(true);
107                 }
108                 if (connheader.getValue().equalsIgnoreCase("close")) {
109                     Header header = new Header("Connection", "close"); 
110                     response.addHeader(header);
111                     conn.setKeepAlive(false);
112                 }
113             } else {
114                 // Use protocol default connection policy
115                 if (response.getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
116                     conn.setKeepAlive(true);
117                 } else {
118                     conn.setKeepAlive(false);
119                 }
120             }
121         }
122         if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
123             // this is a head request, we don't want to send the actualy content
124             response.setBody(null);
125         }
126         conn.writeResponse(response);
127         return true;
128     }
129     
130 }

././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/ProxyAuthRequestHandler.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/ProxyAuthRequestHandler.h100644 0 0 33606 10661532627 31376 0ustar 0 0 ProxyAuthRequestHandler xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/ProxyAuthRequestHandler.java,v 1.12 2004/11/28 15:44:39 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  
35  import org.apache.commons.httpclient.Credentials;
36  import org.apache.commons.httpclient.Header;
37  import org.apache.commons.httpclient.HttpStatus;
38  import org.apache.commons.httpclient.UsernamePasswordCredentials;
39  import org.apache.commons.httpclient.auth.BasicScheme;
40  
41  /**
42   * This request handler guards access to a proxy when used in a request handler
43   * chain. It checks the headers for valid credentials and performs the
44   * authentication handshake if necessary.
45   * 
46   * @author Ortwin Glueck
47   * @author Oleg Kalnichevski
48   */
49  public class ProxyAuthRequestHandler implements HttpRequestHandler {
50  
51      private Credentials credentials = null;
52      private String realm = null;
53      private boolean keepalive = true;
54  
55      /**
56       * The proxy authenticate response header.
57       */
58      public static final String PROXY_AUTH_RESP = "Proxy-Authorization";
59  
60      /**
61       * TODO replace creds parameter with a class specific to an auth scheme
62       * encapsulating all required information for a specific scheme
63       * 
64       * @param creds
65       */
66      public ProxyAuthRequestHandler(final Credentials creds, final String realm, boolean keepalive) {
67          if (creds == null)
68              throw new IllegalArgumentException("Credentials may not be null");
69          this.credentials = creds;
70          this.keepalive = keepalive;
71          if (realm != null) {
72              this.realm = realm;
73          } else {
74              this.realm = "test";
75          }
76      }
77  
78      public ProxyAuthRequestHandler(final Credentials creds, final String realm) {
79          this(creds, realm, true);
80      }
81      
82      public ProxyAuthRequestHandler(final Credentials creds) {
83          this(creds, null, true);
84      }
85  
86      public boolean processRequest(
87          final SimpleHttpServerConnection conn,
88          final SimpleRequest request) throws IOException
89      {
90          Header clientAuth = request.getFirstHeader(PROXY_AUTH_RESP);
91          if (clientAuth != null && checkAuthorization(clientAuth)) {
92              return false;
93          } else {
94              SimpleResponse response = performBasicHandshake(conn, request);
95              // Make sure the request body is fully consumed
96              request.getBodyBytes();
97              conn.writeResponse(response);
98              return true;
99          }
100     }
101 
102     //TODO add more auth schemes
103     private SimpleResponse performBasicHandshake(
104             final SimpleHttpServerConnection conn, 
105             final SimpleRequest request) { 
106 
107         SimpleResponse response = new SimpleResponse();
108         response.setStatusLine(
109                 request.getRequestLine().getHttpVersion(),
110                 HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED);
111         if (!request.getRequestLine().getMethod().equalsIgnoreCase("HEAD")) {
112             response.setBodyString("unauthorized");
113         }
114         response.addHeader(new Header("Proxy-Authenticate", "basic realm=\"" + this.realm + "\""));
115         if (this.keepalive) {
116             response.addHeader(new Header("Proxy-Connection", "keep-alive"));
117             conn.setKeepAlive(true);
118         } else {
119             response.addHeader(new Header("Proxy-Connection", "close"));
120             conn.setKeepAlive(false);
121         }
122         return response;
123     }
124 
125     /**
126      * Checks if the credentials provided by the client match the required
127      * credentials
128      * 
129      * @return true if the client is authorized, false if not.
130      * @param clientAuth
131      */
132     private boolean checkAuthorization(Header clientAuth) {
133         String expectedAuthString = BasicScheme.authenticate(
134             (UsernamePasswordCredentials)credentials,
135             "ISO-8859-1");
136         return expectedAuthString.equals(clientAuth.getValue());
137     }
138 
139 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/ProxyRequestHandler.html100644 0 0 41742 10661532627 31271 0ustar 0 0 ProxyRequestHandler xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/ProxyRequestHandler.java,v 1.11 2004/12/11 22:35:26 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  import java.net.UnknownHostException;
35  
36  import org.apache.commons.httpclient.Header;
37  import org.apache.commons.httpclient.HttpException;
38  import org.apache.commons.httpclient.HttpStatus;
39  import org.apache.commons.httpclient.HttpVersion;
40  import org.apache.commons.httpclient.URI;
41  import org.apache.commons.httpclient.URIException;
42  import org.apache.commons.logging.Log;
43  import org.apache.commons.logging.LogFactory;
44  
45  /**
46   * @author Ortwin Glueck
47   * @author Oleg Kalnichevski
48   */
49  public class ProxyRequestHandler implements HttpRequestHandler {
50  
51      private static final Log LOG = LogFactory.getLog(ProxyRequestHandler.class);
52  
53      private SimpleConnManager connmanager = null;
54      
55      public ProxyRequestHandler(final SimpleConnManager connmanager) {
56          super();
57          if (connmanager == null) {
58              throw new IllegalArgumentException("Connection manager may not be null");
59          }
60          this.connmanager = connmanager;
61      }
62      
63  	/**
64  	 * @see org.apache.commons.httpclient.server.HttpRequestHandler#processRequest(org.apache.commons.httpclient.server.SimpleHttpServerConnection)
65  	 */
66  	public boolean processRequest(
67          final SimpleHttpServerConnection conn,
68          final SimpleRequest request) throws IOException
69      {
70          httpProxy(conn, request);
71          return true;
72  	}
73  
74  	private void httpProxy(
75          final SimpleHttpServerConnection conn,
76          final SimpleRequest request) throws IOException {
77  
78          RequestLine oldreqline = request.getRequestLine();
79          URI uri = null;
80          SimpleHost host = null;
81          try {
82              uri = new URI(oldreqline.getUri(), true);
83              host = new SimpleHost(uri.getHost(), uri.getPort());
84          } catch (URIException ex) {
85              SimpleResponse response = ErrorResponse.getResponse(HttpStatus.SC_BAD_REQUEST);
86              conn.writeResponse(response);
87              return;
88          }
89          SimpleHttpServerConnection proxyconn = null;
90          try {
91              proxyconn = this.connmanager.openConnection(host);
92          } catch (UnknownHostException e) {
93              SimpleResponse response = ErrorResponse.getResponse(HttpStatus.SC_NOT_FOUND);
94              conn.writeResponse(response);
95              return;
96          }
97          try {
98              proxyconn.setSocketTimeout(0);
99              // Rewrite target url
100             RequestLine newreqline = new RequestLine(
101                     oldreqline.getMethod(), 
102                     uri.getEscapedPath(), 
103                     oldreqline.getHttpVersion()); 
104             request.setRequestLine(newreqline);
105             // Remove proxy-auth headers if present
106             request.removeHeaders("Proxy-Authorization");
107             // Manage connection persistence
108             Header connheader = request.getFirstHeader("Proxy-Connection");
109             if (connheader != null) {
110                 if (connheader.getValue().equalsIgnoreCase("close")) {
111                     request.setHeader(new Header("Connection", "close"));
112                 }
113             }
114             request.removeHeaders("Proxy-Connection");
115             
116             proxyconn.writeRequest(request);
117             
118             SimpleResponse response = proxyconn.readResponse();
119             if (response == null) {
120                 return;
121             }
122             response.setHeader(new Header("Via", "1.1 test (Test-Proxy)"));
123             connheader = response.getFirstHeader("Connection");
124             if (connheader != null) {
125                 String s = connheader.getValue(); 
126                 if (s.equalsIgnoreCase("close")) {
127                     response.setHeader(new Header("Proxy-Connection", "close"));
128                     conn.setKeepAlive(false);
129                     proxyconn.setKeepAlive(false);
130                     response.removeHeaders("Connection");
131                 }
132                 if (s.equalsIgnoreCase("keep-alive")) {
133                     response.setHeader(new Header("Proxy-Connection", "keep-alive"));
134                     conn.setKeepAlive(true);
135                     proxyconn.setKeepAlive(true);
136                     response.removeHeaders("Connection");
137                 }
138             } else {
139                 // Use protocol default connection policy
140                 if (response.getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
141                     conn.setKeepAlive(true);
142                     proxyconn.setKeepAlive(true);
143                 } else {
144                     conn.setKeepAlive(false);
145                     proxyconn.setKeepAlive(false);
146                 }
147             }
148             if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
149                 // this is a head request, we don't want to send the actualy content
150                 response.setBody(null);
151             }
152             conn.writeResponse(response);
153 
154         } catch (HttpException e) {
155             SimpleResponse response = ErrorResponse.getResponse(HttpStatus.SC_BAD_REQUEST);
156             conn.writeResponse(response);
157             proxyconn.setKeepAlive(false);
158         } catch (IOException e) {
159             LOG.warn(e.getMessage());
160             proxyconn.setKeepAlive(false);
161         } finally {
162             this.connmanager.releaseConnection(host, proxyconn);
163         }
164 	}
165     
166 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/RequestLine.html100644 0 0 25040 10661532627 27532 0ustar 0 0 RequestLine xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/RequestLine.java,v 1.4 2004/09/14 15:50:41 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32  
33  package org.apache.commons.httpclient.server;
34  
35  import java.util.NoSuchElementException;
36  import java.util.StringTokenizer;
37  
38  import org.apache.commons.httpclient.HttpException;
39  import org.apache.commons.httpclient.HttpVersion;
40  import org.apache.commons.httpclient.ProtocolException;
41  
42  /**
43   * Defines a HTTP request-line, consisting of method name, URI and protocol.
44   * Instances of this class are immutable.
45   * 
46   * @author Christian Kohlschuetter
47   * @author Oleg Kalnichevski
48   */
49  public class RequestLine {
50  
51      private HttpVersion httpversion = null;
52      private String method = null;
53      private String uri= null;
54  
55      public static RequestLine parseLine(final String l) 
56      throws HttpException {
57          String method = null;
58          String uri = null;
59          String protocol = null;
60          try {
61              StringTokenizer st = new StringTokenizer(l, " ");
62              method = st.nextToken();
63              uri = st.nextToken();
64              protocol = st.nextToken();
65          } catch (NoSuchElementException e) {
66          	throw new ProtocolException("Invalid request line: " + l);
67          }
68          return new RequestLine(method, uri, protocol);
69      }
70      
71      public RequestLine(final String method, final String uri, final HttpVersion httpversion) {
72      	super();
73      	if (method == null) {
74      		throw new IllegalArgumentException("Method may not be null");
75      	}
76      	if (uri == null) {
77      		throw new IllegalArgumentException("URI may not be null");
78      	}
79      	if (httpversion == null) {
80      		throw new IllegalArgumentException("HTTP version may not be null");
81      	}
82      	this.method = method;
83          this.uri = uri;
84          this.httpversion = httpversion;
85      }
86  
87      public RequestLine(final String method, final String uri, final String httpversion)
88      throws ProtocolException {
89      	this(method, uri, HttpVersion.parse(httpversion));
90      }
91  
92      public String getMethod() {
93          return this.method;
94      }
95  
96      public HttpVersion getHttpVersion() {
97          return this.httpversion;
98      }
99  
100     public String getUri() {
101         return this.uri;
102     }
103 
104     public String toString() {
105         StringBuffer sb = new StringBuffer();
106         sb.append(this.method);
107         sb.append(" ");
108         sb.append(this.uri);
109         sb.append(" ");
110         sb.append(this.httpversion);
111         return sb.toString();
112     }
113 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/ResponseWriter.html100644 0 0 26564 10661532627 30301 0ustar 0 0 ResponseWriter xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/ResponseWriter.java,v 1.5 2004/11/07 12:31:42 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.BufferedWriter;
34  import java.io.FilterWriter;
35  import java.io.IOException;
36  import java.io.OutputStream;
37  import java.io.OutputStreamWriter;
38  import java.io.UnsupportedEncodingException;
39  
40  /**
41   * Provides a hybrid Writer/OutputStream for sending HTTP response data
42   * 
43   * @author Christian Kohlschuetter
44   */
45  public class ResponseWriter extends FilterWriter {
46      public static final String CRLF = "\r\n";
47      public static final String ISO_8859_1 = "ISO-8859-1";
48      private OutputStream outStream = null;
49      private String encoding = null;
50  
51      public ResponseWriter(final OutputStream outStream) 
52      throws UnsupportedEncodingException {
53          this(outStream, CRLF, ISO_8859_1);
54      }
55      
56      public ResponseWriter(final OutputStream outStream, final String encoding) 
57      throws UnsupportedEncodingException {
58          this(outStream, CRLF, encoding);
59      }
60      
61      public ResponseWriter(
62              final OutputStream outStream, 
63              final String lineSeparator, 
64              final String encoding) throws UnsupportedEncodingException {
65          super(new BufferedWriter(new OutputStreamWriter(outStream, encoding)));
66          this.outStream = outStream;
67          this.encoding = encoding;
68      }
69      
70      public String getEncoding() {
71          return encoding;
72      }
73      
74      public void close() throws IOException {
75          if(outStream != null) {
76              super.close();
77              outStream = null;
78          }
79      }
80  
81      /* (non-Javadoc)
82       * @see java.io.Writer#flush()
83       */
84      public void flush() throws IOException {
85          if(outStream != null) {
86              super.flush();
87              outStream.flush();
88          }
89      }
90  
91      public void write(byte b) throws IOException {
92          super.flush();
93          outStream.write((int)b);
94      }
95      
96      public void write(byte[] b) throws IOException {
97          super.flush();
98          outStream.write(b);
99      }
100     
101     public void write(byte[] b, int off, int len) throws IOException {
102         super.flush();
103         outStream.write(b,off,len);
104     }
105 
106     public void print(String s) throws IOException {
107         if (s == null) {
108             s = "null";
109         }
110         write(s);
111     }
112     
113     public void print(int i) throws IOException {
114         write(Integer.toString(i));
115     }
116     
117     public void println(int i) throws IOException {
118         write(Integer.toString(i));
119         write(CRLF);
120     }
121 
122     public void println(String s) throws IOException {
123         print(s);
124         write(CRLF);
125     }
126     
127     public void println() throws IOException {
128         write(CRLF);
129     }
130     
131 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleConnList.html100644 0 0 20427 10661532627 30201 0ustar 0 0 SimpleConnList xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnList.java,v 1.1 2004/11/13 12:21:28 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.util.ArrayList;
34  import java.util.Iterator;
35  import java.util.List;
36  
37  /**
38   * A simple list of connections.
39   * 
40   * @author Oleg Kalnichevski
41   */
42  public class SimpleConnList {
43      
44      private List connections = new ArrayList();
45      
46      public SimpleConnList() {
47          super();
48      }
49  
50      public synchronized void addConnection(final SimpleHttpServerConnection conn) {
51          this.connections.add(conn);
52      }
53      
54      public synchronized void removeConnection(final SimpleHttpServerConnection conn) {
55          this.connections.remove(conn);
56      }
57  
58      public synchronized SimpleHttpServerConnection removeLast() {
59          int s = this.connections.size(); 
60          if (s > 0) {
61              return (SimpleHttpServerConnection)this.connections.remove(s - 1);
62          } else {
63              return null;
64          }
65      }
66  
67      public synchronized SimpleHttpServerConnection removeFirst() {
68          int s = this.connections.size(); 
69          if (s > 0) {
70              return (SimpleHttpServerConnection)this.connections.remove(0);
71          } else {
72              return null;
73          }
74      }
75  
76      public synchronized void shutdown() {
77          for (Iterator i = this.connections.iterator(); i.hasNext();) {
78              SimpleHttpServerConnection conn = (SimpleHttpServerConnection) i.next();
79              conn.close();
80          }
81          this.connections.clear();
82      }
83  
84  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleConnManager.html100644 0 0 24166 10661532627 30644 0ustar 0 0 SimpleConnManager xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnManager.java,v 1.2 2004/11/20 17:56:40 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  import java.net.Socket;
35  import java.util.HashMap;
36  import java.util.Iterator;
37  import java.util.Map;
38  
39  /**
40   * A REALLY simple connection manager.
41   * 
42   * @author Oleg Kalnichevski
43   */
44  public class SimpleConnManager {
45      
46      private Map connsets = new HashMap();
47      
48      public SimpleConnManager() {
49          super();
50      }
51  
52      public synchronized SimpleHttpServerConnection openConnection(final SimpleHost host)
53          throws IOException {
54          if (host == null) {
55              throw new IllegalArgumentException("Host may not be null");
56          }
57          SimpleHttpServerConnection conn = null;
58          SimpleConnList connlist = (SimpleConnList)this.connsets.get(host);
59          if (connlist != null) {
60              conn = connlist.removeFirst();
61              if (conn != null && !conn.isOpen()) {
62                  conn = null;
63              }
64          }
65          if (conn == null) {
66              Socket socket = new Socket(host.getHostName(), host.getPort());
67              conn = new SimpleHttpServerConnection(socket);
68          }
69          return conn;
70      }
71      
72      public synchronized void releaseConnection(final SimpleHost host, 
73              final SimpleHttpServerConnection conn) throws IOException {
74          if (host == null) {
75              throw new IllegalArgumentException("Host may not be null");
76          }
77          if (conn == null) {
78              return;
79          }
80          if (!conn.isKeepAlive()) {
81              conn.close();
82          }
83          if (conn.isOpen()) {
84              SimpleConnList connlist = (SimpleConnList)this.connsets.get(host);
85              if (connlist == null) {
86                  connlist = new SimpleConnList();
87                  this.connsets.put(host, connlist);
88              }
89              connlist.addConnection(conn);
90          }
91      }
92  
93      public synchronized void shutdown() {
94          for (Iterator i = this.connsets.values().iterator(); i.hasNext();) {
95              SimpleConnList connlist = (SimpleConnList) i.next();
96              connlist.shutdown();
97          }
98          this.connsets.clear();
99      }
100 
101 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleConnSet.html100644 0 0 15066 10661532627 30024 0ustar 0 0 SimpleConnSet xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnSet.java,v 1.1 2004/11/13 12:21:28 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.util.HashSet;
34  import java.util.Iterator;
35  import java.util.Set;
36  
37  /**
38   * A simple set of connections.
39   * 
40   * @author Oleg Kalnichevski
41   */
42  public class SimpleConnSet {
43      
44      private Set connections = new HashSet();
45      
46      public SimpleConnSet() {
47          super();
48      }
49  
50      public synchronized void addConnection(final SimpleHttpServerConnection conn) {
51          this.connections.add(conn);
52      }
53      
54      public synchronized void removeConnection(final SimpleHttpServerConnection conn) {
55          this.connections.remove(conn);
56      }
57  
58      public synchronized void shutdown() {
59          for (Iterator i = connections.iterator(); i.hasNext();) {
60              SimpleHttpServerConnection conn = (SimpleHttpServerConnection) i.next();
61              conn.close();
62          }
63      }
64  
65  }

././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleConnectionThread.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleConnectionThread.ht100644 0 0 26041 10661532627 31344 0ustar 0 0 SimpleConnectionThread xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnectionThread.java,v 1.3 2004/11/13 22:38:27 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  import java.io.InterruptedIOException;
35  
36  import org.apache.commons.logging.Log;
37  import org.apache.commons.logging.LogFactory;
38  
39  /**
40   * Simple HTTP connection thread.
41   * 
42   * @author Christian Kohlschuetter
43   * @author Oleg Kalnichevski
44   */
45  public class SimpleConnectionThread extends Thread {
46  
47      private static final Log LOG = LogFactory.getLog(SimpleConnectionThread.class);
48      
49      public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1";
50  
51      private SimpleHttpServerConnection conn = null;
52      private SimpleConnSet connpool = null;    
53      private HttpRequestHandler handler = null;
54      transient boolean stopped; 
55  
56      public SimpleConnectionThread(
57              final ThreadGroup tg,
58              final String name,
59              final SimpleHttpServerConnection conn,
60              final SimpleConnSet connpool,
61              final HttpRequestHandler handler) 
62      throws IOException {
63          super(tg, name);
64          if (conn == null) {
65              throw new IllegalArgumentException("Connection may not be null");
66          }
67          if (connpool == null) {
68              throw new IllegalArgumentException("Connection pool not be null");
69          }
70          if (handler == null) {
71              throw new IllegalArgumentException("Request handler may not be null");
72          }
73          this.conn = conn;
74          this.connpool = connpool;
75          this.handler = handler;
76          this.stopped = false; 
77      }
78  
79      public synchronized void destroy() {
80          if (this.stopped) {
81              return;
82          }
83          this.stopped = true; 
84          if (conn != null) {
85              conn.close();
86              conn = null;
87          }
88          interrupt();
89      }
90  
91      public void run() {
92          try {
93              do {
94                  this.conn.setKeepAlive(false);
95                  SimpleRequest request = this.conn.readRequest();
96                  if (request != null) {
97                      this.handler.processRequest(this.conn, request);
98                  }
99              } while (this.conn.isKeepAlive());
100         } catch (InterruptedIOException e) {
101         } catch (IOException e) {
102             if (!this.stopped && !isInterrupted() && LOG.isWarnEnabled()) {
103                 LOG.warn("[" + getName() + "] I/O error: " + e.getMessage());
104             }
105         } finally {
106             destroy();
107             this.connpool.removeConnection(this.conn);
108         }
109     }
110 
111 }
112     

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleHost.html100644 0 0 23312 10661532627 27361 0ustar 0 0 SimpleHost xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleHost.java,v 1.1 2004/11/13 12:21:28 olegk Exp $
3    * $Revision: 510582 $
4    * $Date: 2007-02-22 17:42:43 +0100 (Thu, 22 Feb 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  /**
34   * @author Oleg Kalnichevski
35   */
36  public class SimpleHost implements Cloneable {
37  
38      private String hostname = null;
39  
40      private int port = -1;
41  
42      public SimpleHost(final String hostname, int port) {
43          super();
44          if (hostname == null) {
45              throw new IllegalArgumentException("Host name may not be null");
46          }
47          if (port < 0) {
48              throw new IllegalArgumentException("Port may not be negative");
49          }
50          this.hostname = hostname;
51          this.port = port;
52      }
53  
54      public SimpleHost (final SimpleHost httphost) {
55          super();
56          init(httphost);
57      }
58  
59  	private void init(final SimpleHost httphost) {
60  		this.hostname = httphost.hostname;
61          this.port = httphost.port;
62  	}
63  
64      public Object clone() throws CloneNotSupportedException {
65      	SimpleHost copy = (SimpleHost) super.clone();
66      	copy.init(this);
67          return copy;
68      }    
69      
70      public String getHostName() {
71          return this.hostname;
72      }
73  
74      public int getPort() {
75          return this.port;
76      }
77  
78      public String toString() {
79          StringBuffer buffer = new StringBuffer(50);        
80          buffer.append(this.hostname);
81          buffer.append(':');
82          buffer.append(this.port);
83          return buffer.toString();
84      }    
85      
86      public boolean equals(final Object o) {
87          
88          if (o instanceof SimpleHost) {
89              if (o == this) { 
90                  return true;
91              }
92              SimpleHost that = (SimpleHost) o;
93              if (!this.hostname.equalsIgnoreCase(that.hostname)) {
94                  return false;
95              }
96              if (this.port != that.port) {
97                  return false;
98              }
99              return true;
100         } else {
101             return false;
102         }
103     }
104 
105     public int hashCode() {
106         return this.hostname.hashCode() + this.port;
107     }
108 
109 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleHttpServer.html100644 0 0 47763 10661532627 30572 0ustar 0 0 SimpleHttpServer xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleHttpServer.java,v 1.15 2004/12/11 22:35:26 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  import java.net.InetAddress;
35  import java.net.ServerSocket;
36  import java.net.Socket;
37  
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  
41  /**
42   * A simple, but extensible HTTP server, mostly for testing purposes.
43   * 
44   * @author Christian Kohlschuetter
45   * @author Oleg Kalnichevski
46   */
47  public class SimpleHttpServer implements Runnable {
48      private static final Log LOG = LogFactory.getLog(SimpleHttpServer.class);
49      
50      private String testname = "Simple test";
51      private long count = 0;
52      private ServerSocket listener = null;
53      private Thread t;
54      private ThreadGroup tg;
55      private boolean stopped = false;
56  
57      private SimpleConnSet connections = new SimpleConnSet();
58  
59      private HttpRequestHandler requestHandler = null;
60  
61      /**
62       * Creates a new HTTP server instance, using an arbitrary free TCP port
63       * 
64       * @throws IOException  if anything goes wrong during initialization
65       */
66      public SimpleHttpServer() throws IOException {
67          this(null, 0);
68      }
69  
70      /**
71       * Creates a new HTTP server instance, using the specified socket
72       * factory and the TCP port
73       * 
74       * @param   port    Desired TCP port
75       * @throws IOException  if anything goes wrong during initialization
76       */
77      public SimpleHttpServer(SimpleSocketFactory socketfactory, int port) 
78          throws IOException {
79          if (socketfactory == null) {
80          	socketfactory = new SimplePlainSocketFactory();
81          }
82          listener = socketfactory.createServerSocket(port);
83          if(LOG.isDebugEnabled()) {
84              LOG.debug("Starting test HTTP server on port " + getLocalPort());
85          }
86          tg = new ThreadGroup("SimpleHttpServer thread group");
87          t = new Thread(tg, this, "SimpleHttpServer listener");
88          t.setDaemon(true);
89          t.start();
90      }
91  
92      /**
93       * Creates a new HTTP server instance, using the specified TCP port
94       * 
95       * @param   port    Desired TCP port
96       * @throws IOException  if anything goes wrong during initialization
97       */
98      public SimpleHttpServer(int port) throws IOException {
99          this(null, port);
100     }
101 
102     public String getTestname() {
103         return this.testname;
104     }
105 
106     public void setTestname(final String testname) {
107         this.testname = testname;
108     }
109     
110     /**
111      * Returns the TCP port that this HTTP server instance is bound to.
112      *
113      * @return  TCP port, or -1 if not running
114      */
115     public int getLocalPort() {
116         return listener.getLocalPort();
117     }
118     
119     /**
120      * Returns the IP address that this HTTP server instance is bound to.
121      * @return String representation of the IP address or <code>null</code> if not running
122      */
123     public String getLocalAddress() {
124         InetAddress address = listener.getInetAddress();
125         // Ugly work-around for older JDKs
126         byte[] octets = address.getAddress();
127         if ((octets[0] == 0) 
128          && (octets[1] == 0) 
129          && (octets[2] == 0) 
130          && (octets[3] == 0)) {
131             return "localhost"; 
132         } else {
133             return address.getHostAddress();
134         }
135     }
136 
137     /**
138      * Checks if this HTTP server instance is running.
139      * 
140      * @return  true/false
141      */
142     public boolean isRunning() {
143         if(t == null) {
144             return false;
145         }
146         return t.isAlive();
147     }
148 
149     /**
150      * Stops this HTTP server instance.
151      */
152     public synchronized void destroy() {
153         if (stopped) {
154             return;
155         }
156 
157         this.stopped = true;
158         if(LOG.isDebugEnabled()) {
159             LOG.debug("Stopping test HTTP server on port " + getLocalPort());
160         }
161         tg.interrupt();
162         
163         if (listener != null) {
164             try {
165                 listener.close();
166             } catch(IOException e) {
167                 
168             }
169         }
170         this.connections.shutdown();
171     }
172 
173     /**
174      * Returns the currently used HttpRequestHandler by this SimpleHttpServer
175      * 
176      * @return The used HttpRequestHandler, or null.
177      */
178     public HttpRequestHandler getRequestHandler() {
179         return requestHandler;
180     }
181 
182     /**
183      * Sets the HttpRequestHandler to be used for this SimpleHttpServer.
184      * 
185      * @param rh    Request handler to be used, or null to disable.
186      */
187     public void setRequestHandler(HttpRequestHandler rh) {
188         this.requestHandler = rh;
189     }
190 
191     public void setHttpService(HttpService service) {
192         setRequestHandler(new HttpServiceHandler(service));
193     }
194 
195     public void run() {
196         try {
197             while (!this.stopped && !Thread.interrupted()) {
198                 Socket socket = listener.accept();
199                 try {
200                     if (this.requestHandler == null) {
201                         socket.close();
202                         break;
203                     }
204                     SimpleHttpServerConnection conn = new SimpleHttpServerConnection(socket); 
205                     this.connections.addConnection(conn);
206 
207                     Thread t = new SimpleConnectionThread(
208                             tg,
209                             this.testname + " thread " + this.count,
210                             conn, 
211                             this.connections,
212                             this.requestHandler);
213                     t.setDaemon(true);
214                     t.start();
215                 } catch (IOException e) {
216                     LOG.error("I/O error: " + e.getMessage());
217                 }
218                 this.count++;
219                 Thread.sleep(100);
220             }
221         } catch (InterruptedException accept) {
222         } catch (IOException e) {
223             if (!stopped) {
224                 LOG.error("I/O error: " + e.getMessage());
225             }
226         } finally {
227             destroy();
228         }
229     }
230 }

././@LongLink100644 0 0 153 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleHttpServerConnection.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleHttpServerConnectio100644 0 0 52337 10661532627 31462 0ustar 0 0 SimpleHttpServerConnection xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleHttpServerConnection.java,v 1.21 2004/12/11 22:35:26 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.io.OutputStream;
36  import java.io.UnsupportedEncodingException;
37  import java.net.Socket;
38  import java.net.SocketException;
39  import java.util.Iterator;
40  
41  import org.apache.commons.httpclient.ChunkedOutputStream;
42  import org.apache.commons.httpclient.Header;
43  import org.apache.commons.httpclient.HttpParser;
44  import org.apache.commons.httpclient.StatusLine;
45  
46  /**
47   * A connection to the SimpleHttpServer.
48   * 
49   * @author Christian Kohlschuetter
50   * @author Oleg Kalnichevski
51   */
52  public class SimpleHttpServerConnection {
53      
54      private static final String HTTP_ELEMENT_CHARSET = "US-ASCII";
55  
56      private Socket socket = null;
57      private InputStream in = null;
58      private OutputStream out = null;
59      private boolean keepAlive = false;
60  
61      public SimpleHttpServerConnection(final Socket socket) 
62      throws IOException {
63          super();
64          if (socket == null) {
65              throw new IllegalArgumentException("Socket may not be null");
66          }
67          this.socket = socket;
68          this.socket.setSoTimeout(500);
69          this.in = socket.getInputStream();
70          this.out = socket.getOutputStream();
71      }
72  
73      public synchronized void close() {
74          try {
75              if (socket != null) {
76                  in.close();
77                  out.close();
78                  socket.close();
79                  socket = null;
80              }
81          } catch (IOException e) {
82          }
83      }
84  
85      public synchronized boolean isOpen() {
86          return this.socket != null;
87      }
88      
89      public void setKeepAlive(boolean b) {
90          this.keepAlive = b;
91      }
92  
93      public boolean isKeepAlive() {
94          return this.keepAlive;
95      }
96  
97      public InputStream getInputStream() {
98          return this.in;
99      }
100 
101     public OutputStream getOutputStream() {
102         return this.out;
103     }
104 
105     /**
106      * Returns the ResponseWriter used to write the output to the socket.
107      * 
108      * @return This connection's ResponseWriter
109      */
110     public ResponseWriter getWriter() throws UnsupportedEncodingException {
111         return new ResponseWriter(out);
112     }
113 
114     public SimpleRequest readRequest() throws IOException {
115         try {
116             String line = null;
117             do {
118                 line = HttpParser.readLine(in, HTTP_ELEMENT_CHARSET);
119             } while (line != null && line.length() == 0);
120 
121             if (line == null) {
122                 setKeepAlive(false);
123                 return null;
124             }
125             SimpleRequest request = new SimpleRequest( 
126                     RequestLine.parseLine(line),
127                     HttpParser.parseHeaders(this.in, HTTP_ELEMENT_CHARSET),
128                     this.in);
129             return request;
130         } catch (IOException e) {
131             close();
132             throw e;
133         }
134     }
135 
136     public SimpleResponse readResponse() throws IOException {
137         try {
138             String line = null;
139             do {
140                 line = HttpParser.readLine(in, HTTP_ELEMENT_CHARSET);
141             } while (line != null && line.length() == 0);
142 
143             if (line == null) {
144                 setKeepAlive(false);
145                 return null;
146             }
147             SimpleResponse response = new SimpleResponse(
148                     new StatusLine(line),
149                     HttpParser.parseHeaders(this.in, HTTP_ELEMENT_CHARSET),
150                     this.in);
151             return response;
152         } catch (IOException e) {
153             close();
154             throw e;
155         }
156     }
157 
158     public void writeRequest(final SimpleRequest request) throws IOException {
159         if (request == null) {
160             return;
161         }
162         ResponseWriter writer = new ResponseWriter(this.out, HTTP_ELEMENT_CHARSET);
163         writer.println(request.getRequestLine().toString());
164         Iterator item = request.getHeaderIterator();
165         while (item.hasNext()) {
166             Header header = (Header) item.next();
167             writer.print(header.toExternalForm());
168         }
169         writer.println();
170         writer.flush();
171         
172         OutputStream outsream = this.out;
173         InputStream content = request.getBody(); 
174         if (content != null) {
175 
176             Header transferenc = request.getFirstHeader("Transfer-Encoding");
177             if (transferenc != null) {
178                 request.removeHeaders("Content-Length");
179                 if (transferenc.getValue().indexOf("chunked") != -1) {
180                     outsream = new ChunkedOutputStream(outsream);
181                 }
182             }
183             byte[] tmp = new byte[4096];
184             int i = 0;
185             while ((i = content.read(tmp)) >= 0) {
186                 outsream.write(tmp, 0, i);
187             }        
188             if (outsream instanceof ChunkedOutputStream) {
189                 ((ChunkedOutputStream)outsream).finish();
190             }
191         }
192         outsream.flush();
193     }
194     
195     public void writeResponse(final SimpleResponse response) throws IOException {
196         if (response == null) {
197             return;
198         }
199         ResponseWriter writer = new ResponseWriter(this.out, HTTP_ELEMENT_CHARSET);
200         writer.println(response.getStatusLine());
201         Iterator item = response.getHeaderIterator();
202         while (item.hasNext()) {
203             Header header = (Header) item.next();
204             writer.print(header.toExternalForm());
205         }
206         writer.println();
207         writer.flush();
208         
209         OutputStream outsream = this.out;
210         InputStream content = response.getBody(); 
211         if (content != null) {
212 
213             Header transferenc = response.getFirstHeader("Transfer-Encoding");
214             if (transferenc != null) {
215                 response.removeHeaders("Content-Length");
216                 if (transferenc.getValue().indexOf("chunked") != -1) {
217                     outsream = new ChunkedOutputStream(outsream);
218                 }
219             }
220                         
221             byte[] tmp = new byte[1024];
222             int i = 0;
223             while ((i = content.read(tmp)) >= 0) {
224                 outsream.write(tmp, 0, i);
225             }        
226             if (outsream instanceof ChunkedOutputStream) {
227                 ((ChunkedOutputStream)outsream).finish();
228             }
229         }
230         outsream.flush();
231     }
232 
233     public int getSocketTimeout() throws SocketException {
234         return this.socket.getSoTimeout();
235     }
236     
237     public void setSocketTimeout(int timeout) throws SocketException {
238         this.socket.setSoTimeout(timeout);
239     }
240         
241 }
242     

././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimplePlainSocketFactory.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimplePlainSocketFactory.100644 0 0 12567 10661532627 31335 0ustar 0 0 SimplePlainSocketFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimplePlainSocketFactory.java,v 1.1 2004/12/11 22:35:26 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  import java.net.ServerSocket;
35  
36  /**
37   * Defines a plain socket factory
38   * 
39   * @author Oleg Kalnichevski
40   */
41  public class SimplePlainSocketFactory implements SimpleSocketFactory {
42      
43      public SimplePlainSocketFactory() {
44      	super();
45      }
46      
47      public ServerSocket createServerSocket(int port) throws IOException {
48          return new ServerSocket(port);
49      }
50      
51  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleProxy.html100644 0 0 22570 10661532627 27572 0ustar 0 0 SimpleProxy xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleProxy.java,v 1.8 2004/12/11 22:35:26 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  
35  import org.apache.commons.httpclient.Credentials;
36  
37  /**
38   * Simple server that registers default request handlers to act as a proxy.
39   * 
40   * @author Ortwin Glueck
41   * @author Oleg Kalnichevski
42   */
43  public class SimpleProxy extends SimpleHttpServer {
44      
45      private SimpleConnManager connmanager = null; 
46      private HttpRequestHandlerChain stdchain = null;
47  
48      public SimpleProxy(int port) throws IOException {
49          super(port);
50          this.connmanager = new SimpleConnManager(); 
51          this.stdchain = new HttpRequestHandlerChain();
52          this.stdchain.appendHandler(new TransparentProxyRequestHandler());
53          this.stdchain.appendHandler(new ProxyRequestHandler(this.connmanager));
54          setRequestHandler(this.stdchain);
55      }
56  
57      public SimpleProxy() throws IOException {
58          this(0);
59      }
60  
61      public void requireAuthentication(final Credentials creds, final String realm, boolean keepalive) {
62          HttpRequestHandlerChain chain = new HttpRequestHandlerChain(this.stdchain); 
63          chain.prependHandler(new ProxyAuthRequestHandler(creds ,realm, keepalive));
64          setRequestHandler(chain);
65      }
66  
67      public void requireAuthentication(final Credentials creds) {
68          HttpRequestHandlerChain chain = new HttpRequestHandlerChain(this.stdchain); 
69          chain.prependHandler(new ProxyAuthRequestHandler(creds));
70          setRequestHandler(chain);
71      }
72  
73      public void destroy() {
74          super.destroy();
75          this.connmanager.shutdown();
76      }
77      
78      public void addHandler(final HttpRequestHandler handler) {
79          this.stdchain.prependHandler(handler);
80      }
81      
82  }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleRequest.html100644 0 0 46745 10661532627 30113 0ustar 0 0 SimpleRequest xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleRequest.java,v 1.3 2004/11/13 12:21:28 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.ByteArrayOutputStream;
34  import java.io.IOException;
35  import java.io.InputStream;
36  import java.util.Iterator;
37  
38  import org.apache.commons.httpclient.ChunkedInputStream;
39  import org.apache.commons.httpclient.ContentLengthInputStream;
40  import org.apache.commons.httpclient.Header;
41  import org.apache.commons.httpclient.HeaderElement;
42  import org.apache.commons.httpclient.HeaderGroup;
43  import org.apache.commons.httpclient.NameValuePair;
44  
45  /**
46   * A generic HTTP request.
47   * 
48   * @author Oleg Kalnichevski
49   */
50  public class SimpleRequest {
51      
52      public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1";
53      
54      private RequestLine requestLine = null;
55      private HeaderGroup headers = new HeaderGroup();
56      private InputStream entity = null;
57  
58      public SimpleRequest() {
59          super();
60      }
61  
62      public SimpleRequest(
63          final RequestLine requestLine,
64          final Header[] headers,
65          final InputStream content) throws IOException
66      {
67          super();
68          if (requestLine == null) {
69              throw new IllegalArgumentException("Request line may not be null");
70          }
71          this.requestLine = requestLine;
72          if (headers != null) {
73              this.headers.setHeaders(headers);
74          }
75          if (content != null) {
76              // only PUT and POST have content
77              String methodname = requestLine.getMethod(); 
78              if ("POST".equalsIgnoreCase(methodname) || "PUT".equalsIgnoreCase(methodname)) {
79                  Header contentLength = this.headers.getFirstHeader("Content-Length");
80                  Header transferEncoding = this.headers.getFirstHeader("Transfer-Encoding");
81                  InputStream in = content;
82                  if (transferEncoding != null) {
83                      if (transferEncoding.getValue().indexOf("chunked") != -1) {
84                          in = new ChunkedInputStream(in);
85                      }
86                  } else if (contentLength != null) {
87                      long len = getContentLength();
88                      if (len >= 0) {
89                          in = new ContentLengthInputStream(in, len);
90                      }
91                  }
92                  this.entity = in;
93              }
94          }
95      }
96  
97      public SimpleRequest(final RequestLine requestLine, final Header[] headers)
98          throws IOException {
99          this(requestLine, headers, null);
100     }
101     
102     public RequestLine getRequestLine() {
103         return this.requestLine;
104     }
105 
106     public void setRequestLine(final RequestLine requestline) {
107         if (requestline == null) {
108             throw new IllegalArgumentException("Request line may not be null");
109         }
110         this.requestLine = requestline;
111     }
112 
113     public boolean containsHeader(final String name) {
114         return this.headers.containsHeader(name);
115     }
116 
117     public Header[] getHeaders() {
118         return this.headers.getAllHeaders();
119     }
120 
121     public Header getFirstHeader(final String s) {
122         return this.headers.getFirstHeader(s);
123     }
124 
125     public void removeHeaders(final String s) {
126         if (s == null) {
127             return;
128         }
129         Header[] headers = this.headers.getHeaders(s);
130         for (int i = 0; i < headers.length; i++) {
131             this.headers.removeHeader(headers[i]);
132         }
133     }
134 
135     public void addHeader(final Header header) {
136         if (header == null) {
137             return;
138         }
139         this.headers.addHeader(header);
140     }
141 
142     public void setHeader(final Header header) {
143         if (header == null) {
144             return;
145         }
146         removeHeaders(header.getName());
147         addHeader(header);
148     }
149 
150     public Iterator getHeaderIterator() {
151         return this.headers.getIterator();
152     }
153 
154     public String getContentType() {
155         Header contenttype = this.headers.getFirstHeader("Content-Type");
156         if (contenttype != null) {
157             return contenttype.getValue(); 
158         } else {
159             return "text/plain"; 
160         }
161     }
162     
163     public String getCharset() {
164         String charset = null;
165         Header contenttype = this.headers.getFirstHeader("Content-Type");
166         if (contenttype != null) {
167             HeaderElement values[] = contenttype.getElements();
168             if (values.length == 1) {
169                 NameValuePair param = values[0].getParameterByName("charset");
170                 if (param != null) {
171                     charset = param.getValue();
172                 }
173             }
174         }
175         if (charset != null) {
176             return charset;
177         } else {
178             return DEFAULT_CONTENT_CHARSET;
179         }
180     }
181     
182     public long getContentLength() {
183         Header contentLength = this.headers.getFirstHeader("Content-Length");
184         if (contentLength != null) {
185             try {
186                 return Long.parseLong(contentLength.getValue());
187             } catch (NumberFormatException e) {
188                 return -1;
189             }
190         } else {
191             return -1;
192         }
193     }
194     
195     public InputStream getBody() {
196         return this.entity;
197     }
198     
199     public byte[] getBodyBytes() throws IOException {
200         InputStream in = getBody();
201         if (in != null) {
202             byte[] tmp = new byte[4096];
203             int bytesRead = 0;
204             ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
205             while ((bytesRead = in.read(tmp)) != -1) {
206                 buffer.write(tmp, 0, bytesRead);
207             }
208             return buffer.toByteArray();
209         } else {
210             return null;
211         }
212     }
213     
214     public String getBodyString() throws IOException {
215         byte[] raw = getBodyBytes();
216         if (raw != null) {
217             return new String(raw, getCharset());
218         } else {
219             return null;
220         }
221     }
222 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleResponse.html100644 0 0 55553 10661532627 30256 0ustar 0 0 SimpleResponse xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleResponse.java,v 1.8 2004/11/13 12:21:28 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.ByteArrayInputStream;
34  import java.io.ByteArrayOutputStream;
35  import java.io.IOException;
36  import java.io.InputStream;
37  import java.io.UnsupportedEncodingException;
38  import java.util.Iterator;
39  
40  import org.apache.commons.httpclient.ChunkedInputStream;
41  import org.apache.commons.httpclient.ContentLengthInputStream;
42  import org.apache.commons.httpclient.Header;
43  import org.apache.commons.httpclient.HeaderElement;
44  import org.apache.commons.httpclient.HeaderGroup;
45  import org.apache.commons.httpclient.HttpStatus;
46  import org.apache.commons.httpclient.HttpVersion;
47  import org.apache.commons.httpclient.NameValuePair;
48  import org.apache.commons.httpclient.StatusLine;
49  
50  /**
51   * A generic HTTP response.
52   * 
53   * @author Christian Kohlschuetter
54   * @author Oleg Kalnichevski
55   */
56  public class SimpleResponse {
57      
58      public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1";
59      
60      private HttpVersion ver = HttpVersion.HTTP_1_1;
61      private int statuscode = HttpStatus.SC_OK;
62      private String phrase = HttpStatus.getStatusText(HttpStatus.SC_OK);
63      private HeaderGroup headers = new HeaderGroup();
64      private InputStream entity = null;
65  
66      public SimpleResponse() {
67          super();
68      }
69  
70      public SimpleResponse(
71              final StatusLine statusline, 
72              final Header[] headers, 
73              final InputStream content) 
74              throws IOException {
75          super();
76          if (statusline == null) {
77              throw new IllegalArgumentException("Status line may not be null");
78          }
79          setStatusLine(HttpVersion.parse(statusline.getHttpVersion()),
80                  statusline.getStatusCode(), statusline.getReasonPhrase());
81          setHeaders(headers);
82          if (content != null) {
83              InputStream in = content;
84              Header contentLength = this.headers.getFirstHeader("Content-Length");
85              Header transferEncoding = this.headers.getFirstHeader("Transfer-Encoding");
86  
87              if (transferEncoding != null) {
88                  if (transferEncoding.getValue().indexOf("chunked") != -1) {
89                      in = new ChunkedInputStream(in);
90                  }
91              } else if (contentLength != null) {
92                  long len = getContentLength();
93                  if (len >= 0) {
94                      in = new ContentLengthInputStream(in, len);
95                  }
96              }
97              this.entity = in;
98          }
99      }
100 
101 
102     public void setStatusLine(final HttpVersion ver, int statuscode, final String phrase) {
103         if (ver == null) {
104             throw new IllegalArgumentException("HTTP version may not be null");
105         }
106         if (statuscode <= 0) {
107             throw new IllegalArgumentException("Status code may not be negative or zero");
108         }
109         this.ver = ver;
110         this.statuscode = statuscode;
111         if (phrase != null) {
112             this.phrase = phrase;
113         } else {
114             this.phrase = HttpStatus.getStatusText(statuscode);
115         }
116     }
117 
118     public void setStatusLine(final HttpVersion ver, int statuscode) {
119         setStatusLine(ver, statuscode, null);
120     }
121 
122     public String getPhrase() {
123         return this.phrase;
124     }
125 
126     public int getStatuscode() {
127         return this.statuscode;
128     }
129 
130     public HttpVersion getHttpVersion() {
131         return this.ver;
132     }
133 
134     public String getStatusLine() {
135         StringBuffer buffer = new StringBuffer();
136         buffer.append(this.ver);
137         buffer.append(' ');
138         buffer.append(this.statuscode);
139         if (this.phrase != null) {
140             buffer.append(' ');
141             buffer.append(this.phrase);
142         }
143         return buffer.toString();
144     }
145 
146     public boolean containsHeader(final String name) {
147         return this.headers.containsHeader(name);
148     }
149 
150     public Header[] getHeaders() {
151         return this.headers.getAllHeaders();
152     }
153 
154     public Header getFirstHeader(final String name) {
155         return this.headers.getFirstHeader(name);
156     }
157 
158     public void removeHeaders(final String s) {
159         if (s == null) {
160             return;
161         }
162         Header[] headers = this.headers.getHeaders(s);
163         for (int i = 0; i < headers.length; i++) {
164             this.headers.removeHeader(headers[i]);
165         }
166     }
167 
168     public void addHeader(final Header header) {
169         if (header == null) {
170             return;
171         }
172         this.headers.addHeader(header);
173     }
174 
175     public void setHeader(final Header header) {
176         if (header == null) {
177             return;
178         }
179         removeHeaders(header.getName());
180         addHeader(header);
181     }
182 
183     public void setHeaders(final Header[] headers) {
184         if (headers == null) {
185             return;
186         }
187         this.headers.setHeaders(headers);
188     }
189 
190     public Iterator getHeaderIterator() {
191         return this.headers.getIterator();
192     }
193     
194     public String getCharset() {
195         String charset = DEFAULT_CONTENT_CHARSET;
196         Header contenttype = this.headers.getFirstHeader("Content-Type");
197         if (contenttype != null) {
198             HeaderElement values[] = contenttype.getElements();
199             if (values.length == 1) {
200                 NameValuePair param = values[0].getParameterByName("charset");
201                 if (param != null) {
202                     charset = param.getValue();
203                 }
204             }
205         }
206         return charset;
207     }
208 
209     public long getContentLength() {
210         Header contentLength = this.headers.getFirstHeader("Content-Length");
211         if (contentLength != null) {
212             try {
213                 return Long.parseLong(contentLength.getValue());
214             } catch (NumberFormatException e) {
215                 return -1;
216             }
217         } else {
218             return -1;
219         }
220     }
221     
222     public void setBodyString(final String string) {
223         if (string != null) {
224             byte[] raw = null;
225             try {
226                 raw = string.getBytes(DEFAULT_CONTENT_CHARSET);
227             } catch (UnsupportedEncodingException e) {
228                 raw = string.getBytes();
229             }
230             this.entity = new ByteArrayInputStream(raw);
231             if (!containsHeader("Content-Type")) {
232                 setHeader(new Header("Content-Type", "text/plain"));
233             }
234             setHeader(new Header("Content-Length", Long.toString(raw.length)));
235         } else {
236             this.entity = null;
237         }
238     }
239     
240     public void setBody(final InputStream instream) {
241         this.entity = instream;
242     }
243     
244     public InputStream getBody() {
245         return this.entity;
246     }
247     
248     public byte[] getBodyBytes() throws IOException {
249         InputStream in = getBody();
250         if (in != null) {
251             byte[] tmp = new byte[4096];
252             int bytesRead = 0;
253             ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
254             while ((bytesRead = in.read(tmp)) != -1) {
255                 buffer.write(tmp, 0, bytesRead);
256             }
257             return buffer.toByteArray();
258         } else {
259             return null;
260         }
261     }
262     
263     public String getBodyString() throws IOException {
264         byte[] raw = getBodyBytes();
265         if (raw != null) {
266             return new String(raw, getCharset());
267         } else {
268             return null;
269         }
270     }
271 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/SimpleSocketFactory.html100644 0 0 11406 10661532627 31225 0ustar 0 0 SimpleSocketFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleSocketFactory.java,v 1.1 2004/12/11 22:35:26 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  import java.net.ServerSocket;
35  
36  /**
37   * Defines a socket factory interface
38   * 
39   * @author Oleg Kalnichevski
40   */
41  public interface SimpleSocketFactory {
42      
43      ServerSocket createServerSocket(int port) throws IOException;
44      
45  }

././@LongLink100644 0 0 157 10661532634 10264 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/TransparentProxyRequestHandler.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/TransparentProxyRequestHa100644 0 0 33766 10661532627 31532 0ustar 0 0 TransparentProxyRequestHandler xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/TransparentProxyRequestHandler.java,v 1.7 2004/12/11 22:35:26 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.server;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.io.InterruptedIOException;
36  import java.io.OutputStream;
37  import java.net.Socket;
38  
39  import org.apache.commons.httpclient.Header;
40  import org.apache.commons.httpclient.HttpStatus;
41  import org.apache.commons.httpclient.HttpVersion;
42  
43  /**
44   * This request handler can handle the CONNECT method. It does nothing for any
45   * other HTTP methods.
46   * 
47   * @author Ortwin Glueck
48   */
49  public class TransparentProxyRequestHandler implements HttpRequestHandler {
50  
51      /*
52       * (non-Javadoc)
53       * 
54       * @see org.apache.commons.httpclient.server.HttpRequestHandler#processRequest(org.apache.commons.httpclient.server.SimpleHttpServerConnection)
55       */
56      public boolean processRequest(
57          final SimpleHttpServerConnection conn,
58          final SimpleRequest request) throws IOException
59      {
60  
61          RequestLine line = request.getRequestLine();
62          HttpVersion ver = line.getHttpVersion();
63          String method = line.getMethod();
64          if (!"CONNECT".equalsIgnoreCase(method)) {
65              return false;
66          }
67          Socket targetSocket = null;
68          try {
69              targetSocket = connect(line.getUri());
70          } catch (IOException e) {
71              SimpleResponse response = new SimpleResponse();
72              response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND);
73              response.setHeader(new Header("Server", "test proxy"));
74              response.setBodyString("Cannot connect to " + line.getUri());
75              conn.writeResponse(response);
76              return true;
77          }
78          SimpleResponse response = new SimpleResponse();
79          response.setHeader(new Header("Server", "test proxy"));
80          response.setStatusLine(ver, HttpStatus.SC_OK, "Connection established");
81          conn.writeResponse(response);
82          
83          SimpleHttpServerConnection target = new SimpleHttpServerConnection(targetSocket); 
84          pump(conn, target);
85          return true;
86      }
87  
88      private void pump(final SimpleHttpServerConnection source, final SimpleHttpServerConnection target)
89          throws IOException {
90  
91          source.setSocketTimeout(100);
92          target.setSocketTimeout(100);
93  
94          InputStream sourceIn = source.getInputStream();
95          OutputStream sourceOut = source.getOutputStream();
96          InputStream targetIn = target.getInputStream();
97          OutputStream targetOut = target.getOutputStream();
98          
99          byte[] tmp = new byte[1024];
100         int l;
101         for (;;) {
102             if (!source.isOpen() || !target.isOpen()) { 
103                 break;
104             }
105             try {
106                 l = sourceIn.read(tmp);
107                 if (l == -1) {
108                     break;
109                 }
110                 targetOut.write(tmp, 0, l);
111             } catch (InterruptedIOException ignore) {
112                 if (Thread.interrupted()) {
113                     break;
114                 }
115             }
116             try {
117                 l = targetIn.read(tmp);
118                 if (l == -1) {
119                     break;
120                 }
121                 sourceOut.write(tmp, 0, l);
122             } catch (InterruptedIOException ignore) {
123                 if (Thread.interrupted()) {
124                     break;
125                 }
126             }
127         }
128     }
129     
130     private static Socket connect(final String host) throws IOException {
131         String hostname = null; 
132         int port; 
133         int i = host.indexOf(':');
134         if (i != -1) {
135             hostname = host.substring(0, i);
136             try {
137                 port = Integer.parseInt(host.substring(i + 1));
138             } catch (NumberFormatException ex) {
139                 throw new IOException("Invalid host address: " + host);
140             }
141         } else {
142             hostname = host;
143             port = 80;
144         }
145         return new Socket(hostname, port);        
146     }
147     
148 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/package-frame.html100644 0 0 7111 10661532631 27727 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.server

org.apache.commons.httpclient.server

Classes

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/server/package-summary.html100644 0 0 13431 10661532631 30354 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.server

Package org.apache.commons.httpclient.server

Class Summary
AuthRequestHandler
ErrorResponse
HttpRequestHandler
HttpRequestHandlerChain
HttpService
HttpServiceHandler
ProxyAuthRequestHandler
ProxyRequestHandler
RequestLine
ResponseWriter
SimpleConnList
SimpleConnManager
SimpleConnSet
SimpleConnectionThread
SimpleHost
SimpleHttpServer
SimpleHttpServerConnection
SimplePlainSocketFactory
SimpleProxy
SimpleRequest
SimpleResponse
SimpleSocketFactory
TransparentProxyRequestHandler

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/ssl/SimpleSSLSocketFactory.html100644 0 0 23447 10661532627 31112 0ustar 0 0 SimpleSSLSocketFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/ssl/SimpleSSLSocketFactory.java,v 1.1 2004/12/11 22:35:26 olegk Exp $
3    * $Revision: 514390 $
4    * $Date: 2007-03-04 13:37:15 +0100 (Sun, 04 Mar 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.ssl;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.net.ServerSocket;
36  import java.net.URL;
37  import java.security.KeyStore;
38  
39  import javax.net.ServerSocketFactory;
40  
41  import org.apache.commons.httpclient.server.SimpleSocketFactory;
42  import org.apache.commons.logging.Log;
43  import org.apache.commons.logging.LogFactory;
44  
45  import com.sun.net.ssl.KeyManager;
46  import com.sun.net.ssl.KeyManagerFactory;
47  import com.sun.net.ssl.SSLContext;
48  
49  /**
50   * Defines a SSL socket factory
51   * 
52   * @author Oleg Kalnichevski
53   */
54  public class SimpleSSLSocketFactory implements SimpleSocketFactory {
55      
56      private static final Log LOG = LogFactory.getLog(SimpleSocketFactory.class);
57  
58      private static SSLContext SSLCONTEXT = null;
59      
60      private static SSLContext createSSLContext() {
61          try {
62              ClassLoader cl = SimpleSocketFactory.class.getClassLoader();
63              URL url = cl.getResource("org/apache/commons/httpclient/ssl/simpleserver.keystore");
64              KeyStore keystore  = KeyStore.getInstance("jks");
65              InputStream is = null;
66              try {
67  	            is = url.openStream();
68  	            keystore.load(is, "nopassword".toCharArray());
69              } finally {
70              	if (is != null) is.close();
71              }
72              KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
73                      KeyManagerFactory.getDefaultAlgorithm());
74              kmfactory.init(keystore, "nopassword".toCharArray());
75              KeyManager[] keymanagers = kmfactory.getKeyManagers(); 
76              SSLContext sslcontext = SSLContext.getInstance("TLS");
77              sslcontext.init(keymanagers, null, null);
78              return sslcontext;
79          } catch (Exception ex) {
80          	// this is not the way a sane exception handling should be done
81              // but for our simple HTTP testing framework this will suffice
82              LOG.error(ex.getMessage(), ex);
83              throw new IllegalStateException(ex.getMessage());
84          }
85      
86      }
87      
88      private static SSLContext getSSLContext() {
89      	if (SSLCONTEXT == null) {
90      		SSLCONTEXT = createSSLContext();
91          }
92          return SSLCONTEXT;
93      }
94      
95      public SimpleSSLSocketFactory() {
96          super();
97      }
98      
99      public ServerSocket createServerSocket(int port) throws IOException {
100     	ServerSocketFactory socketfactory = getSSLContext().getServerSocketFactory();
101         return socketfactory.createServerSocket(port);
102     }
103     
104 }

././@LongLink100644 0 0 160 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/ssl/SimpleSSLTestProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/ssl/SimpleSSLTestProtocolSocketF100644 0 0 33255 10661532627 31305 0ustar 0 0 SimpleSSLTestProtocolSocketFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/ssl/SimpleSSLTestProtocolSocketFactory.java,v 1.1 2004/12/11 22:35:26 olegk Exp $
3    * $Revision: 514390 $
4    * $Date: 2007-03-04 13:37:15 +0100 (Sun, 04 Mar 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.ssl;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.net.InetAddress;
36  import java.net.Socket;
37  import java.net.URL;
38  import java.net.UnknownHostException;
39  import java.security.KeyStore;
40  
41  import org.apache.commons.httpclient.ConnectTimeoutException;
42  import org.apache.commons.httpclient.params.HttpConnectionParams;
43  import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;
44  import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
45  import org.apache.commons.httpclient.server.SimpleSocketFactory;
46  import org.apache.commons.logging.Log;
47  import org.apache.commons.logging.LogFactory;
48  
49  import com.sun.net.ssl.SSLContext;
50  import com.sun.net.ssl.TrustManager;
51  import com.sun.net.ssl.TrustManagerFactory;
52  
53  public class SimpleSSLTestProtocolSocketFactory implements SecureProtocolSocketFactory {
54  
55      private static final Log LOG = LogFactory.getLog(SimpleSSLTestProtocolSocketFactory.class);
56  
57      private static SSLContext SSLCONTEXT = null;
58      
59      private static SSLContext createSSLContext() {
60          try {
61              ClassLoader cl = SimpleSocketFactory.class.getClassLoader();
62              URL url = cl.getResource("org/apache/commons/httpclient/ssl/simpleserver.keystore");
63              KeyStore keystore  = KeyStore.getInstance("jks");
64              InputStream is = null;
65              try {
66              	is = url.openStream();
67              	keystore.load(is, "nopassword".toCharArray());
68              } finally {
69              	if (is != null) is.close();
70              }
71              TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
72                      TrustManagerFactory.getDefaultAlgorithm());
73              tmfactory.init(keystore);
74              TrustManager[] trustmanagers = tmfactory.getTrustManagers(); 
75              SSLContext sslcontext = SSLContext.getInstance("TLS");
76              sslcontext.init(null, trustmanagers, null);
77              return sslcontext;
78          } catch (Exception ex) {
79              // this is not the way a sane exception handling should be done
80              // but for our simple HTTP testing framework this will suffice
81              LOG.error(ex.getMessage(), ex);
82              throw new IllegalStateException(ex.getMessage());
83          }
84      
85      }
86      
87      private static SSLContext getSSLContext() {
88          if (SSLCONTEXT == null) {
89              SSLCONTEXT = createSSLContext();
90          }
91          return SSLCONTEXT;
92      }
93      
94      public SimpleSSLTestProtocolSocketFactory() {
95          super();
96      }
97      
98      public Socket createSocket(
99          final String host,
100         final int port,
101         final InetAddress localAddress,
102         final int localPort,
103         final HttpConnectionParams params
104     ) throws IOException, UnknownHostException, ConnectTimeoutException {
105         if (params == null) {
106             throw new IllegalArgumentException("Parameters may not be null");
107         }
108         int timeout = params.getConnectionTimeout();
109         if (timeout == 0) {
110             return createSocket(host, port, localAddress, localPort);
111         } else {
112             // To be eventually deprecated when migrated to Java 1.4 or above
113             return ControllerThreadSocketFactory.createSocket(
114                     this, host, port, localAddress, localPort, timeout);
115         }
116     }
117 
118     public Socket createSocket(
119         String host,
120         int port,
121         InetAddress clientHost,
122         int clientPort)
123         throws IOException, UnknownHostException
124    {
125        return getSSLContext().getSocketFactory().createSocket(
126             host,
127             port,
128             clientHost,
129             clientPort
130         );
131     }
132 
133     public Socket createSocket(String host, int port)
134         throws IOException, UnknownHostException
135     {
136         return getSSLContext().getSocketFactory().createSocket(
137             host,
138             port
139         );
140     }
141 
142     public Socket createSocket(
143         Socket socket,
144         String host,
145         int port,
146         boolean autoClose)
147         throws IOException, UnknownHostException
148     {
149         return getSSLContext().getSocketFactory().createSocket(
150             socket,
151             host,
152             port,
153             autoClose
154         );
155     }
156 }

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/ssl/package-frame.html100644 0 0 1617 10661532631 27227 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.ssl

org.apache.commons.httpclient.ssl

Classes

commons-httpclient-3.1/docs/xref-test/org/apache/commons/httpclient/ssl/package-summary.html100644 0 0 4256 10661532631 27634 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.ssl

Package org.apache.commons.httpclient.ssl

Class Summary
SimpleSSLSocketFactory
SimpleSSLTestProtocolSocketFactory

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref-test/overview-frame.html100644 0 0 2560 10661532627 21043 0ustar 0 0 HttpClient 3.1 Reference

All Classes

Packages

commons-httpclient-3.1/docs/xref-test/overview-summary.html100644 0 0 5176 10661532631 21447 0ustar 0 0 HttpClient 3.1 Reference
  • Overview
  • Package

HttpClient 3.1 Reference

Packages
org.apache.commons.httpclient
org.apache.commons.httpclient.auth
org.apache.commons.httpclient.cookie
org.apache.commons.httpclient.params
org.apache.commons.httpclient.server
org.apache.commons.httpclient.ssl
  • Overview
  • Package

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref-test/stylesheet.css100644 0 0 2435 10661532631 20116 0ustar 0 0 /* Javadoc style sheet */ /* Define colors, fonts and other style attributes here to override the defaults */ body { background-color: #fff; font-family: Arial, Helvetica, sans-serif; } a:link { color: #00f; } a:visited { color: #00a; } a:active, a:hover { color: #f30 !important; } ul, li { list-style-type:none ; margin:0; padding:0; } table td{ padding: 3px; border: 1px solid #000; } table{ width:100%; border: 1px solid #000; border-collapse: collapse; } div.overview { background-color:#ddd; padding: 4px 4px 4px 0; } div.overview li, div.framenoframe li { display: inline; } div.framenoframe { text-align: center; font-size: x-small; } div.framenoframe li { margin: 0 3px 0 3px; } div.overview li { margin:3px 3px 0 3px; padding: 4px; } li.selected { background-color:#888; color: #fff; font-weight: bold; } table.summary { margin-bottom: 20px; } table.summary td, table.summary th { font-weight: bold; text-align: left; padding: 3px; } table.summary th{ background-color:#036; color: #fff; } table.summary td{ background-color:#eee; border: 1px solid black; } em { color: #A00; } em.comment { color: #390; } .string { color: #009; } div#footer { text-align:center; } #overview { padding:2px; } hr { height: 1px; color: #000; } commons-httpclient-3.1/docs/xref/allclasses-frame.html100644 0 0 44464 10661532627 20377 0ustar 0 0 All Classes

All Classes

commons-httpclient-3.1/docs/xref/index.html100644 0 0 1243 10661532627 16234 0ustar 0 0 HttpClient 3.1 Reference <h1>Frame Alert</h1> <p> You don't have frames. Go <a href="overview-summary.html">here</a> </p> commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/AutoCloseInputStream.html100644 0 0 41021 10661532627 27076 0ustar 0 0 AutoCloseInputStream xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/AutoCloseInputStream.java,v 1.9 2004/04/18 23:51:34 jsdever Exp $
3    * $Revision: 505890 $
4    * $Date: 2007-02-11 12:25:25 +0100 (Sun, 11 Feb 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.FilterInputStream;
34  import java.io.IOException;
35  import java.io.InputStream;
36  
37  /**
38   * Closes an underlying stream as soon as the end of the stream is reached, and
39   * notifies a client when it has done so.
40   *
41   * @author Ortwin Glueck
42   * @author Eric Johnson
43   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
44   *
45   * @since 2.0
46   */
47  class AutoCloseInputStream extends FilterInputStream {
48  
49      /** 
50       * True if this stream is open.  Assume that the underlying stream 
51       * is open until we get an EOF indication.
52       */
53      private boolean streamOpen = true;
54  
55      /** True if the stream closed itself. */
56      private boolean selfClosed = false;
57  
58      /** 
59       * The watcher is notified when the contents of the stream have
60       * been  exhausted
61       */ 
62      private ResponseConsumedWatcher watcher = null;
63  
64      /**
65       * Create a new auto closing stream for the provided connection
66       *
67       * @param in the input stream to read from
68       * @param watcher   To be notified when the contents of the stream have been
69       *  consumed.
70       */
71      public AutoCloseInputStream(
72              final InputStream in, final ResponseConsumedWatcher watcher) {
73          super(in);
74          this.watcher = watcher;
75      }
76  
77      /**
78       * Reads the next byte of data from the input stream.
79       *
80       * @throws IOException when there is an error reading
81       * @return the character read, or -1 for EOF
82       */
83      public int read() throws IOException {
84          int l = -1;
85  
86          if (isReadAllowed()) {
87              // underlying stream not closed, go ahead and read.
88              l = super.read();
89              checkClose(l);
90          }
91  
92          return l;
93      }
94  
95      /**
96       * Reads up to <code>len</code> bytes of data from the stream.
97       *
98       * @param b a <code>byte</code> array to read data into
99       * @param off an offset within the array to store data
100      * @param len the maximum number of bytes to read
101      * @return the number of bytes read or -1 for EOF
102      * @throws IOException if there are errors reading
103      */
104     public int read(byte[] b, int off, int len) throws IOException {
105         int l = -1;
106 
107         if (isReadAllowed()) {
108             l = super.read(b,  off,  len);
109             checkClose(l);
110         }
111 
112         return l;
113     }
114 
115     /**
116      * Reads some number of bytes from the input stream and stores them into the
117      * buffer array b.
118      *
119      * @param b a <code>byte</code> array to read data into
120      * @return the number of bytes read or -1 for EOF
121      * @throws IOException if there are errors reading
122      */
123     public int read(byte[] b) throws IOException {
124         int l = -1;
125 
126         if (isReadAllowed()) {
127             l = super.read(b);
128             checkClose(l);
129         }
130         return l;
131     }
132 
133     /**
134      * Obtains the number of bytes that can be read without blocking.
135      *
136      * @return  the number of bytes available without blocking
137      * @throws IOException in case of a problem
138      */
139     public int available() throws IOException {
140         int a = 0; // not -1
141 
142         if (isReadAllowed()) {
143             a = super.available();
144             // no checkClose() here, available() can't trigger EOF
145         }
146 
147         return a;
148     }
149 
150     /**
151      * Close the stream, and also close the underlying stream if it is not
152      * already closed.
153      * @throws IOException If an IO problem occurs.
154      */
155     public void close() throws IOException {
156         if (!selfClosed) {
157             selfClosed = true;
158             notifyWatcher();
159         }
160     }
161 
162     /**
163      * Close the underlying stream should the end of the stream arrive.
164      *
165      * @param readResult    The result of the read operation to check.
166      * @throws IOException If an IO problem occurs.
167      */
168     private void checkClose(int readResult) throws IOException {
169         if (readResult == -1) {
170             notifyWatcher();
171         }
172     }
173 
174     /**
175      * See whether a read of the underlying stream should be allowed, and if
176      * not, check to see whether our stream has already been closed!
177      *
178      * @return <code>true</code> if it is still OK to read from the stream.
179      * @throws IOException If an IO problem occurs.
180      */
181     private boolean isReadAllowed() throws IOException {
182         if (!streamOpen && selfClosed) {
183             throw new IOException("Attempted read on closed stream.");
184         }
185         return streamOpen;
186     }
187 
188     /**
189      * Notify the watcher that the contents have been consumed.
190      * @throws IOException If an IO problem occurs.
191      */
192     private void notifyWatcher() throws IOException {
193         if (streamOpen) {
194             super.close();
195             streamOpen = false;
196 
197             if (watcher != null) {
198                 watcher.responseConsumed();
199             }
200         }
201     }
202 }
203 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/ChunkedInputStream.html100644 0 0 75631 10661532627 26577 0ustar 0 0 ChunkedInputStream xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ChunkedInputStream.java,v 1.24 2004/10/10 15:18:55 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.ByteArrayOutputStream;
34  import java.io.IOException;
35  import java.io.InputStream;
36  
37  import org.apache.commons.httpclient.util.EncodingUtil;
38  import org.apache.commons.httpclient.util.ExceptionUtil;
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  
42  
43  /**
44   * <p>Transparently coalesces chunks of a HTTP stream that uses
45   * Transfer-Encoding chunked.</p>
46   *
47   * <p>Note that this class NEVER closes the underlying stream, even when close
48   * gets called.  Instead, it will read until the "end" of its chunking on close,
49   * which allows for the seamless invocation of subsequent HTTP 1.1 calls, while
50   * not requiring the client to remember to read the entire contents of the
51   * response.</p>
52   *
53   * @author Ortwin Glueck
54   * @author Sean C. Sullivan
55   * @author Martin Elwin
56   * @author Eric Johnson
57   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
58   * @author Michael Becke
59   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
60   *
61   * @since 2.0
62   *
63   */
64  public class ChunkedInputStream extends InputStream {
65      /** The inputstream that we're wrapping */
66      private InputStream in;
67  
68      /** The chunk size */
69      private int chunkSize;
70  
71      /** The current position within the current chunk */
72      private int pos;
73  
74      /** True if we'are at the beginning of stream */
75      private boolean bof = true;
76  
77      /** True if we've reached the end of stream */
78      private boolean eof = false;
79  
80      /** True if this stream is closed */
81      private boolean closed = false;
82  
83      /** The method that this stream came from */
84      private HttpMethod method = null;
85  
86      /** Log object for this class. */
87      private static final Log LOG = LogFactory.getLog(ChunkedInputStream.class);
88  
89      /**
90       * ChunkedInputStream constructor that associates the chunked input stream with a 
91       * {@link HttpMethod HTTP method}. Usually it should be the same {@link HttpMethod 
92       * HTTP method} the chunked input stream originates from. If chunked input stream 
93       * contains any footers (trailing headers), they will be added to the associated 
94       * {@link HttpMethod HTTP method}.
95       *
96       * @param in the raw input stream
97       * @param method the HTTP method to associate this input stream with. Can be <tt>null</tt>.  
98       *
99       * @throws IOException If an IO error occurs
100      */
101     public ChunkedInputStream(
102         final InputStream in, final HttpMethod method) throws IOException {
103             
104     	if (in == null) {
105     		throw new IllegalArgumentException("InputStream parameter may not be null");
106     	}
107         this.in = in;
108         this.method = method;
109         this.pos = 0;
110     }
111 
112     /**
113      * ChunkedInputStream constructor
114      *
115      * @param in the raw input stream
116      *
117      * @throws IOException If an IO error occurs
118      */
119     public ChunkedInputStream(final InputStream in) throws IOException {
120     	this(in, null);
121     }
122     
123     /**
124      * <p> Returns all the data in a chunked stream in coalesced form. A chunk
125      * is followed by a CRLF. The method returns -1 as soon as a chunksize of 0
126      * is detected.</p>
127      * 
128      * <p> Trailer headers are read automcatically at the end of the stream and
129      * can be obtained with the getResponseFooters() method.</p>
130      *
131      * @return -1 of the end of the stream has been reached or the next data
132      * byte
133      * @throws IOException If an IO problem occurs
134      * 
135      * @see HttpMethod#getResponseFooters()
136      */
137     public int read() throws IOException {
138 
139         if (closed) {
140             throw new IOException("Attempted read from closed stream.");
141         }
142         if (eof) {
143             return -1;
144         } 
145         if (pos >= chunkSize) {
146             nextChunk();
147             if (eof) { 
148                 return -1;
149             }
150         }
151         pos++;
152         return in.read();
153     }
154 
155     /**
156      * Read some bytes from the stream.
157      * @param b The byte array that will hold the contents from the stream.
158      * @param off The offset into the byte array at which bytes will start to be
159      * placed.
160      * @param len the maximum number of bytes that can be returned.
161      * @return The number of bytes returned or -1 if the end of stream has been
162      * reached.
163      * @see java.io.InputStream#read(byte[], int, int)
164      * @throws IOException if an IO problem occurs.
165      */
166     public int read (byte[] b, int off, int len) throws IOException {
167 
168         if (closed) {
169             throw new IOException("Attempted read from closed stream.");
170         }
171 
172         if (eof) { 
173             return -1;
174         }
175         if (pos >= chunkSize) {
176             nextChunk();
177             if (eof) { 
178                 return -1;
179             }
180         }
181         len = Math.min(len, chunkSize - pos);
182         int count = in.read(b, off, len);
183         pos += count;
184         return count;
185     }
186 
187     /**
188      * Read some bytes from the stream.
189      * @param b The byte array that will hold the contents from the stream.
190      * @return The number of bytes returned or -1 if the end of stream has been
191      * reached.
192      * @see java.io.InputStream#read(byte[])
193      * @throws IOException if an IO problem occurs.
194      */
195     public int read (byte[] b) throws IOException {
196         return read(b, 0, b.length);
197     }
198 
199     /**
200      * Read the CRLF terminator.
201      * @throws IOException If an IO error occurs.
202      */
203     private void readCRLF() throws IOException {
204         int cr = in.read();
205         int lf = in.read();
206         if ((cr != '\r') || (lf != '\n')) { 
207             throw new IOException(
208                 "CRLF expected at end of chunk: " + cr + "/" + lf);
209         }
210     }
211 
212 
213     /**
214      * Read the next chunk.
215      * @throws IOException If an IO error occurs.
216      */
217     private void nextChunk() throws IOException {
218         if (!bof) {
219             readCRLF();
220         }
221         chunkSize = getChunkSizeFromInputStream(in);
222         bof = false;
223         pos = 0;
224         if (chunkSize == 0) {
225             eof = true;
226             parseTrailerHeaders();
227         }
228     }
229 
230     /**
231      * Expects the stream to start with a chunksize in hex with optional
232      * comments after a semicolon. The line must end with a CRLF: "a3; some
233      * comment\r\n" Positions the stream at the start of the next line.
234      *
235      * @param in The new input stream.
236      * @param required <tt>true<tt/> if a valid chunk must be present,
237      *                 <tt>false<tt/> otherwise.
238      * 
239      * @return the chunk size as integer
240      * 
241      * @throws IOException when the chunk size could not be parsed
242      */
243     private static int getChunkSizeFromInputStream(final InputStream in) 
244       throws IOException {
245             
246         ByteArrayOutputStream baos = new ByteArrayOutputStream();
247         // States: 0=normal, 1=\r was scanned, 2=inside quoted string, -1=end
248         int state = 0; 
249         while (state != -1) {
250         int b = in.read();
251             if (b == -1) { 
252                 throw new IOException("chunked stream ended unexpectedly");
253             }
254             switch (state) {
255                 case 0: 
256                     switch (b) {
257                         case '\r':
258                             state = 1;
259                             break;
260                         case '\"':
261                             state = 2;
262                             /* fall through */
263                         default:
264                             baos.write(b);
265                     }
266                     break;
267 
268                 case 1:
269                     if (b == '\n') {
270                         state = -1;
271                     } else {
272                         // this was not CRLF
273                         throw new IOException("Protocol violation: Unexpected"
274                             + " single newline character in chunk size");
275                     }
276                     break;
277 
278                 case 2:
279                     switch (b) {
280                         case '\\':
281                             b = in.read();
282                             baos.write(b);
283                             break;
284                         case '\"':
285                             state = 0;
286                             /* fall through */
287                         default:
288                             baos.write(b);
289                     }
290                     break;
291                 default: throw new RuntimeException("assertion failed");
292             }
293         }
294 
295         //parse data
296         String dataString = EncodingUtil.getAsciiString(baos.toByteArray());
297         int separator = dataString.indexOf(';');
298         dataString = (separator > 0)
299             ? dataString.substring(0, separator).trim()
300             : dataString.trim();
301 
302         int result;
303         try {
304             result = Integer.parseInt(dataString.trim(), 16);
305         } catch (NumberFormatException e) {
306             throw new IOException ("Bad chunk size: " + dataString);
307         }
308         return result;
309     }
310 
311     /**
312      * Reads and stores the Trailer headers.
313      * @throws IOException If an IO problem occurs
314      */
315     private void parseTrailerHeaders() throws IOException {
316         Header[] footers = null;
317         try {
318             String charset = "US-ASCII";
319             if (this.method != null) {
320                 charset = this.method.getParams().getHttpElementCharset();
321             }
322             footers = HttpParser.parseHeaders(in, charset);
323         } catch(HttpException e) {
324             LOG.error("Error parsing trailer headers", e);
325             IOException ioe = new IOException(e.getMessage());
326             ExceptionUtil.initCause(ioe, e); 
327             throw ioe;
328         }
329         if (this.method != null) {
330             for (int i = 0; i < footers.length; i++) {
331                 this.method.addResponseFooter(footers[i]);
332             }
333         }
334     }
335 
336     /**
337      * Upon close, this reads the remainder of the chunked message,
338      * leaving the underlying socket at a position to start reading the
339      * next response without scanning.
340      * @throws IOException If an IO problem occurs.
341      */
342     public void close() throws IOException {
343         if (!closed) {
344             try {
345                 if (!eof) {
346                     exhaustInputStream(this);
347                 }
348             } finally {
349                 eof = true;
350                 closed = true;
351             }
352         }
353     }
354 
355     /**
356      * Exhaust an input stream, reading until EOF has been encountered.
357      *
358      * <p>Note that this function is intended as a non-public utility.
359      * This is a little weird, but it seemed silly to make a utility
360      * class for this one function, so instead it is just static and
361      * shared that way.</p>
362      *
363      * @param inStream The {@link InputStream} to exhaust.
364      * @throws IOException If an IO problem occurs
365      */
366     static void exhaustInputStream(InputStream inStream) throws IOException {
367         // read and discard the remainder of the message
368         byte buffer[] = new byte[1024];
369         while (inStream.read(buffer) >= 0) {
370             ;
371         }
372     }
373 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/ChunkedOutputStream.html100644 0 0 41562 10661532627 26774 0ustar 0 0 ChunkedOutputStream xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ChunkedOutputStream.java,v 1.16 2004/05/13 04:03:25 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.io.OutputStream;
35  
36  import org.apache.commons.httpclient.util.EncodingUtil;
37  
38  /**
39   * Implements HTTP chunking support. Writes are buffered to an internal buffer (2048 default size).
40   * Chunks are guaranteed to be at least as large as the buffer size (except for the last chunk).
41   *
42   * @author Mohammad Rezaei, Goldman, Sachs & Co.
43   */
44  public class ChunkedOutputStream extends OutputStream {
45  
46      // ------------------------------------------------------- Static Variables
47      private static final byte CRLF[] = new byte[] {(byte) 13, (byte) 10};
48  
49      /** End chunk */
50      private static final byte ENDCHUNK[] = CRLF;
51  
52      /** 0 */
53      private static final byte ZERO[] = new byte[] {(byte) '0'};
54  
55      // ----------------------------------------------------- Instance Variables
56      private OutputStream stream = null;
57  
58      private byte[] cache;
59  
60      private int cachePosition = 0;
61  
62      private boolean wroteLastChunk = false;
63  
64      // ----------------------------------------------------------- Constructors
65      /**
66       * Wraps a stream and chunks the output.
67       * @param stream to wrap
68       * @param bufferSize minimum chunk size (excluding last chunk)
69       * @throws IOException
70       * 
71       * @since 3.0
72       */
73      public ChunkedOutputStream(OutputStream stream, int bufferSize) throws IOException {
74          this.cache = new byte[bufferSize];
75          this.stream = stream;
76      }
77  
78      /**
79       * Wraps a stream and chunks the output. The default buffer size of 2048 was chosen because
80       * the chunk overhead is less than 0.5%
81       * @param stream
82       * @throws IOException
83       */
84      public ChunkedOutputStream(OutputStream stream) throws IOException {
85          this(stream, 2048);
86      }
87  
88      // ----------------------------------------------------------- Internal methods
89      /**
90       * Writes the cache out onto the underlying stream
91       * @throws IOException
92       * 
93       * @since 3.0
94       */
95      protected void flushCache() throws IOException {
96          if (cachePosition > 0) {
97              byte chunkHeader[] = EncodingUtil.getAsciiBytes(
98                      Integer.toHexString(cachePosition) + "\r\n");
99              stream.write(chunkHeader, 0, chunkHeader.length);
100             stream.write(cache, 0, cachePosition);
101             stream.write(ENDCHUNK, 0, ENDCHUNK.length);
102             cachePosition = 0;
103         }
104     }
105 
106     /**
107      * Writes the cache and bufferToAppend to the underlying stream
108      * as one large chunk
109      * @param bufferToAppend
110      * @param off
111      * @param len
112      * @throws IOException
113      * 
114      * @since 3.0
115      */
116     protected void flushCacheWithAppend(byte bufferToAppend[], int off, int len) throws IOException {
117         byte chunkHeader[] = EncodingUtil.getAsciiBytes(
118                 Integer.toHexString(cachePosition + len) + "\r\n");
119         stream.write(chunkHeader, 0, chunkHeader.length);
120         stream.write(cache, 0, cachePosition);
121         stream.write(bufferToAppend, off, len);
122         stream.write(ENDCHUNK, 0, ENDCHUNK.length);
123         cachePosition = 0;
124     }
125 
126     protected void writeClosingChunk() throws IOException {
127         // Write the final chunk.
128 
129         stream.write(ZERO, 0, ZERO.length);
130         stream.write(CRLF, 0, CRLF.length);
131         stream.write(ENDCHUNK, 0, ENDCHUNK.length);
132     }
133 
134     // ----------------------------------------------------------- Public Methods
135     /**
136      * Must be called to ensure the internal cache is flushed and the closing chunk is written.
137      * @throws IOException
138      * 
139      * @since 3.0
140      */
141     public void finish() throws IOException {
142         if (!wroteLastChunk) {
143             flushCache();
144             writeClosingChunk();
145             wroteLastChunk = true;
146         }
147     }
148 
149     // -------------------------------------------- OutputStream Methods
150     /**
151      * Write the specified byte to our output stream.
152      * 
153      * Note: Avoid this method as it will cause an inefficient single byte chunk. 
154      * Use write (byte[], int, int) instead.
155      * 
156      * @param b The byte to be written
157      * @throws IOException if an input/output error occurs
158      */
159     public void write(int b) throws IOException {
160         cache[cachePosition] = (byte) b;
161         cachePosition++;
162         if (cachePosition == cache.length) flushCache();
163     }
164 
165     /**
166      * Writes the array. If the array does not fit within the buffer, it is
167      * not split, but rather written out as one large chunk.
168      * @param b
169      * @throws IOException
170      * 
171      * @since 3.0
172      */
173     public void write(byte b[]) throws IOException {
174         this.write(b, 0, b.length);
175     }
176 
177     public void write(byte src[], int off, int len) throws IOException {
178         if (len >= cache.length - cachePosition) {
179             flushCacheWithAppend(src, off, len);
180         } else {
181             System.arraycopy(src, off, cache, cachePosition, len);
182             cachePosition += len;
183         }
184     }
185 
186     /**
187      * Flushes the underlying stream, but leaves the internal buffer alone.
188      * @throws IOException
189      */
190     public void flush() throws IOException {
191         stream.flush();
192     }
193 
194     /**
195      * Finishes writing to the underlying stream, but does NOT close the underlying stream.
196      * @throws IOException
197      */
198     public void close() throws IOException {
199         finish();
200         super.close();
201     }
202 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/CircularRedirectException.html100644 0 0 15776 10661532627 30133 0ustar 0 0 CircularRedirectException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/CircularRedirectException.java,v 1.1 2005/01/14 19:40:39 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * Signals a circular redirect
35   * 
36   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
37   * 
38   * @since 3.0
39   */
40  public class CircularRedirectException extends RedirectException {
41  
42      /**
43       * Creates a new CircularRedirectException with a <tt>null</tt> detail message. 
44       */
45      public CircularRedirectException() {
46          super();
47      }
48  
49      /**
50       * Creates a new CircularRedirectException with the specified detail message.
51       * 
52       * @param message The exception detail message
53       */
54      public CircularRedirectException(String message) {
55          super(message);
56      }
57  
58      /**
59       * Creates a new CircularRedirectException with the specified detail message and cause.
60       * 
61       * @param message the exception detail message
62       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
63       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
64       */
65      public CircularRedirectException(String message, Throwable cause) {
66          super(message, cause);
67      }
68  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/ConnectMethod.html100644 0 0 56526 10661532627 25556 0ustar 0 0 ConnectMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ConnectMethod.java,v 1.29 2004/06/24 21:39:52 mbecke Exp $
3    * $Revision: 483949 $
4    * $Date: 2006-12-08 12:34:50 +0100 (Fri, 08 Dec 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  
38  /**
39   * Establishes a tunneled HTTP connection via the CONNECT method.
40   *
41   * @author Ortwin Gl???ck
42   * @author dIon Gillard
43   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
44   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
45   * @since 2.0
46   * @version $Revision: 483949 $ $Date: 2006-12-08 12:34:50 +0100 (Fri, 08 Dec 2006) $
47   */
48  public class ConnectMethod extends HttpMethodBase {
49      
50      /** the name of this method */
51      public static final String NAME = "CONNECT";
52  
53      private final HostConfiguration targethost;
54  
55      /**
56       * @deprecated use #ConnectMethod(HttpHost);
57       * 
58       * Create a connect method.
59       * 
60       * @since 3.0
61       */
62      public ConnectMethod() {
63          super();
64          this.targethost = null;
65      }
66  
67      /**
68       * @deprecated the wrapped method is no longer used
69       * 
70       * Create a connect method wrapping the existing method
71       *
72       * @param method the {@link HttpMethod method} to execute after connecting
73       *      to the server
74       */
75      public ConnectMethod(HttpMethod method) {
76          super();
77          this.targethost = null;
78      }
79  
80      /**
81       * Create a connect method.
82       * 
83       * @since 3.0
84       */
85      public ConnectMethod(final HostConfiguration targethost) {
86          super();
87          if (targethost == null) {
88              throw new IllegalArgumentException("Target host may not be null");
89          }
90          this.targethost = targethost;
91      }
92  
93      /**
94       * Provide the {@link #NAME name} of this method.
95       *
96       * @return the String "CONNECT"
97       */
98      public String getName() {
99          return NAME;
100     }
101     
102     public String getPath() {
103         if (this.targethost != null) {
104             StringBuffer buffer = new StringBuffer();
105             buffer.append(this.targethost.getHost()); 
106             int port = this.targethost.getPort();
107             if (port == -1) {
108                 port = this.targethost.getProtocol().getDefaultPort();  
109             }
110             buffer.append(':'); 
111             buffer.append(port);
112             return buffer.toString();
113         } else {
114             return "/";
115         }
116     }
117 
118     public URI getURI() throws URIException {
119         String charset = getParams().getUriCharset();
120         return new URI(getPath(), true, charset);
121     }
122 
123     /**
124      * This method does nothing. <tt>CONNECT</tt> request is not supposed 
125      * to contain <tt>Cookie</tt> request header.
126      *
127      * @param state current state of http requests
128      * @param conn the connection to use for I/O
129      *
130      * @throws IOException when errors occur reading or writing to/from the
131      *         connection
132      * @throws HttpException when a recoverable error occurs
133      *  
134      * @see HttpMethodBase#addCookieRequestHeader(HttpState, HttpConnection)
135      */
136     protected void addCookieRequestHeader(HttpState state, HttpConnection conn)
137         throws IOException, HttpException {
138         // Do nothing. Not applicable to CONNECT method
139     }
140 
141 
142     /**
143      * Populates the request headers map to with additional {@link Header
144      * headers} to be submitted to the given {@link HttpConnection}.
145      *
146      * <p>
147      * This implementation adds <tt>User-Agent</tt>, <tt>Host</tt>,
148      * and <tt>Proxy-Authorization</tt> headers, when appropriate.
149      * </p>
150      *
151      * @param state the client state
152      * @param conn the {@link HttpConnection} the headers will eventually be
153      *        written to
154      * @throws IOException when an error occurs writing the request
155      * @throws HttpException when a HTTP protocol error occurs
156      *
157      * @see #writeRequestHeaders
158      */
159     protected void addRequestHeaders(HttpState state, HttpConnection conn)
160         throws IOException, HttpException {
161         LOG.trace("enter ConnectMethod.addRequestHeaders(HttpState, "
162             + "HttpConnection)");
163         addUserAgentRequestHeader(state, conn);
164         addHostRequestHeader(state, conn);
165         addProxyConnectionHeader(state, conn);
166     }
167 
168     /**
169      * Execute this method and create a tunneled HttpConnection.  If the method
170      * is successful (i.e. the status is a 2xx) tunnelCreated() will be called
171      * on the connection.
172      *
173      * @param state the current http state
174      * @param conn the connection to write to
175      * @return the http status code from execution
176      * @throws HttpException when an error occurs writing the headers
177      * @throws IOException when an error occurs writing the headers
178      * 
179      * @see HttpConnection#tunnelCreated()
180      */
181     public int execute(HttpState state, HttpConnection conn) 
182     throws IOException, HttpException {
183 
184         LOG.trace("enter ConnectMethod.execute(HttpState, HttpConnection)");
185         int code = super.execute(state, conn);
186         if (LOG.isDebugEnabled()) {
187             LOG.debug("CONNECT status code " + code);
188         }
189         return code;
190     }
191 
192     /**
193      * Special Connect request.
194      *
195      * @param state the current http state
196      * @param conn the connection to write to
197      * @throws IOException when an error occurs writing the request
198      * @throws HttpException when an error occurs writing the request
199      */
200     protected void writeRequestLine(HttpState state, HttpConnection conn)
201     throws IOException, HttpException {
202         StringBuffer buffer = new StringBuffer();
203         buffer.append(getName()); 
204         buffer.append(' '); 
205         if (this.targethost != null) {
206             buffer.append(getPath()); 
207         } else {
208             int port = conn.getPort();
209             if (port == -1) {
210                 port = conn.getProtocol().getDefaultPort();  
211             }
212             buffer.append(conn.getHost()); 
213             buffer.append(':'); 
214             buffer.append(port); 
215         }
216         buffer.append(" "); 
217         buffer.append(getEffectiveVersion()); 
218         String line = buffer.toString();
219         conn.printLine(line, getParams().getHttpElementCharset());
220         if (Wire.HEADER_WIRE.enabled()) {
221             Wire.HEADER_WIRE.output(line);
222         }
223     }
224 
225     /**
226      * Returns <code>true</code> if the status code is anything other than
227      * SC_OK, <code>false</code> otherwise.
228      * 
229      * @see HttpMethodBase#shouldCloseConnection(HttpConnection)
230      * @see HttpStatus#SC_OK
231      * 
232      * @return <code>true</code> if the connection should be closed
233      */
234     protected boolean shouldCloseConnection(HttpConnection conn) {
235         if (getStatusCode() == HttpStatus.SC_OK) {
236             Header connectionHeader = null;
237             if (!conn.isTransparent()) {
238                 connectionHeader = getResponseHeader("proxy-connection");
239             }
240             if (connectionHeader == null) {
241                 connectionHeader = getResponseHeader("connection");
242             }
243             if (connectionHeader != null) {
244                 if (connectionHeader.getValue().equalsIgnoreCase("close")) {
245                     if (LOG.isWarnEnabled()) {
246                         LOG.warn("Invalid header encountered '" + connectionHeader.toExternalForm() 
247                         + "' in response " + getStatusLine().toString());
248                     }
249                 }
250             }
251             return false;
252         } else {
253             return super.shouldCloseConnection(conn);
254         }
255     }
256     
257     /** Log object for this class. */
258     private static final Log LOG = LogFactory.getLog(ConnectMethod.class);
259 
260 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/ConnectTimeoutException.html100644 0 0 17041 10661532627 27630 0ustar 0 0 ConnectTimeoutException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ConnectTimeoutException.java,v 1.5 2004/07/05 22:46:58 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.InterruptedIOException;
34  
35  import org.apache.commons.httpclient.util.ExceptionUtil;
36  
37  /**
38   * A timeout while connecting to an HTTP server or waiting for an
39   * available connection from an HttpConnectionManager.
40   * 
41   * @author <a href="mailto:laura@lwerner.org">Laura Werner</a>
42   * 
43   * @since 3.0
44   */
45  public class ConnectTimeoutException extends InterruptedIOException {
46  
47      /**
48       * Creates a ConnectTimeoutException with a <tt>null</tt> detail message.
49       */
50      public ConnectTimeoutException() {
51          super();
52      }
53  
54      /**
55       * Creates a ConnectTimeoutException with the specified detail message.
56       * 
57       * @param message The exception detail message 
58       */
59      public ConnectTimeoutException(String message) {
60          super(message);
61      }
62  
63      /**
64       * Creates a new ConnectTimeoutException with the specified detail message and cause.
65       * 
66       * @param message the exception detail message
67       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
68       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
69       */
70      public ConnectTimeoutException(String message, Throwable cause) {
71          super(message);
72          // If we're running on JDK 1.4 or later, tell Throwable what the cause was
73          ExceptionUtil.initCause(this, cause);
74      }
75  
76  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/ConnectionPoolTimeoutException.html100644 0 0 16310 10661532627 31166 0ustar 0 0 ConnectionPoolTimeoutException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ConnectionPoolTimeoutException.java,v 1.1 2004/07/05 22:46:58 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * A timeout while connecting waiting for an available connection 
35   * from an HttpConnectionManager.
36   * 
37   * @author <a href="mailto:laura@lwerner.org">Laura Werner</a>
38   * 
39   * @since 3.0
40   */
41  public class ConnectionPoolTimeoutException extends ConnectTimeoutException {
42  
43      /**
44       * Creates a ConnectTimeoutException with a <tt>null</tt> detail message.
45       */
46      public ConnectionPoolTimeoutException() {
47          super();
48      }
49  
50      /**
51       * Creates a ConnectTimeoutException with the specified detail message.
52       * 
53       * @param message The exception detail message 
54       */
55      public ConnectionPoolTimeoutException(String message) {
56          super(message);
57      }
58  
59      /**
60       * Creates a new ConnectTimeoutException with the specified detail message and cause.
61       * 
62       * @param message the exception detail message
63       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
64       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
65       */
66      public ConnectionPoolTimeoutException(String message, Throwable cause) {
67          super(message, cause);
68      }
69  
70  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/ContentLengthInputStream.html100644 0 0 45574 10661532627 27775 0ustar 0 0 ContentLengthInputStream xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ContentLengthInputStream.java,v 1.12 2004/10/04 22:05:44 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  
36  /**
37   * Cuts the wrapped InputStream off after a specified number of bytes.
38   *
39   * <p>Implementation note: Choices abound. One approach would pass
40   * through the {@link InputStream#mark} and {@link InputStream#reset} calls to
41   * the underlying stream.  That's tricky, though, because you then have to
42   * start duplicating the work of keeping track of how much a reset rewinds.
43   * Further, you have to watch out for the "readLimit", and since the semantics
44   * for the readLimit leave room for differing implementations, you might get
45   * into a lot of trouble.</p>
46   *
47   * <p>Alternatively, you could make this class extend {@link java.io.BufferedInputStream}
48   * and then use the protected members of that class to avoid duplicated effort.
49   * That solution has the side effect of adding yet another possible layer of
50   * buffering.</p>
51   *
52   * <p>Then, there is the simple choice, which this takes - simply don't
53   * support {@link InputStream#mark} and {@link InputStream#reset}.  That choice
54   * has the added benefit of keeping this class very simple.</p>
55   *
56   * @author Ortwin Glueck
57   * @author Eric Johnson
58   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
59   * @since 2.0
60   */
61  public class ContentLengthInputStream extends InputStream {
62      
63      /**
64       * The maximum number of bytes that can be read from the stream. Subsequent
65       * read operations will return -1.
66       */
67      private long contentLength;
68  
69      /** The current position */
70      private long pos = 0;
71  
72      /** True if the stream is closed. */
73      private boolean closed = false;
74  
75      /**
76       * Wrapped input stream that all calls are delegated to.
77       */
78      private InputStream wrappedStream = null;
79  
80      /**
81       * @deprecated use {@link #ContentLengthInputStream(InputStream, long)}
82       * 
83       * Creates a new length limited stream
84       *
85       * @param in The stream to wrap
86       * @param contentLength The maximum number of bytes that can be read from
87       * the stream. Subsequent read operations will return -1.
88       */
89      public ContentLengthInputStream(InputStream in, int contentLength) {
90          this(in, (long)contentLength);
91      }
92  
93      /**
94       * Creates a new length limited stream
95       *
96       * @param in The stream to wrap
97       * @param contentLength The maximum number of bytes that can be read from
98       * the stream. Subsequent read operations will return -1.
99       * 
100      * @since 3.0
101      */
102     public ContentLengthInputStream(InputStream in, long contentLength) {
103         super();
104         this.wrappedStream = in;
105         this.contentLength = contentLength;
106     }
107 
108     /**
109      * <p>Reads until the end of the known length of content.</p>
110      *
111      * <p>Does not close the underlying socket input, but instead leaves it
112      * primed to parse the next response.</p>
113      * @throws IOException If an IO problem occurs.
114      */
115     public void close() throws IOException {
116         if (!closed) {
117             try {
118                 ChunkedInputStream.exhaustInputStream(this);
119             } finally {
120                 // close after above so that we don't throw an exception trying
121                 // to read after closed!
122                 closed = true;
123             }
124         }
125     }
126 
127 
128     /**
129      * Read the next byte from the stream
130      * @return The next byte or -1 if the end of stream has been reached.
131      * @throws IOException If an IO problem occurs
132      * @see java.io.InputStream#read()
133      */
134     public int read() throws IOException {
135         if (closed) {
136             throw new IOException("Attempted read from closed stream.");
137         }
138 
139         if (pos >= contentLength) {
140             return -1;
141         }
142         pos++;
143         return this.wrappedStream.read();
144     }
145 
146     /**
147      * Does standard {@link InputStream#read(byte[], int, int)} behavior, but
148      * also notifies the watcher when the contents have been consumed.
149      *
150      * @param b     The byte array to fill.
151      * @param off   Start filling at this position.
152      * @param len   The number of bytes to attempt to read.
153      * @return The number of bytes read, or -1 if the end of content has been
154      *  reached.
155      *
156      * @throws java.io.IOException Should an error occur on the wrapped stream.
157      */
158     public int read (byte[] b, int off, int len) throws java.io.IOException {
159         if (closed) {
160             throw new IOException("Attempted read from closed stream.");
161         }
162 
163         if (pos >= contentLength) {
164             return -1;
165         }
166 
167         if (pos + len > contentLength) {
168             len = (int) (contentLength - pos);
169         }
170         int count = this.wrappedStream.read(b, off, len);
171         pos += count;
172         return count;
173     }
174 
175 
176     /**
177      * Read more bytes from the stream.
178      * @param b The byte array to put the new data in.
179      * @return The number of bytes read into the buffer.
180      * @throws IOException If an IO problem occurs
181      * @see java.io.InputStream#read(byte[])
182      */
183     public int read(byte[] b) throws IOException {
184         return read(b, 0, b.length);
185     }
186 
187     /**
188      * Skips and discards a number of bytes from the input stream.
189      * @param n The number of bytes to skip.
190      * @return The actual number of bytes skipped. <= 0 if no bytes
191      * are skipped.
192      * @throws IOException If an error occurs while skipping bytes.
193      * @see InputStream#skip(long)
194      */
195     public long skip(long n) throws IOException {
196         // make sure we don't skip more bytes than are 
197         // still available
198         long length = Math.min(n, contentLength - pos);
199         // skip and keep track of the bytes actually skipped
200         length = this.wrappedStream.skip(length);
201         // only add the skipped bytes to the current position
202         // if bytes were actually skipped
203         if (length > 0) {
204             pos += length;
205         }
206         return length;
207     }
208 
209     public int available() throws IOException {
210         if (this.closed) {
211             return 0;
212         }
213         int avail = this.wrappedStream.available();
214         if (this.pos + avail > this.contentLength ) {
215             avail = (int)(this.contentLength - this.pos);
216         }
217         return avail;     
218     }
219     
220 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/Cookie.html100644 0 0 125451 10661532627 24247 0ustar 0 0 Cookie xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Cookie.java,v 1.44 2004/06/05 16:49:20 olegk Exp $
3    * $Revision: 531354 $
4    * $Date: 2007-04-23 08:53:20 +0200 (Mon, 23 Apr 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.Serializable;
34  import java.util.Comparator;
35  import java.util.Date;
36  
37  import org.apache.commons.httpclient.cookie.CookiePolicy;
38  import org.apache.commons.httpclient.cookie.CookieSpec;
39  import org.apache.commons.httpclient.util.LangUtils;
40  import org.apache.commons.logging.Log;
41  import org.apache.commons.logging.LogFactory;
42  
43  /**
44   * <p>
45   * HTTP "magic-cookie" represents a piece of state information
46   * that the HTTP agent and the target server can exchange to maintain 
47   * a session.
48   * </p>
49   * 
50   * @author B.C. Holmes
51   * @author <a href="mailto:jericho@thinkfree.com">Park, Sung-Gu</a>
52   * @author <a href="mailto:dsale@us.britannica.com">Doug Sale</a>
53   * @author Rod Waldhoff
54   * @author dIon Gillard
55   * @author Sean C. Sullivan
56   * @author <a href="mailto:JEvans@Cyveillance.com">John Evans</a>
57   * @author Marc A. Saegesser
58   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
59   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
60   * 
61   * @version $Revision: 531354 $ $Date: 2007-04-23 08:53:20 +0200 (Mon, 23 Apr 2007) $
62   */
63  public class Cookie extends NameValuePair implements Serializable, Comparator {
64  
65      // ----------------------------------------------------------- Constructors
66  
67      /**
68       * Default constructor. Creates a blank cookie 
69       */
70  
71      public Cookie() {
72          this(null, "noname", null, null, null, false);
73      }
74  
75      /**
76       * Creates a cookie with the given name, value and domain attribute.
77       *
78       * @param name    the cookie name
79       * @param value   the cookie value
80       * @param domain  the domain this cookie can be sent to
81       */
82      public Cookie(String domain, String name, String value) {
83          this(domain, name, value, null, null, false);
84      }
85  
86      /**
87       * Creates a cookie with the given name, value, domain attribute,
88       * path attribute, expiration attribute, and secure attribute 
89       *
90       * @param name    the cookie name
91       * @param value   the cookie value
92       * @param domain  the domain this cookie can be sent to
93       * @param path    the path prefix for which this cookie can be sent
94       * @param expires the {@link Date} at which this cookie expires,
95       *                or <tt>null</tt> if the cookie expires at the end
96       *                of the session
97       * @param secure if true this cookie can only be sent over secure
98       * connections
99       * @throws IllegalArgumentException If cookie name is null or blank,
100      *   cookie name contains a blank, or cookie name starts with character $
101      *   
102      */
103     public Cookie(String domain, String name, String value, 
104         String path, Date expires, boolean secure) {
105             
106         super(name, value);
107         LOG.trace("enter Cookie(String, String, String, String, Date, boolean)");
108         if (name == null) {
109             throw new IllegalArgumentException("Cookie name may not be null");
110         }
111         if (name.trim().equals("")) {
112             throw new IllegalArgumentException("Cookie name may not be blank");
113         }
114         this.setPath(path);
115         this.setDomain(domain);
116         this.setExpiryDate(expires);
117         this.setSecure(secure);
118     }
119 
120     /**
121      * Creates a cookie with the given name, value, domain attribute,
122      * path attribute, maximum age attribute, and secure attribute 
123      *
124      * @param name   the cookie name
125      * @param value  the cookie value
126      * @param domain the domain this cookie can be sent to
127      * @param path   the path prefix for which this cookie can be sent
128      * @param maxAge the number of seconds for which this cookie is valid.
129      *               maxAge is expected to be a non-negative number. 
130      *               <tt>-1</tt> signifies that the cookie should never expire.
131      * @param secure if <tt>true</tt> this cookie can only be sent over secure
132      * connections
133      */
134     public Cookie(String domain, String name, String value, String path, 
135         int maxAge, boolean secure) {
136             
137         this(domain, name, value, path, null, secure);
138         if (maxAge < -1) {
139             throw new IllegalArgumentException("Invalid max age:  " + Integer.toString(maxAge));
140         }            
141         if (maxAge >= 0) {
142             setExpiryDate(new Date(System.currentTimeMillis() + maxAge * 1000L));
143         }
144     }
145 
146     /**
147      * Returns the comment describing the purpose of this cookie, or
148      * <tt>null</tt> if no such comment has been defined.
149      * 
150      * @return comment 
151      *
152      * @see #setComment(String)
153      */
154     public String getComment() {
155         return cookieComment;
156     }
157 
158     /**
159      * If a user agent (web browser) presents this cookie to a user, the
160      * cookie's purpose will be described using this comment.
161      * 
162      * @param comment
163      *  
164      * @see #getComment()
165      */
166     public void setComment(String comment) {
167         cookieComment = comment;
168     }
169 
170     /**
171      * Returns the expiration {@link Date} of the cookie, or <tt>null</tt>
172      * if none exists.
173      * <p><strong>Note:</strong> the object returned by this method is 
174      * considered immutable. Changing it (e.g. using setTime()) could result
175      * in undefined behaviour. Do so at your peril. </p>
176      * @return Expiration {@link Date}, or <tt>null</tt>.
177      *
178      * @see #setExpiryDate(java.util.Date)
179      *
180      */
181     public Date getExpiryDate() {
182         return cookieExpiryDate;
183     }
184 
185     /**
186      * Sets expiration date.
187      * <p><strong>Note:</strong> the object returned by this method is considered
188      * immutable. Changing it (e.g. using setTime()) could result in undefined 
189      * behaviour. Do so at your peril.</p>
190      *
191      * @param expiryDate the {@link Date} after which this cookie is no longer valid.
192      *
193      * @see #getExpiryDate
194      *
195      */
196     public void setExpiryDate (Date expiryDate) {
197         cookieExpiryDate = expiryDate;
198     }
199 
200 
201     /**
202      * Returns <tt>false</tt> if the cookie should be discarded at the end
203      * of the "session"; <tt>true</tt> otherwise.
204      *
205      * @return <tt>false</tt> if the cookie should be discarded at the end
206      *         of the "session"; <tt>true</tt> otherwise
207      */
208     public boolean isPersistent() {
209         return (null != cookieExpiryDate);
210     }
211 
212 
213     /**
214      * Returns domain attribute of the cookie.
215      * 
216      * @return the value of the domain attribute
217      *
218      * @see #setDomain(java.lang.String)
219      */
220     public String getDomain() {
221         return cookieDomain;
222     }
223 
224     /**
225      * Sets the domain attribute.
226      * 
227      * @param domain The value of the domain attribute
228      *
229      * @see #getDomain
230      */
231     public void setDomain(String domain) {
232         if (domain != null) {
233             int ndx = domain.indexOf(":");
234             if (ndx != -1) {
235               domain = domain.substring(0, ndx);
236             }
237             cookieDomain = domain.toLowerCase();
238         }
239     }
240 
241 
242     /**
243      * Returns the path attribute of the cookie
244      * 
245      * @return The value of the path attribute.
246      * 
247      * @see #setPath(java.lang.String)
248      */
249     public String getPath() {
250         return cookiePath;
251     }
252 
253     /**
254      * Sets the path attribute.
255      *
256      * @param path The value of the path attribute
257      *
258      * @see #getPath
259      *
260      */
261     public void setPath(String path) {
262         cookiePath = path;
263     }
264 
265     /**
266      * @return <code>true</code> if this cookie should only be sent over secure connections.
267      * @see #setSecure(boolean)
268      */
269     public boolean getSecure() {
270         return isSecure;
271     }
272 
273     /**
274      * Sets the secure attribute of the cookie.
275      * <p>
276      * When <tt>true</tt> the cookie should only be sent
277      * using a secure protocol (https).  This should only be set when
278      * the cookie's originating server used a secure protocol to set the
279      * cookie's value.
280      *
281      * @param secure The value of the secure attribute
282      * 
283      * @see #getSecure()
284      */
285     public void setSecure (boolean secure) {
286         isSecure = secure;
287     }
288 
289     /**
290      * Returns the version of the cookie specification to which this
291      * cookie conforms.
292      *
293      * @return the version of the cookie.
294      * 
295      * @see #setVersion(int)
296      *
297      */
298     public int getVersion() {
299         return cookieVersion;
300     }
301 
302     /**
303      * Sets the version of the cookie specification to which this
304      * cookie conforms. 
305      *
306      * @param version the version of the cookie.
307      * 
308      * @see #getVersion
309      */
310     public void setVersion(int version) {
311         cookieVersion = version;
312     }
313 
314     /**
315      * Returns true if this cookie has expired.
316      * 
317      * @return <tt>true</tt> if the cookie has expired.
318      */
319     public boolean isExpired() {
320         return (cookieExpiryDate != null  
321             && cookieExpiryDate.getTime() <= System.currentTimeMillis());
322     }
323 
324     /**
325      * Returns true if this cookie has expired according to the time passed in.
326      * 
327      * @param now The current time.
328      * 
329      * @return <tt>true</tt> if the cookie expired.
330      */
331     public boolean isExpired(Date now) {
332         return (cookieExpiryDate != null  
333             && cookieExpiryDate.getTime() <= now.getTime());
334     }
335 
336 
337     /**
338      * Indicates whether the cookie had a path specified in a 
339      * path attribute of the <tt>Set-Cookie</tt> header. This value
340      * is important for generating the <tt>Cookie</tt> header because 
341      * some cookie specifications require that the <tt>Cookie</tt> header 
342      * should only include a path attribute if the cookie's path 
343      * was specified in the <tt>Set-Cookie</tt> header.
344      *
345      * @param value <tt>true</tt> if the cookie's path was explicitly 
346      * set, <tt>false</tt> otherwise.
347      * 
348      * @see #isPathAttributeSpecified
349      */
350     public void setPathAttributeSpecified(boolean value) {
351         hasPathAttribute = value;
352     }
353 
354     /**
355      * Returns <tt>true</tt> if cookie's path was set via a path attribute
356      * in the <tt>Set-Cookie</tt> header.
357      *
358      * @return value <tt>true</tt> if the cookie's path was explicitly 
359      * set, <tt>false</tt> otherwise.
360      * 
361      * @see #setPathAttributeSpecified
362      */
363     public boolean isPathAttributeSpecified() {
364         return hasPathAttribute;
365     }
366 
367     /**
368      * Indicates whether the cookie had a domain specified in a 
369      * domain attribute of the <tt>Set-Cookie</tt> header. This value
370      * is important for generating the <tt>Cookie</tt> header because 
371      * some cookie specifications require that the <tt>Cookie</tt> header 
372      * should only include a domain attribute if the cookie's domain 
373      * was specified in the <tt>Set-Cookie</tt> header.
374      *
375      * @param value <tt>true</tt> if the cookie's domain was explicitly 
376      * set, <tt>false</tt> otherwise.
377      *
378      * @see #isDomainAttributeSpecified
379      */
380     public void setDomainAttributeSpecified(boolean value) {
381         hasDomainAttribute = value;
382     }
383 
384     /**
385      * Returns <tt>true</tt> if cookie's domain was set via a domain 
386      * attribute in the <tt>Set-Cookie</tt> header.
387      *
388      * @return value <tt>true</tt> if the cookie's domain was explicitly 
389      * set, <tt>false</tt> otherwise.
390      *
391      * @see #setDomainAttributeSpecified
392      */
393     public boolean isDomainAttributeSpecified() {
394         return hasDomainAttribute;
395     }
396 
397     /**
398      * Returns a hash code in keeping with the
399      * {@link Object#hashCode} general hashCode contract.
400      * @return A hash code
401      */
402     public int hashCode() {
403         int hash = LangUtils.HASH_SEED;
404         hash = LangUtils.hashCode(hash, this.getName());
405         hash = LangUtils.hashCode(hash, this.cookieDomain);
406         hash = LangUtils.hashCode(hash, this.cookiePath);
407         return hash;
408     }
409 
410 
411     /**
412      * Two cookies are equal if the name, path and domain match.
413      * @param obj The object to compare against.
414      * @return true if the two objects are equal.
415      */
416     public boolean equals(Object obj) {
417         if (obj == null) return false;
418         if (this == obj) return true;
419         if (obj instanceof Cookie) {
420             Cookie that = (Cookie) obj;
421             return LangUtils.equals(this.getName(), that.getName())
422                   && LangUtils.equals(this.cookieDomain, that.cookieDomain)
423                   && LangUtils.equals(this.cookiePath, that.cookiePath);
424         } else {
425             return false;
426         }
427     }
428 
429 
430     /**
431      * Return a textual representation of the cookie.
432      * 
433      * @return string.
434      */
435     public String toExternalForm() {
436         CookieSpec spec = null;
437         if (getVersion() > 0) {
438             spec = CookiePolicy.getDefaultSpec(); 
439         } else {
440             spec = CookiePolicy.getCookieSpec(CookiePolicy.NETSCAPE); 
441         }
442         return spec.formatCookie(this); 
443     }
444 
445     /**
446      * <p>Compares two cookies to determine order for cookie header.</p>
447      * <p>Most specific should be first. </p>
448      * <p>This method is implemented so a cookie can be used as a comparator for
449      * a SortedSet of cookies. Specifically it's used above in the 
450      * createCookieHeader method.</p>
451      * @param o1 The first object to be compared
452      * @param o2 The second object to be compared
453      * @return See {@link java.util.Comparator#compare(Object,Object)}
454      */
455     public int compare(Object o1, Object o2) {
456         LOG.trace("enter Cookie.compare(Object, Object)");
457 
458         if (!(o1 instanceof Cookie)) {
459             throw new ClassCastException(o1.getClass().getName());
460         }
461         if (!(o2 instanceof Cookie)) {
462             throw new ClassCastException(o2.getClass().getName());
463         }
464         Cookie c1 = (Cookie) o1;
465         Cookie c2 = (Cookie) o2;
466         if (c1.getPath() == null && c2.getPath() == null) {
467             return 0;
468         } else if (c1.getPath() == null) {
469             // null is assumed to be "/"
470             if (c2.getPath().equals(CookieSpec.PATH_DELIM)) {
471                 return 0;
472             } else {
473                 return -1;
474             }
475         } else if (c2.getPath() == null) {
476             // null is assumed to be "/"
477             if (c1.getPath().equals(CookieSpec.PATH_DELIM)) {
478                 return 0;
479             } else {
480                 return 1;
481             }
482         } else {
483             return c1.getPath().compareTo(c2.getPath());
484         }
485     }
486 
487     /**
488      * Return a textual representation of the cookie.
489      * 
490      * @return string.
491      * 
492      * @see #toExternalForm
493      */
494     public String toString() {
495         return toExternalForm();
496     }
497 
498    // ----------------------------------------------------- Instance Variables
499 
500    /** Comment attribute. */
501    private String  cookieComment;
502 
503    /** Domain attribute. */
504    private String  cookieDomain;
505 
506    /** Expiration {@link Date}. */
507    private Date    cookieExpiryDate;
508 
509    /** Path attribute. */
510    private String  cookiePath;
511 
512    /** My secure flag. */
513    private boolean isSecure;
514 
515    /**
516     * Specifies if the set-cookie header included a Path attribute for this
517     * cookie
518     */
519    private boolean hasPathAttribute = false;
520 
521    /**
522     * Specifies if the set-cookie header included a Domain attribute for this
523     * cookie
524     */
525    private boolean hasDomainAttribute = false;
526 
527    /** The version of the cookie specification I was created from. */
528    private int     cookieVersion = 0;
529 
530    // -------------------------------------------------------------- Constants
531 
532    /** Log object for this class */
533    private static final Log LOG = LogFactory.getLog(Cookie.class);
534 
535 }
536 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/Credentials.html100644 0 0 11755 10661532627 25254 0ustar 0 0 Credentials xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Credentials.java,v 1.9 2004/04/18 23:51:34 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * <p>Authentication credentials.</p>
35   * <p>
36   * This  is just a marker interface, the  current implementation has no methods.
37   * </p>
38   * @author Unascribed
39   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
40   * 
41   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
42   */
43  public interface Credentials {
44  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/DefaultHttpMethodRetryHandler.html100644 0 0 33511 10661532627 30722 0ustar 0 0 DefaultHttpMethodRetryHandler xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/DefaultHttpMethodRetryHandler.java,v 1.3 2004/12/20 11:47:46 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.io.InterruptedIOException;
35  import java.net.NoRouteToHostException;
36  import java.net.UnknownHostException;
37  
38  /**
39   * The default {@link HttpMethodRetryHandler} used by {@link HttpMethod}s.
40   * 
41   * @author Michael Becke
42   * @author <a href="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a>
43   */
44  public class DefaultHttpMethodRetryHandler implements HttpMethodRetryHandler {
45  
46  
47  	private static Class SSL_HANDSHAKE_EXCEPTION = null;
48  	
49  	static {
50  		try {
51  			SSL_HANDSHAKE_EXCEPTION = Class.forName("javax.net.ssl.SSLHandshakeException");
52  		} catch (ClassNotFoundException ignore) {			
53  		}
54  	}
55  	/** the number of times a method will be retried */
56      private int retryCount;
57      
58      /** Whether or not methods that have successfully sent their request will be retried */
59      private boolean requestSentRetryEnabled;
60      
61      /**
62       * Creates a new DefaultHttpMethodRetryHandler.
63       * @param retryCount the number of times a method will be retried
64       * @param requestSentRetryEnabled if true, methods that have successfully sent their request will be retried
65       */
66      public DefaultHttpMethodRetryHandler(int retryCount, boolean requestSentRetryEnabled) {
67          super();
68          this.retryCount = retryCount;
69          this.requestSentRetryEnabled = requestSentRetryEnabled;
70      }
71      
72      /**
73       * Creates a new DefaultHttpMethodRetryHandler that retries up to 3 times
74       * but does not retry methods that have successfully sent their requests.
75       */
76      public DefaultHttpMethodRetryHandler() {
77          this(3, false);
78      }
79      /** 
80       * Used <code>retryCount</code> and <code>requestSentRetryEnabled</code> to determine
81       * if the given method should be retried.
82       * 
83       * @see HttpMethodRetryHandler#retryMethod(HttpMethod, IOException, int)
84       */
85      public boolean retryMethod(
86          final HttpMethod method, 
87          final IOException exception, 
88          int executionCount) {
89          if (method == null) {
90              throw new IllegalArgumentException("HTTP method may not be null");
91          }
92          if (exception == null) {
93              throw new IllegalArgumentException("Exception parameter may not be null");
94          }
95          // HttpMethod interface is the WORST thing ever done to HttpClient
96          if (method instanceof HttpMethodBase) {
97          	if (((HttpMethodBase)method).isAborted()) {
98                  return false;
99          	}
100         }
101         if (executionCount > this.retryCount) {
102             // Do not retry if over max retry count
103             return false;
104         }
105         if (exception instanceof NoHttpResponseException) {
106             // Retry if the server dropped connection on us
107             return true;
108         }
109         if (exception instanceof InterruptedIOException) {
110             // Timeout
111             return false;
112         }
113         if (exception instanceof UnknownHostException) {
114             // Unknown host
115             return false;
116         }
117         if (exception instanceof NoRouteToHostException) {
118             // Host unreachable
119             return false;
120         }
121         if (SSL_HANDSHAKE_EXCEPTION != null && SSL_HANDSHAKE_EXCEPTION.isInstance(exception)) {
122             // SSL handshake exception
123             return false;
124         }
125         if (!method.isRequestSent() || this.requestSentRetryEnabled) {
126             // Retry if the request has not been sent fully or
127             // if it's OK to retry methods that have been sent
128             return true;
129         }
130         // otherwise do not retry
131         return false;
132     }
133     
134     /**
135      * @return <code>true</code> if this handler will retry methods that have 
136      * successfully sent their request, <code>false</code> otherwise
137      */
138     public boolean isRequestSentRetryEnabled() {
139         return requestSentRetryEnabled;
140     }
141 
142     /**
143      * @return the maximum number of times a method will be retried
144      */
145     public int getRetryCount() {
146         return retryCount;
147     }
148 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/DefaultMethodRetryHandler.html100644 0 0 23206 10661532627 30062 0ustar 0 0 DefaultMethodRetryHandler xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/DefaultMethodRetryHandler.java,v 1.4 2004/07/05 22:46:58 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * The default MethodRetryHandler used by HttpMethodBase.
35   * 
36   * @author Michael Becke
37   * 
38   * @see HttpMethodBase#setMethodRetryHandler(MethodRetryHandler)
39   * 
40   * @deprecated use {@link org.apache.commons.httpclient.DefaultHttpMethodRetryHandler}
41   */
42  public class DefaultMethodRetryHandler implements MethodRetryHandler {
43  
44      /** the number of times a method will be retried */
45      private int retryCount;
46      
47      /** Whether or not methods that have successfully sent their request will be retried */
48      private boolean requestSentRetryEnabled;
49      
50      /**
51       */
52      public DefaultMethodRetryHandler() {
53          this.retryCount = 3;
54          this.requestSentRetryEnabled = false;
55      }
56      
57      /** 
58       * Used <code>retryCount</code> and <code>requestSentRetryEnabled</code> to determine
59       * if the given method should be retried.
60       * 
61       * @see MethodRetryHandler#retryMethod(HttpMethod, HttpConnection, HttpRecoverableException, int, boolean)
62       */
63      public boolean retryMethod(
64          HttpMethod method,
65          HttpConnection connection,
66          HttpRecoverableException recoverableException,
67          int executionCount,
68          boolean requestSent
69      ) {
70          return ((!requestSent || requestSentRetryEnabled) && (executionCount <= retryCount));
71      }
72      /**
73       * @return <code>true</code> if this handler will retry methods that have 
74       * successfully sent their request, <code>false</code> otherwise
75       */
76      public boolean isRequestSentRetryEnabled() {
77          return requestSentRetryEnabled;
78      }
79  
80      /**
81       * @return the maximum number of times a method will be retried
82       */
83      public int getRetryCount() {
84          return retryCount;
85      }
86  
87      /**
88       * @param requestSentRetryEnabled a flag indicating if methods that have 
89       * successfully sent their request should be retried
90       */
91      public void setRequestSentRetryEnabled(boolean requestSentRetryEnabled) {
92          this.requestSentRetryEnabled = requestSentRetryEnabled;
93      }
94  
95      /**
96       * @param retryCount the maximum number of times a method can be retried
97       */
98      public void setRetryCount(int retryCount) {
99          this.retryCount = retryCount;
100     }
101 
102 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/Header.html100644 0 0 30527 10661532627 24205 0ustar 0 0 Header xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Header.java,v 1.17 2004/09/15 20:42:17 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * <p>An HTTP header.</p>
35   *
36   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
37   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
38   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
39   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
40   */
41  public class Header extends NameValuePair {
42  
43      // ----------------------------------------------------------- Constructors
44  
45      /**
46       * Autogenerated header flag.
47       */
48      private boolean isAutogenerated = false;
49      
50      /**
51       * Default constructor.
52       */
53      public Header() {
54          this(null, null);
55      }
56  
57      /**
58       * Constructor with name and value
59       *
60       * @param name the header name
61       * @param value the header value
62       */
63      public Header(String name, String value) {
64          super(name, value);
65      }
66  
67      /**
68       * Constructor with name and value
69       *
70       * @param name the header name
71       * @param value the header value
72       * @param isAutogenerated <tt>true</tt> if the header is autogenerated,
73       *  <tt>false</tt> otherwise.
74       * 
75       * @since 3.0
76       */
77      public Header(String name, String value, boolean isAutogenerated) {
78          super(name, value);
79          this.isAutogenerated = isAutogenerated;
80      }
81  
82      // --------------------------------------------------------- Public Methods
83  
84      /**
85       * Returns a {@link String} representation of the header.
86       *
87       * @return stringHEAD
88       */
89      public String toExternalForm() {
90          return ((null == getName() ? "" : getName()) 
91              + ": " 
92              + (null == getValue() ? "" : getValue()) 
93              + "\r\n");
94      }
95  
96      /**
97       * Returns a {@link String} representation of the header.
98       *
99       * @return stringHEAD
100      */
101     public String toString() {
102         return toExternalForm();
103     }
104 
105     /**
106      * Returns an array of {@link HeaderElement}s
107      * constructed from my value.
108      *
109      * @see HeaderElement#parse
110      * @throws HttpException if the header cannot be parsed
111      * @return an array of header elements
112      * 
113      * @deprecated Use #getElements
114      */
115     public HeaderElement[] getValues() throws HttpException {
116         return HeaderElement.parse(getValue());
117     }
118 
119     /**
120      * Returns an array of {@link HeaderElement}s
121      * constructed from my value.
122      *
123      * @see HeaderElement#parseElements(String)
124      * 
125      * @return an array of header elements
126      * 
127      * @since 3.0
128      */
129     public HeaderElement[] getElements() {
130         return HeaderElement.parseElements(getValue());
131     }
132 
133     /**
134      * Returns the value of the auto-generated header flag.
135      * 
136      * @return <tt>true</tt> if the header is autogenerated,
137      *  <tt>false</tt> otherwise.
138      * 
139      * @since 3.0
140      */
141     public boolean isAutogenerated() {
142         return isAutogenerated;
143     }
144 
145 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HeaderElement.html100644 0 0 64676 10661532627 25533 0ustar 0 0 HeaderElement xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HeaderElement.java,v 1.23 2004/05/13 04:03:25 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.util.ArrayList;
34  import java.util.List;
35  
36  import org.apache.commons.httpclient.util.ParameterParser;
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  
40  /**
41   * <p>One element of an HTTP header's value.</p>
42   * <p>
43   * Some HTTP headers (such as the set-cookie header) have values that
44   * can be decomposed into multiple elements.  Such headers must be in the
45   * following form:
46   * </p>
47   * <pre>
48   * header  = [ element ] *( "," [ element ] )
49   * element = name [ "=" [ value ] ] *( ";" [ param ] )
50   * param   = name [ "=" [ value ] ]
51   *
52   * name    = token
53   * value   = ( token | quoted-string )
54   *
55   * token         = 1*&lt;any char except "=", ",", ";", &lt;"&gt; and
56   *                       white space&gt;
57   * quoted-string = &lt;"&gt; *( text | quoted-char ) &lt;"&gt;
58   * text          = any char except &lt;"&gt;
59   * quoted-char   = "\" char
60   * </pre>
61   * <p>
62   * Any amount of white space is allowed between any part of the
63   * header, element or param and is ignored. A missing value in any
64   * element or param will be stored as the empty {@link String};
65   * if the "=" is also missing <var>null</var> will be stored instead.
66   * </p>
67   * <p>
68   * This class represents an individual header element, containing
69   * both a name/value pair (value may be <tt>null</tt>) and optionally
70   * a set of additional parameters.
71   * </p>
72   * <p>
73   * This class also exposes a {@link #parse} method for parsing a
74   * {@link Header} value into an array of elements.
75   * </p>
76   *
77   * @see Header
78   *
79   * @author <a href="mailto:bcholmes@interlog.com">B.C. Holmes</a>
80   * @author <a href="mailto:jericho@thinkfree.com">Park, Sung-Gu</a>
81   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
82   * @author <a href="mailto:oleg@ural.com">Oleg Kalnichevski</a>
83   * 
84   * @since 1.0
85   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
86   */
87  public class HeaderElement extends NameValuePair {
88  
89      // ----------------------------------------------------------- Constructors
90  
91      /**
92       * Default constructor.
93       */
94      public HeaderElement() {
95          this(null, null, null);
96      }
97  
98      /**
99        * Constructor.
100       * @param name my name
101       * @param value my (possibly <tt>null</tt>) value
102       */
103     public HeaderElement(String name, String value) {
104         this(name, value, null);
105     }
106 
107     /**
108      * Constructor with name, value and parameters.
109      *
110      * @param name my name
111      * @param value my (possibly <tt>null</tt>) value
112      * @param parameters my (possibly <tt>null</tt>) parameters
113      */
114     public HeaderElement(String name, String value,
115             NameValuePair[] parameters) {
116         super(name, value);
117         this.parameters = parameters;
118     }
119 
120     /**
121      * Constructor with array of characters.
122      *
123      * @param chars the array of characters
124      * @param offset - the initial offset.
125      * @param length - the length.
126      * 
127      * @since 3.0
128      */
129     public HeaderElement(char[] chars, int offset, int length) {
130         this();
131         if (chars == null) {
132             return;
133         }
134         ParameterParser parser = new ParameterParser();
135         List params = parser.parse(chars, offset, length, ';');
136         if (params.size() > 0) {
137             NameValuePair element = (NameValuePair) params.remove(0);
138             setName(element.getName());  
139             setValue(element.getValue());
140             if (params.size() > 0) {
141                 this.parameters = (NameValuePair[])
142                     params.toArray(new NameValuePair[params.size()]);    
143             }
144         }
145     }
146 
147     /**
148      * Constructor with array of characters.
149      *
150      * @param chars the array of characters
151      * 
152      * @since 3.0
153      */
154     public HeaderElement(char[] chars) {
155         this(chars, 0, chars.length);
156     }
157 
158     // -------------------------------------------------------- Constants
159 
160     /** Log object for this class. */
161     private static final Log LOG = LogFactory.getLog(HeaderElement.class);
162 
163     // ----------------------------------------------------- Instance Variables
164 
165     /** My parameters, if any. */
166     private NameValuePair[] parameters = null;
167 
168     // ------------------------------------------------------------- Properties
169 
170     /**
171      * Get parameters, if any.
172      *
173      * @since 2.0
174      * @return parameters as an array of {@link NameValuePair}s
175      */
176     public NameValuePair[] getParameters() {
177         return this.parameters;
178     }
179 
180     // --------------------------------------------------------- Public Methods
181 
182     /**
183      * This parses the value part of a header. The result is an array of
184      * HeaderElement objects.
185      *
186      * @param headerValue  the array of char representation of the header value
187      *                     (as received from the web server).
188      * @return array of {@link HeaderElement}s.
189      * 
190      * @since 3.0
191      */
192     public static final HeaderElement[] parseElements(char[] headerValue) {
193             
194         LOG.trace("enter HeaderElement.parseElements(char[])");
195 
196         if (headerValue == null) {
197             return new HeaderElement[] {};
198         }
199         List elements = new ArrayList(); 
200         
201         int i = 0;
202         int from = 0;
203         int len = headerValue.length;
204         boolean qouted = false;
205         while (i < len) {
206             char ch = headerValue[i];
207             if (ch == '"') {
208                 qouted = !qouted;
209             }
210             HeaderElement element = null;
211             if ((!qouted) && (ch == ',')) {
212                 element = new HeaderElement(headerValue, from, i);
213                 from = i + 1;
214             } else if (i == len - 1) {
215                 element = new HeaderElement(headerValue, from, len);
216             }
217             if ((element != null) && (element.getName() != null)) {
218                 elements.add(element);
219             }
220             i++;
221         }
222         return (HeaderElement[])
223             elements.toArray(new HeaderElement[elements.size()]);
224     }
225 
226     /**
227      * This parses the value part of a header. The result is an array of
228      * HeaderElement objects.
229      *
230      * @param headerValue  the string representation of the header value
231      *                     (as received from the web server).
232      * @return array of {@link HeaderElement}s.
233      * 
234      * @since 3.0
235      */
236     public static final HeaderElement[] parseElements(String headerValue) {
237             
238         LOG.trace("enter HeaderElement.parseElements(String)");
239 
240         if (headerValue == null) {
241             return new HeaderElement[] {};
242         }
243         return parseElements(headerValue.toCharArray());
244     }
245 
246     /**
247      * This parses the value part of a header. The result is an array of
248      * HeaderElement objects.
249      *
250      * @param headerValue  the string representation of the header value
251      *                     (as received from the web server).
252      * @return array of {@link HeaderElement}s.
253      * @throws HttpException if the above syntax rules are violated.
254      * 
255      * @deprecated Use #parseElements(String).
256      */
257     public static final HeaderElement[] parse(String headerValue)
258         throws HttpException {
259             
260         LOG.trace("enter HeaderElement.parse(String)");
261 
262         if (headerValue == null) {
263             return new HeaderElement[] {};
264         }
265         return parseElements(headerValue.toCharArray());
266     }
267          
268 
269     /**
270      * Returns parameter with the given name, if found. Otherwise null 
271      * is returned
272      *
273      * @param name The name to search by.
274      * @return NameValuePair parameter with the given name
275      */
276 
277     public NameValuePair getParameterByName(String name) {
278 
279         LOG.trace("enter HeaderElement.getParameterByName(String)");
280 
281         if (name == null) {
282             throw new IllegalArgumentException("Name may not be null");
283         } 
284         NameValuePair found = null;
285         NameValuePair parameters[] = getParameters();
286         if (parameters != null) {
287             for (int i = 0; i < parameters.length; i++) {
288                 NameValuePair current = parameters[ i ];
289                 if (current.getName().equalsIgnoreCase(name)) {
290                     found = current;
291                     break;
292                 }
293             }
294         }
295         return found;
296     }
297 
298 }
299 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HeaderGroup.html100644 0 0 46410 10661532627 25220 0ustar 0 0 HeaderGroup xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HeaderGroup.java,v 1.8 2004/05/13 04:03:25 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.util.ArrayList;
34  import java.util.Iterator;
35  import java.util.List;
36  
37  /**
38   * A class for combining a set of headers.  This class allows for multiple
39   * headers with the same name and keeps track of the order in which headers were
40   * added.
41   * 
42   * @author Michael Becke
43   * 
44   * @since 2.0beta1
45   */
46  public class HeaderGroup {
47  
48      /** The list of headers for this group, in the order in which they were added */
49      private List headers;
50  
51      /**
52       * Constructor for HeaderGroup.
53       */
54      public HeaderGroup() {
55          this.headers = new ArrayList();
56      }
57      
58      /**
59       * Removes any contained headers.
60       */
61      public void clear() {
62          headers.clear();
63      }
64      
65      /**
66       * Adds the given header to the group.  The order in which this header was
67       * added is preserved.
68       * 
69       * @param header the header to add
70       */
71      public void addHeader(Header header) {
72          headers.add(header);
73      }
74      
75      /**
76       * Removes the given header.
77       *
78       * @param header the header to remove
79       */
80      public void removeHeader(Header header) {
81          headers.remove(header);
82      }
83  
84      /**
85       * Sets all of the headers contained within this group overriding any
86       * existing headers. The headers are added in the order in which they appear
87       * in the array.
88       * 
89       * @param headers the headers to set
90       */
91      public void setHeaders(Header[] headers) {
92          clear();
93          
94          for (int i = 0; i < headers.length; i++) {
95              addHeader(headers[i]);
96          }
97      }
98      
99      /**
100      * Gets a header representing all of the header values with the given name.
101      * If more that one header with the given name exists the values will be
102      * combined with a "," as per RFC 2616.
103      * 
104      * <p>Header name comparison is case insensitive.
105      * 
106      * @param name the name of the header(s) to get
107      * @return a header with a condensed value or <code>null</code> if no
108      * headers by the given name are present
109      */
110     public Header getCondensedHeader(String name) {
111         Header[] headers = getHeaders(name);
112         
113         if (headers.length == 0) {
114             return null;   
115         } else if (headers.length == 1) {
116             return new Header(headers[0].getName(), headers[0].getValue());
117         } else {
118             StringBuffer valueBuffer = new StringBuffer(headers[0].getValue());
119             
120             for (int i = 1; i < headers.length; i++) {
121                 valueBuffer.append(", ");
122                 valueBuffer.append(headers[i].getValue());
123             }
124             
125             return new Header(name.toLowerCase(), valueBuffer.toString());
126         }
127     }
128     
129     /**
130      * Gets all of the headers with the given name.  The returned array
131      * maintains the relative order in which the headers were added.  
132      * 
133      * <p>Header name comparison is case insensitive.
134      * 
135      * @param name the name of the header(s) to get
136      * 
137      * @return an array of length >= 0
138      */
139     public Header[] getHeaders(String name) {
140         ArrayList headersFound = new ArrayList();
141         
142         for (Iterator headerIter = headers.iterator(); headerIter.hasNext();) {
143             Header header = (Header) headerIter.next();
144             if (header.getName().equalsIgnoreCase(name)) {
145                 headersFound.add(header);
146             }
147         }
148         
149         return (Header[]) headersFound.toArray(new Header[headersFound.size()]);
150     }
151     
152     /**
153      * Gets the first header with the given name.
154      * 
155      * <p>Header name comparison is case insensitive.
156      * 
157      * @param name the name of the header to get
158      * @return the first header or <code>null</code>
159      */
160     public Header getFirstHeader(String name) {
161         for (Iterator headerIter = headers.iterator(); headerIter.hasNext();) {
162             Header header = (Header) headerIter.next();
163             if (header.getName().equalsIgnoreCase(name)) {
164                 return header;
165             }
166         }
167         
168         return null;                
169     }
170     
171     /**
172      * Gets the last header with the given name.
173      *
174      * <p>Header name comparison is case insensitive.
175      *
176      * @param name the name of the header to get
177      * @return the last header or <code>null</code>
178      */
179     public Header getLastHeader(String name) {
180         // start at the end of the list and work backwards
181         for (int i = headers.size() - 1; i >= 0; i--) {
182             Header header = (Header) headers.get(i);
183             if (header.getName().equalsIgnoreCase(name)) {
184                 return header;
185             }            
186         }
187         
188         return null;        
189     }
190     
191     /**
192      * Gets all of the headers contained within this group.
193      * 
194      * @return an array of length >= 0
195      */
196     public Header[] getAllHeaders() {
197         return (Header[]) headers.toArray(new Header[headers.size()]);
198     }
199     
200     /**
201      * Tests if headers with the given name are contained within this group.
202      * 
203      * <p>Header name comparison is case insensitive.
204      * 
205      * @param name the header name to test for
206      * @return <code>true</code> if at least one header with the name is
207      * contained, <code>false</code> otherwise
208      */
209     public boolean containsHeader(String name) {
210         for (Iterator headerIter = headers.iterator(); headerIter.hasNext();) {
211             Header header = (Header) headerIter.next();
212             if (header.getName().equalsIgnoreCase(name)) {
213                 return true;
214             }
215         }
216         
217         return false;
218     }
219 
220     /**
221      * Returns an iterator over this group of headers.
222      * 
223      * @return iterator over this group of headers.
224      * 
225      * @since 3.0
226      */
227     public Iterator getIterator() {
228         return this.headers.iterator(); 
229     }
230 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HostConfiguration.html100644 0 0 131240 10661532627 26474 0ustar 0 0 HostConfiguration xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HostConfiguration.java,v 1.23 2005/01/14 21:16:40 olegk Exp $
3    * $Revision: 510585 $
4    * $Date: 2007-02-22 17:52:16 +0100 (Thu, 22 Feb 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import org.apache.commons.httpclient.params.HostParams;
34  import org.apache.commons.httpclient.protocol.Protocol;
35  import org.apache.commons.httpclient.util.LangUtils;
36  
37  import java.net.InetAddress;
38  
39  /**
40   * Holds all of the variables needed to describe an HTTP connection to a host.  This includes 
41   * remote host, port and protocol, proxy host and port, local address, and virtual host.
42   * 
43   * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
44   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
45   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
46   * @author Laura Werner
47   * 
48   * @since 2.0 
49   */
50  public class HostConfiguration implements Cloneable {
51  
52      /**
53       * A value to represent any host configuration, instead of using something like
54       * <code>null</code>. This value should be treated as immutable and only used in 
55       * lookups and other such places to represent "any" host config.
56       */
57      public static final HostConfiguration ANY_HOST_CONFIGURATION = new HostConfiguration();
58  
59      /** The host to use. */
60      private HttpHost host = null;
61  
62      /** The host name of the proxy server */
63      private ProxyHost proxyHost = null;
64  
65      /** The local address to use when creating the socket, or null to use the default */
66      private InetAddress localAddress = null;
67  
68      /** Parameters specific to this host */
69      private HostParams params = new HostParams();
70  
71      /**
72       * Constructor for HostConfiguration.
73       */
74      public HostConfiguration() {
75          super();
76      }
77      
78      /**
79       * Copy constructor for HostConfiguration
80       * 
81       * @param hostConfiguration the hostConfiguration to copy
82       */
83      public HostConfiguration (final HostConfiguration hostConfiguration) {
84          init(hostConfiguration);        
85      }
86  
87  	private void init(final HostConfiguration hostConfiguration) {
88  		// wrap all of the assignments in a synchronized block to avoid
89          // having to negotiate the monitor for each method call
90          synchronized (hostConfiguration) {
91              try {
92                  if (hostConfiguration.host != null) {
93                      this.host = (HttpHost) hostConfiguration.host.clone();
94                  } else {
95                      this.host = null;
96                  }
97                  if (hostConfiguration.proxyHost != null) {
98                      this.proxyHost = (ProxyHost) hostConfiguration.proxyHost.clone();
99                  } else {
100                     this.proxyHost = null;
101                 }
102                 this.localAddress = hostConfiguration.getLocalAddress();
103                 this.params = (HostParams)hostConfiguration.getParams().clone();
104             } catch (CloneNotSupportedException e) {
105                 throw new IllegalArgumentException("Host configuration could not be cloned");
106             }
107         }        
108     }
109 
110     /**
111      * @see java.lang.Object#clone()
112      */
113     public Object clone() {
114     	HostConfiguration copy;
115 		try {
116 			copy = (HostConfiguration) super.clone();
117 		} catch (CloneNotSupportedException e) {
118             throw new IllegalArgumentException("Host configuration could not be cloned");
119 		}
120     	copy.init(this);
121         return copy;
122     }    
123     
124     /**
125      * @see java.lang.Object#toString()
126      */
127     public synchronized String toString() {
128         
129         boolean appendComma = false;
130         StringBuffer b = new StringBuffer(50);        
131         b.append("HostConfiguration[");
132         
133         if (this.host != null) {
134             appendComma = true;
135             b.append("host=").append(this.host);
136         }
137         if (this.proxyHost != null) {
138             if (appendComma) {
139                 b.append(", ");
140             } else {
141                 appendComma = true;
142             }
143             b.append("proxyHost=").append(this.proxyHost);
144         }
145         if (this.localAddress != null) {
146             if (appendComma) {
147                 b.append(", ");
148             } else {
149                 appendComma = true;
150             }
151             b.append("localAddress=").append(this.localAddress);
152             if (appendComma) {
153                 b.append(", ");
154             } else {
155                 appendComma = true;
156             }
157             b.append("params=").append(this.params);
158         }
159         b.append("]");
160         return b.toString();
161     }    
162     
163     /**
164      * Tests if the host configuration equals the configuration set on the
165      * connection. True only if the host, port, protocol, local address and virtual address
166      * are equal.  If no host configuration has been set false will be returned.
167      * 
168      * @param connection the connection to test against
169      * @return <code>true</code> if the connection's host information equals that of this
170      * configuration
171      * 
172      * @see #proxyEquals(HttpConnection)
173      */
174     public synchronized boolean hostEquals(final HttpConnection connection) {
175         if (connection == null) {
176             throw new IllegalArgumentException("Connection may not be null");
177         }
178         if (this.host != null) {
179             if (!this.host.getHostName().equalsIgnoreCase(connection.getHost())) {
180                 return false;
181             }
182             if (this.host.getPort() != connection.getPort()) {
183                 return false;
184             }
185             if (!this.host.getProtocol().equals(connection.getProtocol())) {
186                 return false;
187             }
188             if (this.localAddress != null) {
189                 if (!this.localAddress.equals(connection.getLocalAddress())) {
190                     return false;
191                 }
192             } else {
193                 if (connection.getLocalAddress() != null) {
194                     return false; 
195                 }
196             }
197             return true;
198         } else {
199             return false;   
200         }
201     }
202 
203     /**
204      * Tests if the proxy configuration equals the configuration set on the
205      * connection. True only if the proxyHost and proxyPort are equal.
206      *
207      * @param connection the connection to test against
208      * @return <code>true</code> if the connection's proxy information equals that of this
209      * configuration
210      *
211      * @see #hostEquals(HttpConnection)
212      */
213     public synchronized boolean proxyEquals(final HttpConnection connection) {
214         if (connection == null) {
215             throw new IllegalArgumentException("Connection may not be null");
216         }
217         if (this.proxyHost != null) {
218             return
219                 this.proxyHost.getHostName().equalsIgnoreCase(connection.getProxyHost())
220                 && this.proxyHost.getPort() == connection.getProxyPort();
221         } else {
222             return connection.getProxyHost() == null;
223         }
224     }    
225     
226     /**
227      * Returns true if the host is set.
228      * @return <code>true</code> if the host is set.
229      * 
230      * @deprecated no longer used
231      */
232     public synchronized boolean isHostSet() {
233         return this.host != null;
234     }
235 
236     /**
237      * Sets the given host
238      * 
239      * @param host the host
240      */
241     public synchronized void setHost(final HttpHost host) {
242         this.host = host;
243     }
244     
245     /**
246      * Sets the given host, port and protocol
247      * 
248      * @param host the host(IP or DNS name)
249      * @param port The port
250      * @param protocol The protocol.
251      */
252     public synchronized void setHost(final String host, int port, final String protocol) {
253         this.host = new HttpHost(host, port, Protocol.getProtocol(protocol));
254     }
255     
256     /**
257      * Sets the given host, virtual host, port and protocol.
258      * 
259      * @param host the host(IP or DNS name)
260      * @param virtualHost the virtual host name or <code>null</code>
261      * @param port the host port or -1 to use protocol default
262      * @param protocol the protocol
263      * 
264      * @deprecated #setHost(String, int, Protocol)
265      */
266     public synchronized void setHost(final String host, final String virtualHost, int port, 
267         final Protocol protocol) {
268         setHost(host, port, protocol);
269         this.params.setVirtualHost(virtualHost);
270     }
271 
272     /**
273      * Sets the given host, port and protocol.
274      *   
275      * @param host the host(IP or DNS name)
276      * @param port The port
277      * @param protocol the protocol
278      */
279     public synchronized void setHost(final String host, int port, final Protocol protocol) {
280         if (host == null) {
281             throw new IllegalArgumentException("host must not be null");   
282         }
283         if (protocol == null) {
284             throw new IllegalArgumentException("protocol must not be null");   
285         }
286         this.host = new HttpHost(host, port, protocol);
287     }
288 
289     /**
290      * Sets the given host and port.  Uses the default protocol "http".
291      * 
292      * @param host the host(IP or DNS name)
293      * @param port The port
294      */
295     public synchronized void setHost(final String host, int port) {
296         setHost(host, port, Protocol.getProtocol("http"));
297     }
298     
299     /**
300      * Set the given host. Uses the default protocol("http") and its port.
301      * 
302      * @param host The host(IP or DNS name).
303      */
304     public synchronized void setHost(final String host) {
305         Protocol defaultProtocol = Protocol.getProtocol("http"); 
306         setHost(host, defaultProtocol.getDefaultPort(), defaultProtocol);
307     }
308     
309     /**
310      * Sets the protocol, host and port from the given URI.
311      * @param uri the URI.
312      */
313     public synchronized void setHost(final URI uri) {
314         try {
315             setHost(uri.getHost(), uri.getPort(), uri.getScheme());
316         } catch (URIException e) {
317             throw new IllegalArgumentException(e.toString());
318         }
319     }
320 
321     /**
322      * Return the host url.
323      * 
324      * @return The host url.
325      */
326     public synchronized String getHostURL() {
327         if (this.host == null) {
328             throw new IllegalStateException("Host must be set to create a host URL");   
329         } else {
330             return this.host.toURI();
331         }
332     }
333 
334     /**
335      * Returns the host.
336      * 
337      * @return the host(IP or DNS name), or <code>null</code> if not set
338      * 
339      * @see #isHostSet()
340      */
341     public synchronized String getHost() {
342         if (this.host != null) {
343             return this.host.getHostName();
344         } else {
345             return null;
346         }
347     }
348 
349     /**
350      * Returns the virtual host.
351      * 
352      * @return the virtual host name, or <code>null</code> if not set
353      * 
354      * @deprecated use HostParams
355      */
356     public synchronized String getVirtualHost() {
357     	return this.params.getVirtualHost();
358     }
359 
360     /**
361      * Returns the port.
362      * 
363      * @return the host port, or <code>-1</code> if not set
364      * 
365      * @see #isHostSet()
366      */
367     public synchronized int getPort() {
368         if (this.host != null) {
369             return this.host.getPort();
370         } else {
371             return -1;
372         }
373     }
374 
375     /**
376      * Returns the protocol.
377      * @return The protocol.
378      */
379     public synchronized Protocol getProtocol() {
380         if (this.host != null) {
381             return this.host.getProtocol();
382         } else {
383             return null;
384         }
385     }
386 
387     /**
388      * Tests if the proxy host/port have been set.
389      * 
390      * @return <code>true</code> if a proxy server has been set.
391      * 
392      * @see #setProxy(String, int)
393      * 
394      * @deprecated no longer used
395      */    
396     public synchronized boolean isProxySet() {
397         return this.proxyHost != null;   
398     }
399 
400     /**
401      * Sets the given proxy host
402      * 
403      * @param proxyHost the proxy host
404      */
405     public synchronized void setProxyHost(final ProxyHost proxyHost) {
406         this.proxyHost = proxyHost;
407     }
408     
409     /**
410      * Set the proxy settings.
411      * @param proxyHost The proxy host
412      * @param proxyPort The proxy port
413      */
414     public synchronized void setProxy(final String proxyHost, int proxyPort) {
415         this.proxyHost = new ProxyHost(proxyHost, proxyPort); 
416     }
417 
418     /**
419      * Returns the proxyHost.
420      * 
421      * @return the proxy host, or <code>null</code> if not set
422      * 
423      * @see #isProxySet()
424      */
425     public synchronized String getProxyHost() {
426         if (this.proxyHost != null) {
427             return this.proxyHost.getHostName();
428         } else {
429             return null;
430         }
431     }
432 
433     /**
434      * Returns the proxyPort.
435      * 
436      * @return the proxy port, or <code>-1</code> if not set
437      * 
438      * @see #isProxySet()
439      */
440     public synchronized int getProxyPort() {
441         if (this.proxyHost != null) {
442             return this.proxyHost.getPort();
443         } else {
444             return -1;
445         }
446     }
447 
448     /**
449      * Set the local address to be used when creating connections.
450      * If this is unset, the default address will be used.
451      * This is useful for specifying the interface to use on multi-homed or clustered systems.
452      * 
453      * @param localAddress the local address to use
454      */
455     
456     public synchronized void setLocalAddress(InetAddress localAddress) {
457         this.localAddress = localAddress;
458     }
459 
460     /**
461      * Return the local address to be used when creating connections.
462      * If this is unset, the default address should be used.
463      * 
464      * @return the local address to be used when creating Sockets, or <code>null</code>
465      */
466     
467     public synchronized InetAddress getLocalAddress() {
468         return this.localAddress;
469     }
470     
471     /**
472      * Returns {@link HostParams HTTP protocol parameters} associated with this host.
473      *
474      * @return HTTP parameters.
475      *
476      * @since 3.0
477      */
478     public HostParams getParams() {
479         return this.params;
480     }
481 
482     /**
483      * Assigns {@link HostParams HTTP protocol parameters} specific to this host.
484      * 
485      * @since 3.0
486      * 
487      * @see HostParams
488      */
489     public void setParams(final HostParams params) {
490         if (params == null) {
491             throw new IllegalArgumentException("Parameters may not be null");
492         }
493         this.params = params;
494     }
495 
496     /**
497      * @see java.lang.Object#equals(java.lang.Object)
498      */
499     public synchronized boolean equals(final Object o) {
500         if (o instanceof HostConfiguration) {
501             // shortcut if we're comparing with ourselves
502             if (o == this) { 
503                 return true;
504             }
505             HostConfiguration that = (HostConfiguration) o;
506             return LangUtils.equals(this.host, that.host)
507                 && LangUtils.equals(this.proxyHost, that.proxyHost)
508                 && LangUtils.equals(this.localAddress, that.localAddress);
509         } else {
510             return false;
511         }
512         
513     }
514 
515     /**
516      * @see java.lang.Object#hashCode()
517      */
518     public synchronized int hashCode() {
519         int hash = LangUtils.HASH_SEED;
520         hash = LangUtils.hashCode(hash, this.host);
521         hash = LangUtils.hashCode(hash, this.proxyHost);
522         hash = LangUtils.hashCode(hash, this.localAddress);
523         return hash;
524     }
525 
526 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpClient.html100644 0 0 131716 10661532627 25115 0ustar 0 0 HttpClient xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpClient.java,v 1.98 2004/10/07 16:14:15 olegk Exp $
3    * $Revision: 509577 $
4    * $Date: 2007-02-20 15:28:18 +0100 (Tue, 20 Feb 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.security.Provider;
35  import java.security.Security;
36  
37  import org.apache.commons.httpclient.params.HttpClientParams;
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  
41  /**
42   * <p>
43   * An HTTP "user-agent", containing an {@link HttpState HTTP state} and
44   * one or more {@link HttpConnection HTTP connections}, to which
45   * {@link HttpMethod HTTP methods} can be applied.
46   * </p>
47   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
48   * @author <a href="mailto:rwaldhoff@apache.org">Rodney Waldhoff</a>
49   * @author Sean C. Sullivan
50   * @author <a href="mailto:dion@apache.org">dIon Gillard</a>
51   * @author Ortwin Gl?ck
52   * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
53   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
54   * @author Sam Maloney
55   * @author Laura Werner
56   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
57   * 
58   * @version $Revision: 509577 $ $Date: 2007-02-20 15:28:18 +0100 (Tue, 20 Feb 2007) $
59   */
60  public class HttpClient {
61  
62  
63      // -------------------------------------------------------------- Constants
64  
65      /** Log object for this class. */
66      private static final Log LOG = LogFactory.getLog(HttpClient.class);
67  
68      static {
69          
70          if (LOG.isDebugEnabled()) {
71              try {
72                  LOG.debug("Java version: " + System.getProperty("java.version"));
73                  LOG.debug("Java vendor: " + System.getProperty("java.vendor"));
74                  LOG.debug("Java class path: " + System.getProperty("java.class.path"));
75                  LOG.debug("Operating system name: " + System.getProperty("os.name"));
76                  LOG.debug("Operating system architecture: " + System.getProperty("os.arch"));
77                  LOG.debug("Operating system version: " + System.getProperty("os.version"));
78  
79                  Provider[] providers = Security.getProviders();
80                  for (int i = 0; i < providers.length; i++) {
81                      Provider provider = providers[i];
82                      LOG.debug(provider.getName() + " " + provider.getVersion()
83                         + ": " + provider.getInfo());   
84                  }
85              } catch (SecurityException ignore) {
86              }
87          }
88      }
89      // ----------------------------------------------------------- Constructors
90  
91      /**
92       * Creates an instance of HttpClient using default {@link HttpClientParams parameter set}.
93       * 
94       * @see HttpClientParams
95       */
96      public HttpClient() {
97          this(new HttpClientParams());
98      }
99  
100     /**
101      * Creates an instance of HttpClient using the given 
102      * {@link HttpClientParams parameter set}.
103      * 
104      * @param params The {@link HttpClientParams parameters} to use.
105      * 
106      * @see HttpClientParams
107      * 
108      * @since 3.0
109      */
110     public HttpClient(HttpClientParams params) {
111         super();
112         if (params == null) {
113             throw new IllegalArgumentException("Params may not be null");  
114         }
115         this.params = params;
116         this.httpConnectionManager = null;
117         Class clazz = params.getConnectionManagerClass();
118         if (clazz != null) {
119             try {
120                 this.httpConnectionManager = (HttpConnectionManager) clazz.newInstance();
121             } catch (Exception e) {
122                 LOG.warn("Error instantiating connection manager class, defaulting to"
123                     + " SimpleHttpConnectionManager", 
124                     e);
125             }
126         }
127         if (this.httpConnectionManager == null) {
128             this.httpConnectionManager = new SimpleHttpConnectionManager();
129         }
130         if (this.httpConnectionManager != null) {
131             this.httpConnectionManager.getParams().setDefaults(this.params);
132         }
133     }
134 
135     /**
136      * Creates an instance of HttpClient with a user specified 
137      * {@link HttpClientParams parameter set} and 
138      * {@link HttpConnectionManager HTTP connection manager}.
139      * 
140      * @param params The {@link HttpClientParams parameters} to use.
141      * @param httpConnectionManager The {@link HttpConnectionManager connection manager}
142      * to use.
143      * 
144      * @since 3.0
145      */
146     public HttpClient(HttpClientParams params, HttpConnectionManager httpConnectionManager) {
147         super();
148         if (httpConnectionManager == null) {
149             throw new IllegalArgumentException("httpConnectionManager cannot be null");  
150         }
151         if (params == null) {
152             throw new IllegalArgumentException("Params may not be null");  
153         }
154         this.params = params; 
155         this.httpConnectionManager = httpConnectionManager;
156         this.httpConnectionManager.getParams().setDefaults(this.params);
157     }
158     
159     /**
160      * Creates an instance of HttpClient with a user specified 
161      * {@link HttpConnectionManager HTTP connection manager}.
162      * 
163      * @param httpConnectionManager The {@link HttpConnectionManager connection manager}
164      * to use.
165      * 
166      * @since 2.0
167      */
168     public HttpClient(HttpConnectionManager httpConnectionManager) {
169         this(new HttpClientParams(), httpConnectionManager);
170     }
171     
172     // ----------------------------------------------------- Instance Variables
173 
174     /** 
175      * The {@link HttpConnectionManager connection manager} being used to manage
176      * connections for this HttpClient
177      */
178     private HttpConnectionManager httpConnectionManager;
179 
180     /**
181      * The {@link HttpState HTTP state} associated with this HttpClient.
182      */
183     private HttpState state = new HttpState();
184     
185     /**
186      * The {@link HttpClientParams collection of parameters} associated with this HttpClient.
187      */
188     private HttpClientParams params = null; 
189 
190     /** 
191      * The {@link HostConfiguration host configuration} associated with
192      * the HttpClient
193      */
194     private HostConfiguration hostConfiguration = new HostConfiguration();
195     
196     // ------------------------------------------------------------- Properties
197 
198     /**
199      * Returns {@link HttpState HTTP state} associated with the HttpClient.
200      *
201      * @see #setState(HttpState)
202      * @return the shared client state
203      */
204     public synchronized HttpState getState() {
205         return state;
206     }
207 
208     /**
209      * Assigns {@link HttpState HTTP state} for the HttpClient.
210      *
211      * @see #getState()
212      * @param state the new {@link HttpState HTTP state} for the client
213      */
214     public synchronized void setState(HttpState state) {
215         this.state = state;
216     }
217 
218     /**
219      * Defines how strictly the method follows the HTTP protocol specification  
220      * (see RFC 2616 and other relevant RFCs). 
221      * 
222      * In the strict mode the method precisely
223      * implements the requirements of the specification, whereas in non-strict mode 
224      * it attempts to mimic the exact behaviour of commonly used HTTP agents, 
225      * which many HTTP servers expect.
226      * 
227      * @param strictMode <tt>true</tt> for strict mode, <tt>false</tt> otherwise
228      *
229      * @see #isStrictMode()
230      *
231      * @deprecated Use {@link HttpClientParams#setParameter(String, Object)}
232      * to exercise a more granular control over HTTP protocol strictness.
233      */
234     public synchronized void setStrictMode(boolean strictMode) {
235         if (strictMode) {
236             this.params.makeStrict();
237         } else {
238             this.params.makeLenient();
239         }
240     }
241 
242     /**
243      * Returns the value of the strict mode flag.
244      * 
245      * @return <tt>true</tt> if strict mode is enabled, <tt>false</tt> otherwise
246      *
247      * @see #setStrictMode(boolean)
248      *
249      * @deprecated Use 
250      * {@link org.apache.commons.httpclient.params.HttpClientParams#getParameter(String)} 
251      * to exercise a more granular control over HTTP protocol strictness.
252      */
253     public synchronized boolean isStrictMode() {
254         return false;
255     }
256 
257     /**
258      * Sets the socket timeout (<tt>SO_TIMEOUT</tt>) in milliseconds which is the 
259      * timeout for waiting for data. A timeout value of zero is interpreted as an 
260      * infinite timeout.
261      *
262      * @param newTimeoutInMilliseconds Timeout in milliseconds
263      * 
264      * @deprecated Use 
265      * {@link org.apache.commons.httpclient.params.HttpConnectionManagerParams#setSoTimeout(int)},
266      * {@link HttpConnectionManager#getParams()}.
267      *
268      */
269     public synchronized void setTimeout(int newTimeoutInMilliseconds) {
270         this.params.setSoTimeout(newTimeoutInMilliseconds);
271     }
272 
273     /**
274      * Sets the timeout in milliseconds used when retrieving an 
275      * {@link HttpConnection HTTP connection} from the
276      * {@link HttpConnectionManager HTTP connection manager}.
277      * 
278      * @param timeout the timeout in milliseconds
279      * 
280      * @see HttpConnectionManager#getConnection(HostConfiguration, long)
281      * 
282      * @deprecated Use 
283      * {@link org.apache.commons.httpclient.params.HttpClientParams#setConnectionManagerTimeout(long)},
284      * {@link HttpClient#getParams()}
285      */
286     public synchronized void setHttpConnectionFactoryTimeout(long timeout) {
287         this.params.setConnectionManagerTimeout(timeout);
288     }
289 
290     /**
291      * Sets the timeout until a connection is etablished. A value of zero 
292      * means the timeout is not used. The default value is zero.
293      * 
294      * @see HttpConnection#setConnectionTimeout(int)
295      * @param newTimeoutInMilliseconds Timeout in milliseconds.
296      * 
297      * @deprecated Use 
298      * {@link org.apache.commons.httpclient.params.HttpConnectionManagerParams#setConnectionTimeout(int)},
299      * {@link HttpConnectionManager#getParams()}.
300      */
301     public synchronized void setConnectionTimeout(int newTimeoutInMilliseconds) {
302        this.httpConnectionManager.getParams().setConnectionTimeout(newTimeoutInMilliseconds);
303     }
304 
305     // --------------------------------------------------------- Public Methods
306 
307    /**
308      * Executes the given {@link HttpMethod HTTP method}.
309      *
310      * @param method the {@link HttpMethod HTTP method} to execute.
311      * @return the method's response code
312      *
313      * @throws IOException If an I/O (transport) error occurs. Some transport exceptions
314      *                     can be recovered from.      
315      * @throws HttpException  If a protocol exception occurs. Usually protocol exceptions 
316      *                    cannot be recovered from.
317      */
318     public int executeMethod(HttpMethod method)
319         throws IOException, HttpException  {
320             
321         LOG.trace("enter HttpClient.executeMethod(HttpMethod)");
322         // execute this method and use its host configuration, if it has one
323         return executeMethod(null, method, null);
324     }
325 
326     /**
327     * Executes the given {@link HttpMethod HTTP method} using custom 
328     * {@link HostConfiguration host configuration}.
329     *
330     * @param hostConfiguration The {@link HostConfiguration host configuration} to use.
331      * If <code>null</code>, the host configuration returned by {@link #getHostConfiguration} will be used.
332     * @param method the {@link HttpMethod HTTP method} to execute.
333     * @return the method's response code
334     *
335     * @throws IOException If an I/O (transport) error occurs. Some transport exceptions
336     *                     can be recovered from.
337     * @throws HttpException  If a protocol exception occurs. Usually protocol exceptions 
338     *                    cannot be recovered from.
339     * @since 2.0
340     */
341     public int executeMethod(final HostConfiguration hostConfiguration, final HttpMethod method)
342         throws IOException, HttpException {
343     
344         LOG.trace("enter HttpClient.executeMethod(HostConfiguration,HttpMethod)");
345 
346         return executeMethod(hostConfiguration, method, null); 
347     }
348     
349 
350     
351     /**
352      * Executes the given {@link HttpMethod HTTP method} using the given custom 
353      * {@link HostConfiguration host configuration} with the given custom 
354      * {@link HttpState HTTP state}.
355      *
356      * @param hostconfig The {@link HostConfiguration host configuration} to use.
357      * If <code>null</code>, the host configuration returned by {@link #getHostConfiguration} will be used.
358      * @param method the {@link HttpMethod HTTP method} to execute.
359      * @param state the {@link HttpState HTTP state} to use when executing the method.
360      * If <code>null</code>, the state returned by {@link #getState} will be used.
361      *
362      * @return the method's response code
363      *
364      * @throws IOException If an I/O (transport) error occurs. Some transport exceptions
365      *                     can be recovered from.
366      * @throws HttpException  If a protocol exception occurs. Usually protocol exceptions 
367      *                    cannot be recovered from.
368      * @since 2.0
369      */
370     public int executeMethod(HostConfiguration hostconfig, 
371         final HttpMethod method, final HttpState state)
372         throws IOException, HttpException  {
373             
374         LOG.trace("enter HttpClient.executeMethod(HostConfiguration,HttpMethod,HttpState)");
375 
376         if (method == null) {
377             throw new IllegalArgumentException("HttpMethod parameter may not be null");
378         }
379         HostConfiguration defaulthostconfig = getHostConfiguration();
380         if (hostconfig == null) {
381             hostconfig = defaulthostconfig;
382         }
383         URI uri = method.getURI(); 
384         if (hostconfig == defaulthostconfig || uri.isAbsoluteURI()) {
385             // make a deep copy of the host defaults
386             hostconfig = (HostConfiguration) hostconfig.clone();
387             if (uri.isAbsoluteURI()) {
388                 hostconfig.setHost(uri);
389             }
390         }
391         
392         HttpMethodDirector methodDirector = new HttpMethodDirector(
393                 getHttpConnectionManager(),
394                 hostconfig,
395                 this.params,
396                 (state == null ? getState() : state));
397         methodDirector.executeMethod(method);
398         return method.getStatusCode();
399     }
400 
401     /**
402       * Returns the default host. 
403       *
404       * @return The default host.
405       * 
406       * @deprecated use #getHostConfiguration()
407       */
408      public String getHost() {
409          return hostConfiguration.getHost();
410      }
411 
412      /**
413       * Returns the default port.
414       *
415       * @return The default port.
416       * 
417       * @deprecated use #getHostConfiguration()
418       */
419      public int getPort() {
420          return hostConfiguration.getPort();
421      }
422      
423     /**
424      * Returns the {@link HostConfiguration host configuration} associated with the 
425      * HttpClient.
426      * 
427      * @return {@link HostConfiguration host configuration}
428      * 
429      * @since 2.0
430      */
431     public synchronized HostConfiguration getHostConfiguration() {
432         return hostConfiguration;
433     }
434 
435     /**
436      * Assigns the {@link HostConfiguration host configuration} to use with the
437      * HttpClient.
438      * 
439      * @param hostConfiguration The {@link HostConfiguration host configuration} to set
440      * 
441      * @since 2.0
442      */
443     public synchronized void setHostConfiguration(HostConfiguration hostConfiguration) {
444         this.hostConfiguration = hostConfiguration;
445     }
446 
447     /**
448      * Returns the {@link HttpConnectionManager HTTP connection manager} associated 
449      * with the HttpClient.
450      * 
451      * @return {@link HttpConnectionManager HTTP connection manager}
452      * 
453      * @since 2.0
454      */
455     public synchronized HttpConnectionManager getHttpConnectionManager() {
456         return httpConnectionManager;
457     }
458 
459     /**
460      * Assigns the {@link HttpConnectionManager HTTP connection manager} to use with
461      * the HttpClient.
462      * 
463      * @param httpConnectionManager The {@link HttpConnectionManager HTTP connection manager}
464      *  to set
465      * 
466      * @since 2.0
467      */
468     public synchronized void setHttpConnectionManager(
469         HttpConnectionManager httpConnectionManager
470     ) {
471         this.httpConnectionManager = httpConnectionManager;
472         if (this.httpConnectionManager != null) {
473             this.httpConnectionManager.getParams().setDefaults(this.params);
474         }
475     }
476 
477     /**
478      * Returns {@link HttpClientParams HTTP protocol parameters} associated with this HttpClient.
479      * 
480      * @since 3.0
481      * 
482      * @see HttpClientParams
483      */
484     public HttpClientParams getParams() {
485         return this.params;
486     }
487 
488     /**
489      * Assigns {@link HttpClientParams HTTP protocol parameters} for this HttpClient.
490      * 
491      * @since 3.0
492      * 
493      * @see HttpClientParams
494      */
495     public void setParams(final HttpClientParams params) {
496         if (params == null) {
497             throw new IllegalArgumentException("Parameters may not be null");
498         }
499         this.params = params;
500     }
501 
502 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpClientError.html100644 0 0 13455 10661532627 26106 0ustar 0 0 HttpClientError xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpClientError.java,v 1.4 2004/05/13 04:03:25 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * Signals that an error has occurred.
35   * 
36   * @author Ortwin Gl?ck
37   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
38   * @since 3.0
39   */
40  public class HttpClientError extends Error {
41  
42      /**
43       * Creates a new HttpClientError with a <tt>null</tt> detail message.
44       */
45      public HttpClientError() {
46          super();
47      }
48  
49      /**
50       * Creates a new HttpClientError with the specified detail message.
51       * @param message The error message
52       */
53      public HttpClientError(String message) {
54          super(message);
55      }
56  
57  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpConnection.html100644 0 0 340424 10661532627 25774 0ustar 0 0 HttpConnection xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpConnection.java,v 1.107 2005/01/14 21:30:59 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.BufferedInputStream;
34  import java.io.BufferedOutputStream;
35  import java.io.IOException;
36  import java.io.InputStream;
37  import java.io.InterruptedIOException;
38  import java.io.OutputStream;
39  import java.lang.reflect.Method;
40  import java.net.InetAddress;
41  import java.net.Socket;
42  import java.net.SocketException;
43  
44  import org.apache.commons.httpclient.params.HttpConnectionParams;
45  import org.apache.commons.httpclient.protocol.Protocol;
46  import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
47  import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
48  import org.apache.commons.httpclient.util.EncodingUtil;
49  import org.apache.commons.httpclient.util.ExceptionUtil;
50  import org.apache.commons.logging.Log;
51  import org.apache.commons.logging.LogFactory;
52  
53  /**
54   * An abstraction of an HTTP {@link InputStream} and {@link OutputStream}
55   * pair, together with the relevant attributes.
56   * <p>
57   * The following options are set on the socket before getting the input/output 
58   * streams in the {@link #open()} method:
59   * <table border=1><tr>
60   *    <th>Socket Method
61   *    <th>Sockets Option
62   *    <th>Configuration
63   * </tr><tr>
64   *    <td>{@link java.net.Socket#setTcpNoDelay(boolean)}
65   *    <td>SO_NODELAY
66   *    <td>{@link HttpConnectionParams#setTcpNoDelay(boolean)}
67   * </tr><tr>
68   *    <td>{@link java.net.Socket#setSoTimeout(int)}
69   *    <td>SO_TIMEOUT
70   *    <td>{@link HttpConnectionParams#setSoTimeout(int)}
71   * </tr><tr>
72   *    <td>{@link java.net.Socket#setSendBufferSize(int)}
73   *    <td>SO_SNDBUF
74   *    <td>{@link HttpConnectionParams#setSendBufferSize(int)}
75   * </tr><tr>
76   *    <td>{@link java.net.Socket#setReceiveBufferSize(int)}
77   *    <td>SO_RCVBUF
78   *    <td>{@link HttpConnectionParams#setReceiveBufferSize(int)}
79   * </tr></table>
80   *
81   * @author Rod Waldhoff
82   * @author Sean C. Sullivan
83   * @author Ortwin Glueck
84   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
85   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
86   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
87   * @author Michael Becke
88   * @author Eric E Johnson
89   * @author Laura Werner
90   * 
91   * @version   $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
92   */
93  public class HttpConnection {
94  
95      // ----------------------------------------------------------- Constructors
96  
97      /**
98       * Creates a new HTTP connection for the given host and port.
99       *
100      * @param host the host to connect to
101      * @param port the port to connect to
102      */
103     public HttpConnection(String host, int port) {
104         this(null, -1, host, null, port, Protocol.getProtocol("http"));
105     }
106 
107     /**
108      * Creates a new HTTP connection for the given host and port
109      * using the given protocol.
110      *
111      * @param host the host to connect to
112      * @param port the port to connect to
113      * @param protocol the protocol to use
114      */
115     public HttpConnection(String host, int port, Protocol protocol) {
116         this(null, -1, host, null, port, protocol);
117     }
118 
119     /**
120      * Creates a new HTTP connection for the given host with the virtual 
121      * alias and port using given protocol.
122      *
123      * @param host the host to connect to
124      * @param virtualHost the virtual host requests will be sent to
125      * @param port the port to connect to
126      * @param protocol the protocol to use
127      */
128     public HttpConnection(String host, String virtualHost, int port, Protocol protocol) {
129         this(null, -1, host, virtualHost, port, protocol);
130     }
131 
132     /**
133      * Creates a new HTTP connection for the given host and port via the 
134      * given proxy host and port using the default protocol.
135      *
136      * @param proxyHost the host to proxy via
137      * @param proxyPort the port to proxy via
138      * @param host the host to connect to
139      * @param port the port to connect to
140      */
141     public HttpConnection(
142         String proxyHost,
143         int proxyPort,
144         String host,
145         int port) {
146         this(proxyHost, proxyPort, host, null, port, Protocol.getProtocol("http"));
147     }
148 
149     /**
150      * Creates a new HTTP connection for the given host configuration.
151      * 
152      * @param hostConfiguration the host/proxy/protocol to use
153      */
154     public HttpConnection(HostConfiguration hostConfiguration) {
155         this(hostConfiguration.getProxyHost(),
156              hostConfiguration.getProxyPort(),
157              hostConfiguration.getHost(),
158              hostConfiguration.getPort(),
159              hostConfiguration.getProtocol());
160         this.localAddress = hostConfiguration.getLocalAddress();
161     }
162 
163     /**
164      * Creates a new HTTP connection for the given host with the virtual 
165      * alias and port via the given proxy host and port using the given 
166      * protocol.
167      * 
168      * @param proxyHost the host to proxy via
169      * @param proxyPort the port to proxy via
170      * @param host the host to connect to. Parameter value must be non-null.
171      * @param virtualHost No longer applicable. 
172      * @param port the port to connect to
173      * @param protocol The protocol to use. Parameter value must be non-null.
174      * 
175      * @deprecated use #HttpConnection(String, int, String, int, Protocol)
176      */
177     public HttpConnection(
178         String proxyHost,
179         int proxyPort,
180         String host,
181         String virtualHost,
182         int port,
183         Protocol protocol) {
184     	this(proxyHost, proxyPort, host, port, protocol);
185     }
186 
187     /**
188      * Creates a new HTTP connection for the given host with the virtual 
189      * alias and port via the given proxy host and port using the given 
190      * protocol.
191      * 
192      * @param proxyHost the host to proxy via
193      * @param proxyPort the port to proxy via
194      * @param host the host to connect to. Parameter value must be non-null.
195      * @param port the port to connect to
196      * @param protocol The protocol to use. Parameter value must be non-null.
197      */
198     public HttpConnection(
199         String proxyHost,
200         int proxyPort,
201         String host,
202         int port,
203         Protocol protocol) {
204 
205         if (host == null) {
206             throw new IllegalArgumentException("host parameter is null");
207         }
208         if (protocol == null) {
209             throw new IllegalArgumentException("protocol is null");
210         }
211 
212         proxyHostName = proxyHost;
213         proxyPortNumber = proxyPort;
214         hostName = host;
215         portNumber = protocol.resolvePort(port);
216         protocolInUse = protocol;
217     }
218 
219     // ------------------------------------------ Attribute Setters and Getters
220 
221     /**
222      * Returns the connection socket.
223      *
224      * @return the socket.
225      * 
226      * @since 3.0
227      */
228     protected Socket getSocket() {
229         return this.socket;
230     }
231 
232     /**
233      * Returns the host.
234      *
235      * @return the host.
236      */
237     public String getHost() {
238         return hostName;
239     }
240 
241     /**
242      * Sets the host to connect to.
243      *
244      * @param host the host to connect to. Parameter value must be non-null.
245      * @throws IllegalStateException if the connection is already open
246      */
247     public void setHost(String host) throws IllegalStateException {
248         if (host == null) {
249             throw new IllegalArgumentException("host parameter is null");
250         }
251         assertNotOpen();
252         hostName = host;
253     }
254 
255     /**
256      * Returns the target virtual host.
257      *
258      * @return the virtual host.
259      * 
260      * @deprecated no longer applicable
261      */
262 
263     public String getVirtualHost() {
264         return this.hostName;
265     }
266 
267     /**
268      * Sets the virtual host to target.
269      *
270      * @param host the virtual host name that should be used instead of 
271      *        physical host name when sending HTTP requests. Virtual host 
272      *        name can be set to <tt> null</tt> if virtual host name is not
273      *        to be used
274      * 
275      * @throws IllegalStateException if the connection is already open
276      * 
277      * @deprecated no longer applicable
278      */
279 
280     public void setVirtualHost(String host) throws IllegalStateException {
281         assertNotOpen();
282     }
283 
284     /**
285      * Returns the port of the host.
286      *
287      * If the port is -1 (or less than 0) the default port for
288      * the current protocol is returned.
289      *
290      * @return the port.
291      */
292     public int getPort() {
293         if (portNumber < 0) {
294             return isSecure() ? 443 : 80;
295         } else {
296             return portNumber;
297         }
298     }
299 
300     /**
301      * Sets the port to connect to.
302      *
303      * @param port the port to connect to
304      * 
305      * @throws IllegalStateException if the connection is already open
306      */
307     public void setPort(int port) throws IllegalStateException {
308         assertNotOpen();
309         portNumber = port;
310     }
311 
312     /**
313      * Returns the proxy host.
314      *
315      * @return the proxy host.
316      */
317     public String getProxyHost() {
318         return proxyHostName;
319     }
320 
321     /**
322      * Sets the host to proxy through.
323      *
324      * @param host the host to proxy through.
325      * 
326      * @throws IllegalStateException if the connection is already open
327      */
328     public void setProxyHost(String host) throws IllegalStateException {
329         assertNotOpen();
330         proxyHostName = host;
331     }
332 
333     /**
334      * Returns the port of the proxy host.
335      *
336      * @return the proxy port.
337      */
338     public int getProxyPort() {
339         return proxyPortNumber;
340     }
341 
342     /**
343      * Sets the port of the host to proxy through.
344      *
345      * @param port the port of the host to proxy through.
346      * 
347      * @throws IllegalStateException if the connection is already open
348      */
349     public void setProxyPort(int port) throws IllegalStateException {
350         assertNotOpen();
351         proxyPortNumber = port;
352     }
353 
354     /**
355      * Returns <tt>true</tt> if the connection is established over 
356      * a secure protocol.
357      *
358      * @return <tt>true</tt> if connected over a secure protocol.
359      */
360     public boolean isSecure() {
361         return protocolInUse.isSecure();
362     }
363 
364     /**
365      * Returns the protocol used to establish the connection.
366      * @return The protocol
367      */
368     public Protocol getProtocol() {
369         return protocolInUse;
370     }
371 
372     /**
373      * Sets the protocol used to establish the connection
374      * 
375      * @param protocol The protocol to use.
376      * 
377      * @throws IllegalStateException if the connection is already open
378      */
379     public void setProtocol(Protocol protocol) {
380         assertNotOpen();
381 
382         if (protocol == null) {
383             throw new IllegalArgumentException("protocol is null");
384         }
385 
386         protocolInUse = protocol;
387 
388     }
389 
390     /**
391      * Return the local address used when creating the connection.
392      * If <tt>null</tt>, the default address is used.
393      * 
394      * @return InetAddress the local address to be used when creating Sockets
395      */
396     public InetAddress getLocalAddress() {
397         return this.localAddress;
398     }
399     
400     /**
401      * Set the local address used when creating the connection.
402      * If unset or <tt>null</tt>, the default address is used.
403      * 
404      * @param localAddress the local address to use
405      */
406     public void setLocalAddress(InetAddress localAddress) {
407         assertNotOpen();
408         this.localAddress = localAddress;
409     }
410 
411     /**
412      * Tests if the connection is open. 
413      *
414      * @return <code>true</code> if the connection is open
415      */
416     public boolean isOpen() {
417         return isOpen;
418     }
419 
420     /**
421      * Closes the connection if stale.
422      * 
423      * @return <code>true</code> if the connection was stale and therefore closed, 
424      * <code>false</code> otherwise.
425      * 
426      * @see #isStale()
427      * 
428      * @since 3.0
429      */
430     public boolean closeIfStale() throws IOException {
431         if (isOpen && isStale()) {
432             LOG.debug("Connection is stale, closing...");
433             close();
434             return true;
435         }
436         return false;
437     }
438     
439     /**
440      * Tests if stale checking is enabled.
441      * 
442      * @return <code>true</code> if enabled
443      * 
444      * @see #isStale()
445      * 
446      * @deprecated Use {@link HttpConnectionParams#isStaleCheckingEnabled()},
447      * {@link HttpConnection#getParams()}.
448      */
449     public boolean isStaleCheckingEnabled() {
450         return this.params.isStaleCheckingEnabled();
451     }
452 
453     /**
454      * Sets whether or not isStale() will be called when testing if this connection is open.
455      * 
456      * <p>Setting this flag to <code>false</code> will increase performance when reusing
457      * connections, but it will also make them less reliable.  Stale checking ensures that
458      * connections are viable before they are used.  When set to <code>false</code> some
459      * method executions will result in IOExceptions and they will have to be retried.</p>
460      * 
461      * @param staleCheckEnabled <code>true</code> to enable isStale()
462      * 
463      * @see #isStale()
464      * @see #isOpen()
465      * 
466      * @deprecated Use {@link HttpConnectionParams#setStaleCheckingEnabled(boolean)},
467      * {@link HttpConnection#getParams()}.
468      */
469     public void setStaleCheckingEnabled(boolean staleCheckEnabled) {
470         this.params.setStaleCheckingEnabled(staleCheckEnabled);
471     }
472 
473     /**
474      * Determines whether this connection is "stale", which is to say that either
475      * it is no longer open, or an attempt to read the connection would fail.
476      *
477      * <p>Unfortunately, due to the limitations of the JREs prior to 1.4, it is
478      * not possible to test a connection to see if both the read and write channels
479      * are open - except by reading and writing.  This leads to a difficulty when
480      * some connections leave the "write" channel open, but close the read channel
481      * and ignore the request.  This function attempts to ameliorate that
482      * problem by doing a test read, assuming that the caller will be doing a
483      * write followed by a read, rather than the other way around.
484      * </p>
485      *
486      * <p>To avoid side-effects, the underlying connection is wrapped by a
487      * {@link BufferedInputStream}, so although data might be read, what is visible
488      * to clients of the connection will not change with this call.</p.
489      *
490      * @throws IOException if the stale connection test is interrupted.
491      * 
492      * @return <tt>true</tt> if the connection is already closed, or a read would
493      * fail.
494      */
495     protected boolean isStale() throws IOException {
496         boolean isStale = true;
497         if (isOpen) {
498             // the connection is open, but now we have to see if we can read it
499             // assume the connection is not stale.
500             isStale = false;
501             try {
502                 if (inputStream.available() <= 0) {
503                     try {
504                         socket.setSoTimeout(1);
505                         inputStream.mark(1);
506                         int byteRead = inputStream.read();
507                         if (byteRead == -1) {
508                             // again - if the socket is reporting all data read,
509                             // probably stale
510                             isStale = true;
511                         } else {
512                             inputStream.reset();
513                         }
514                     } finally {
515                         socket.setSoTimeout(this.params.getSoTimeout());
516                     }
517                 }
518             } catch (InterruptedIOException e) {
519                 if (!ExceptionUtil.isSocketTimeoutException(e)) {
520                     throw e;
521                 }
522                 // aha - the connection is NOT stale - continue on!
523             } catch (IOException e) {
524                 // oops - the connection is stale, the read or soTimeout failed.
525                 LOG.debug(
526                     "An error occurred while reading from the socket, is appears to be stale",
527                     e
528                 );
529                 isStale = true;
530             }
531         }
532 
533         return isStale;
534     }
535 
536     /**
537      * Returns <tt>true</tt> if the connection is established via a proxy,
538      * <tt>false</tt> otherwise.
539      *
540      * @return <tt>true</tt> if a proxy is used to establish the connection, 
541      * <tt>false</tt> otherwise.
542      */
543     public boolean isProxied() {
544         return (!(null == proxyHostName || 0 >= proxyPortNumber));
545     }
546 
547     /**
548      * Set the state to keep track of the last response for the last request.
549      *
550      * <p>The connection managers use this to ensure that previous requests are
551      * properly closed before a new request is attempted.  That way, a GET
552      * request need not be read in its entirety before a new request is issued.
553      * Instead, this stream can be closed as appropriate.</p>
554      *
555      * @param inStream  The stream associated with an HttpMethod.
556      */
557     public void setLastResponseInputStream(InputStream inStream) {
558         lastResponseInputStream = inStream;
559     }
560 
561     /**
562      * Returns the stream used to read the last response's body.
563      *
564      * <p>Clients will generally not need to call this function unless
565      * using HttpConnection directly, instead of calling {@link HttpClient#executeMethod}.
566      * For those clients, call this function, and if it returns a non-null stream,
567      * close the stream before attempting to execute a method.  Note that
568      * calling "close" on the stream returned by this function <i>may</i> close
569      * the connection if the previous response contained a "Connection: close" header. </p>
570      *
571      * @return An {@link InputStream} corresponding to the body of the last
572      *  response.
573      */
574     public InputStream getLastResponseInputStream() {
575         return lastResponseInputStream;
576     }
577 
578     // --------------------------------------------------- Other Public Methods
579 
580     /**
581      * Returns {@link HttpConnectionParams HTTP protocol parameters} associated with this method.
582      *
583      * @return HTTP parameters.
584      *
585      * @since 3.0
586      */
587     public HttpConnectionParams getParams() {
588         return this.params;
589     }
590 
591     /**
592      * Assigns {@link HttpConnectionParams HTTP protocol parameters} for this method.
593      * 
594      * @since 3.0
595      * 
596      * @see HttpConnectionParams
597      */
598     public void setParams(final HttpConnectionParams params) {
599         if (params == null) {
600             throw new IllegalArgumentException("Parameters may not be null");
601         }
602         this.params = params;
603     }
604 
605     /**
606      * Set the {@link Socket}'s timeout, via {@link Socket#setSoTimeout}.  If the
607      * connection is already open, the SO_TIMEOUT is changed.  If no connection
608      * is open, then subsequent connections will use the timeout value.
609      * <p>
610      * Note: This is not a connection timeout but a timeout on network traffic!
611      *
612      * @param timeout the timeout value
613      * @throws SocketException - if there is an error in the underlying
614      * protocol, such as a TCP error.
615      * 
616      * @deprecated Use {@link HttpConnectionParams#setSoTimeout(int)},
617      * {@link HttpConnection#getParams()}.
618      */
619     public void setSoTimeout(int timeout)
620         throws SocketException, IllegalStateException {
621         this.params.setSoTimeout(timeout);
622         if (this.socket != null) {
623             this.socket.setSoTimeout(timeout);
624         }
625     }
626 
627     /**
628      * Sets <code>SO_TIMEOUT</code> value directly on the underlying {@link Socket socket}. 
629      * This method does not change the default read timeout value set via 
630      * {@link HttpConnectionParams}.
631      *
632      * @param timeout the timeout value
633      * @throws SocketException - if there is an error in the underlying
634      * protocol, such as a TCP error.
635      * @throws IllegalStateException if not connected
636      * 
637      * @since 3.0
638      */
639     public void setSocketTimeout(int timeout)
640         throws SocketException, IllegalStateException {
641         assertOpen();
642         if (this.socket != null) {
643             this.socket.setSoTimeout(timeout);
644         }
645     }
646 
647     /**
648      * Returns the {@link Socket}'s timeout, via {@link Socket#getSoTimeout}, if the
649      * connection is already open. If no connection is open, return the value subsequent 
650      * connection will use.
651      * <p>
652      * Note: This is not a connection timeout but a timeout on network traffic!
653      *
654      * @return the timeout value
655      * 
656      * @deprecated Use {@link HttpConnectionParams#getSoTimeout()},
657      * {@link HttpConnection#getParams()}.
658      */
659     public int getSoTimeout() throws SocketException {
660         return this.params.getSoTimeout();
661     }
662 
663     /**
664      * Sets the connection timeout. This is the maximum time that may be spent
665      * until a connection is established. The connection will fail after this
666      * amount of time.
667      * @param timeout The timeout in milliseconds. 0 means timeout is not used.
668      * 
669      * @deprecated Use {@link HttpConnectionParams#setConnectionTimeout(int)},
670      * {@link HttpConnection#getParams()}.
671      */
672     public void setConnectionTimeout(int timeout) {
673         this.params.setConnectionTimeout(timeout);
674     }
675 
676     /**
677      * Establishes a connection to the specified host and port
678      * (via a proxy if specified).
679      * The underlying socket is created from the {@link ProtocolSocketFactory}.
680      *
681      * @throws IOException if an attempt to establish the connection results in an
682      *   I/O error.
683      */
684     public void open() throws IOException {
685         LOG.trace("enter HttpConnection.open()");
686 
687         final String host = (proxyHostName == null) ? hostName : proxyHostName;
688         final int port = (proxyHostName == null) ? portNumber : proxyPortNumber;
689         assertNotOpen();
690         
691         if (LOG.isDebugEnabled()) {
692             LOG.debug("Open connection to " + host + ":" + port);
693         }
694         
695         try {
696             if (this.socket == null) {
697                 usingSecureSocket = isSecure() && !isProxied();
698                 // use the protocol's socket factory unless this is a secure
699                 // proxied connection
700                 ProtocolSocketFactory socketFactory = null;
701                 if (isSecure() && isProxied()) {
702                     Protocol defaultprotocol = Protocol.getProtocol("http");
703                     socketFactory = defaultprotocol.getSocketFactory();
704                 } else {
705                     socketFactory = this.protocolInUse.getSocketFactory();
706                 }
707                 this.socket = socketFactory.createSocket(
708                             host, port, 
709                             localAddress, 0,
710                             this.params);
711             }
712 
713             /*
714             "Nagling has been broadly implemented across networks, 
715             including the Internet, and is generally performed by default 
716             - although it is sometimes considered to be undesirable in 
717             highly interactive environments, such as some client/server 
718             situations. In such cases, nagling may be turned off through 
719             use of the TCP_NODELAY sockets option." */
720 
721             socket.setTcpNoDelay(this.params.getTcpNoDelay());
722             socket.setSoTimeout(this.params.getSoTimeout());
723             
724             int linger = this.params.getLinger();
725             if (linger >= 0) {
726                 socket.setSoLinger(linger > 0, linger);
727             }
728             
729             int sndBufSize = this.params.getSendBufferSize();
730             if (sndBufSize >= 0) {
731                 socket.setSendBufferSize(sndBufSize);
732             }        
733             int rcvBufSize = this.params.getReceiveBufferSize();
734             if (rcvBufSize >= 0) {
735                 socket.setReceiveBufferSize(rcvBufSize);
736             }        
737             int outbuffersize = socket.getSendBufferSize();
738             if ((outbuffersize > 2048) || (outbuffersize <= 0)) {
739                 outbuffersize = 2048;
740             }
741             int inbuffersize = socket.getReceiveBufferSize();
742             if ((inbuffersize > 2048) || (inbuffersize <= 0)) {
743                 inbuffersize = 2048;
744             }
745             inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize);
746             outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize);
747             isOpen = true;
748         } catch (IOException e) {
749             // Connection wasn't opened properly
750             // so close everything out
751             closeSocketAndStreams();
752             throw e;
753         }
754     }
755 
756     /**
757      * Instructs the proxy to establish a secure tunnel to the host. The socket will 
758      * be switched to the secure socket. Subsequent communication is done via the secure 
759      * socket. The method can only be called once on a proxied secure connection.
760      *
761      * @throws IllegalStateException if connection is not secure and proxied or
762      * if the socket is already secure.
763      * @throws IOException if an attempt to establish the secure tunnel results in an
764      *   I/O error.
765      */
766     public void tunnelCreated() throws IllegalStateException, IOException {
767         LOG.trace("enter HttpConnection.tunnelCreated()");
768 
769         if (!isSecure() || !isProxied()) {
770             throw new IllegalStateException(
771                 "Connection must be secure "
772                     + "and proxied to use this feature");
773         }
774 
775         if (usingSecureSocket) {
776             throw new IllegalStateException("Already using a secure socket");
777         }
778         
779         if (LOG.isDebugEnabled()) {
780             LOG.debug("Secure tunnel to " + this.hostName + ":" + this.portNumber);
781         }
782 
783         SecureProtocolSocketFactory socketFactory =
784             (SecureProtocolSocketFactory) protocolInUse.getSocketFactory();
785 
786         socket = socketFactory.createSocket(socket, hostName, portNumber, true);
787         int sndBufSize = this.params.getSendBufferSize();
788         if (sndBufSize >= 0) {
789             socket.setSendBufferSize(sndBufSize);
790         }        
791         int rcvBufSize = this.params.getReceiveBufferSize();
792         if (rcvBufSize >= 0) {
793             socket.setReceiveBufferSize(rcvBufSize);
794         }        
795         int outbuffersize = socket.getSendBufferSize();
796         if (outbuffersize > 2048) {
797             outbuffersize = 2048;
798         }
799         int inbuffersize = socket.getReceiveBufferSize();
800         if (inbuffersize > 2048) {
801             inbuffersize = 2048;
802         }
803         inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize);
804         outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize);
805         usingSecureSocket = true;
806         tunnelEstablished = true;
807     }
808 
809     /**
810      * Indicates if the connection is completely transparent from end to end.
811      *
812      * @return true if conncetion is not proxied or tunneled through a transparent
813      * proxy; false otherwise.
814      */
815     public boolean isTransparent() {
816         return !isProxied() || tunnelEstablished;
817     }
818 
819     /**
820      * Flushes the output request stream.  This method should be called to 
821      * ensure that data written to the request OutputStream is sent to the server.
822      * 
823      * @throws IOException if an I/O problem occurs
824      */
825     public void flushRequestOutputStream() throws IOException {
826         LOG.trace("enter HttpConnection.flushRequestOutputStream()");
827         assertOpen();
828         outputStream.flush();
829     }
830 
831     /**
832      * Returns an {@link OutputStream} suitable for writing the request.
833      *
834      * @throws IllegalStateException if the connection is not open
835      * @throws IOException if an I/O problem occurs
836      * @return a stream to write the request to
837      */
838     public OutputStream getRequestOutputStream()
839         throws IOException, IllegalStateException {
840         LOG.trace("enter HttpConnection.getRequestOutputStream()");
841         assertOpen();
842         OutputStream out = this.outputStream;
843         if (Wire.CONTENT_WIRE.enabled()) {
844             out = new WireLogOutputStream(out, Wire.CONTENT_WIRE);
845         }
846         return out;
847     }
848 
849     /**
850      * Return a {@link InputStream} suitable for reading the response.
851      * @return InputStream The response input stream.
852      * @throws IOException If an IO problem occurs
853      * @throws IllegalStateException If the connection isn't open.
854      */
855     public InputStream getResponseInputStream()
856         throws IOException, IllegalStateException {
857         LOG.trace("enter HttpConnection.getResponseInputStream()");
858         assertOpen();
859         return inputStream;
860     }
861 
862     /**
863      * Tests if input data avaialble. This method returns immediately
864      * and does not perform any read operations on the input socket
865      * 
866      * @return boolean <tt>true</tt> if input data is available, 
867      *                 <tt>false</tt> otherwise.
868      * 
869      * @throws IOException If an IO problem occurs
870      * @throws IllegalStateException If the connection isn't open.
871      */
872     public boolean isResponseAvailable() 
873         throws IOException {
874         LOG.trace("enter HttpConnection.isResponseAvailable()");
875         if (this.isOpen) {
876             return this.inputStream.available() > 0;
877         } else {
878             return false;
879         }
880     }
881 
882     /**
883      * Tests if input data becomes available within the given period time in milliseconds.
884      * 
885      * @param timeout The number milliseconds to wait for input data to become available 
886      * @return boolean <tt>true</tt> if input data is availble, 
887      *                 <tt>false</tt> otherwise.
888      * 
889      * @throws IOException If an IO problem occurs
890      * @throws IllegalStateException If the connection isn't open.
891      */
892     public boolean isResponseAvailable(int timeout) 
893         throws IOException {
894         LOG.trace("enter HttpConnection.isResponseAvailable(int)");
895         assertOpen();
896         boolean result = false;
897         if (this.inputStream.available() > 0) {
898             result = true;
899         } else {
900             try {
901                 this.socket.setSoTimeout(timeout);
902                 inputStream.mark(1);
903                 int byteRead = inputStream.read();
904                 if (byteRead != -1) {
905                     inputStream.reset();
906                     LOG.debug("Input data available");
907                     result = true;
908                 } else {
909                     LOG.debug("Input data not available");
910                 }
911             } catch (InterruptedIOException e) {
912                 if (!ExceptionUtil.isSocketTimeoutException(e)) {
913                     throw e;
914                 }
915                 if (LOG.isDebugEnabled()) {
916                     LOG.debug("Input data not available after " + timeout + " ms");
917                 }
918             } finally {
919                 try {
920                     socket.setSoTimeout(this.params.getSoTimeout());
921                 } catch (IOException ioe) {
922                     LOG.debug("An error ocurred while resetting soTimeout, we will assume that"
923                         + " no response is available.",
924                         ioe);
925                     result = false;
926                 }
927             }
928         }
929         return result;
930     }
931 
932     /**
933      * Writes the specified bytes to the output stream.
934      *
935      * @param data the data to be written
936      * @throws IllegalStateException if not connected
937      * @throws IOException if an I/O problem occurs
938      * @see #write(byte[],int,int)
939      */
940     public void write(byte[] data)
941         throws IOException, IllegalStateException {
942         LOG.trace("enter HttpConnection.write(byte[])");
943         this.write(data, 0, data.length);
944     }
945 
946     /**
947      * Writes <i>length</i> bytes in <i>data</i> starting at
948      * <i>offset</i> to the output stream.
949      *
950      * The general contract for
951      * write(b, off, len) is that some of the bytes in the array b are written
952      * to the output stream in order; element b[off] is the first byte written
953      * and b[off+len-1] is the last byte written by this operation.
954      *
955      * @param data array containing the data to be written.
956      * @param offset the start offset in the data.
957      * @param length the number of bytes to write.
958      * @throws IllegalStateException if not connected
959      * @throws IOException if an I/O problem occurs
960      */
961     public void write(byte[] data, int offset, int length)
962         throws IOException, IllegalStateException {
963         LOG.trace("enter HttpConnection.write(byte[], int, int)");
964 
965         if (offset < 0) {
966             throw new IllegalArgumentException("Array offset may not be negative");
967         }
968         if (length < 0) {
969             throw new IllegalArgumentException("Array length may not be negative");
970         }
971         if (offset + length > data.length) {
972             throw new IllegalArgumentException("Given offset and length exceed the array length");
973         }
974         assertOpen();
975         this.outputStream.write(data, offset, length);
976     }
977 
978     /**
979      * Writes the specified bytes, followed by <tt>"\r\n".getBytes()</tt> to the
980      * output stream.
981      *
982      * @param data the bytes to be written
983      * @throws IllegalStateException if the connection is not open
984      * @throws IOException if an I/O problem occurs
985      */
986     public void writeLine(byte[] data)
987         throws IOException, IllegalStateException {
988         LOG.trace("enter HttpConnection.writeLine(byte[])");
989         write(data);
990         writeLine();
991     }
992 
993     /**
994      * Writes <tt>"\r\n".getBytes()</tt> to the output stream.
995      *
996      * @throws IllegalStateException if the connection is not open
997      * @throws IOException if an I/O problem occurs
998      */
999     public void writeLine()
1000         throws IOException, IllegalStateException {
1001         LOG.trace("enter HttpConnection.writeLine()");
1002         write(CRLF);
1003     }
1004 
1005     /**
1006      * @deprecated Use {@link #print(String, String)}
1007      * 
1008      * Writes the specified String (as bytes) to the output stream.
1009      *
1010      * @param data the string to be written
1011      * @throws IllegalStateException if the connection is not open
1012      * @throws IOException if an I/O problem occurs
1013      */
1014     public void print(String data)
1015         throws IOException, IllegalStateException {
1016         LOG.trace("enter HttpConnection.print(String)");
1017         write(EncodingUtil.getBytes(data, "ISO-8859-1"));
1018     }
1019 
1020     /**
1021      * Writes the specified String (as bytes) to the output stream.
1022      *
1023      * @param data the string to be written
1024      * @param charset the charset to use for writing the data
1025      * @throws IllegalStateException if the connection is not open
1026      * @throws IOException if an I/O problem occurs
1027      * 
1028      * @since 3.0
1029      */
1030     public void print(String data, String charset)
1031     	throws IOException, IllegalStateException {
1032         LOG.trace("enter HttpConnection.print(String)");
1033         write(EncodingUtil.getBytes(data, charset));
1034     }
1035     
1036     /**
1037      * @deprecated Use {@link #printLine(String, String)}
1038      * 
1039      * Writes the specified String (as bytes), followed by
1040      * <tt>"\r\n".getBytes()</tt> to the output stream.
1041      *
1042      * @param data the data to be written
1043      * @throws IllegalStateException if the connection is not open
1044      * @throws IOException if an I/O problem occurs
1045      */
1046     public void printLine(String data)
1047         throws IOException, IllegalStateException {
1048         LOG.trace("enter HttpConnection.printLine(String)");
1049         writeLine(EncodingUtil.getBytes(data, "ISO-8859-1"));
1050     }
1051 
1052     /**
1053      * Writes the specified String (as bytes), followed by
1054      * <tt>"\r\n".getBytes()</tt> to the output stream.
1055      *
1056      * @param data the data to be written
1057      * @param charset the charset to use for writing the data
1058      * @throws IllegalStateException if the connection is not open
1059      * @throws IOException if an I/O problem occurs
1060      * 
1061      * @since 3.0
1062      */
1063     public void printLine(String data, String charset)
1064     	throws IOException, IllegalStateException {
1065         LOG.trace("enter HttpConnection.printLine(String)");
1066         writeLine(EncodingUtil.getBytes(data, charset));
1067     }    
1068     
1069     /**
1070      * Writes <tt>"\r\n".getBytes()</tt> to the output stream.
1071      *
1072      * @throws IllegalStateException if the connection is not open
1073      * @throws IOException if an I/O problem occurs
1074      */
1075     public void printLine()
1076         throws IOException, IllegalStateException {
1077         LOG.trace("enter HttpConnection.printLine()");
1078         writeLine();
1079     }
1080 
1081     /**
1082      * Reads up to <tt>"\n"</tt> from the (unchunked) input stream.
1083      * If the stream ends before the line terminator is found,
1084      * the last part of the string will still be returned.
1085      *
1086      * @throws IllegalStateException if the connection is not open
1087      * @throws IOException if an I/O problem occurs
1088      * @return a line from the response
1089      * 
1090      * @deprecated use #readLine(String)
1091      */
1092     public String readLine() throws IOException, IllegalStateException {
1093         LOG.trace("enter HttpConnection.readLine()");
1094 
1095         assertOpen();
1096         return HttpParser.readLine(inputStream);
1097     }
1098 
1099     /**
1100      * Reads up to <tt>"\n"</tt> from the (unchunked) input stream.
1101      * If the stream ends before the line terminator is found,
1102      * the last part of the string will still be returned.
1103      * 
1104      * @param charset the charset to use for reading the data
1105      *
1106      * @throws IllegalStateException if the connection is not open
1107      * @throws IOException if an I/O problem occurs
1108      * @return a line from the response
1109      * 
1110      * @since 3.0
1111      */
1112     public String readLine(final String charset) throws IOException, IllegalStateException {
1113         LOG.trace("enter HttpConnection.readLine()");
1114 
1115         assertOpen();
1116         return HttpParser.readLine(inputStream, charset);
1117     }
1118 
1119     /**
1120      * Attempts to shutdown the {@link Socket}'s output, via Socket.shutdownOutput()
1121      * when running on JVM 1.3 or higher.
1122      * 
1123      * @deprecated unused
1124      */
1125     public void shutdownOutput() {
1126         LOG.trace("enter HttpConnection.shutdownOutput()");
1127 
1128         try {
1129             // Socket.shutdownOutput is a JDK 1.3
1130             // method. We'll use reflection in case
1131             // we're running in an older VM
1132             Class[] paramsClasses = new Class[0];
1133             Method shutdownOutput =
1134                 socket.getClass().getMethod("shutdownOutput", paramsClasses);
1135             Object[] params = new Object[0];
1136             shutdownOutput.invoke(socket, params);
1137         } catch (Exception ex) {
1138             LOG.debug("Unexpected Exception caught", ex);
1139             // Ignore, and hope everything goes right
1140         }
1141         // close output stream?
1142     }
1143 
1144     /**
1145      * Closes the socket and streams.
1146      */
1147     public void close() {
1148         LOG.trace("enter HttpConnection.close()");
1149         closeSocketAndStreams();
1150     }
1151 
1152     /**
1153      * Returns the httpConnectionManager.
1154      * @return HttpConnectionManager
1155      */
1156     public HttpConnectionManager getHttpConnectionManager() {
1157         return httpConnectionManager;
1158     }
1159 
1160     /**
1161      * Sets the httpConnectionManager.
1162      * @param httpConnectionManager The httpConnectionManager to set
1163      */
1164     public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager) {
1165         this.httpConnectionManager = httpConnectionManager;
1166     }
1167 
1168     /**
1169      * Releases the connection. If the connection is locked or does not have a connection
1170      * manager associated with it, this method has no effect. Note that it is completely safe 
1171      * to call this method multiple times.
1172      */
1173     public void releaseConnection() {
1174         LOG.trace("enter HttpConnection.releaseConnection()");
1175         if (locked) {
1176             LOG.debug("Connection is locked.  Call to releaseConnection() ignored.");
1177         } else if (httpConnectionManager != null) {
1178             LOG.debug("Releasing connection back to connection manager.");
1179             httpConnectionManager.releaseConnection(this);
1180         } else {
1181             LOG.warn("HttpConnectionManager is null.  Connection cannot be released.");
1182         }
1183     }
1184 
1185     /**
1186      * Tests if the connection is locked. Locked connections cannot be released. 
1187      * An attempt to release a locked connection will have no effect.
1188      * 
1189      * @return <tt>true</tt> if the connection is locked, <tt>false</tt> otherwise.
1190      * 
1191      * @since 3.0
1192      */
1193     protected boolean isLocked() {
1194         return locked;
1195     }
1196 
1197     /**
1198      * Locks or unlocks the connection. Locked connections cannot be released. 
1199      * An attempt to release a locked connection will have no effect.
1200      * 
1201      * @param locked <tt>true</tt> to lock the connection, <tt>false</tt> to unlock
1202      *  the connection.
1203      * 
1204      * @since 3.0
1205      */
1206     protected void setLocked(boolean locked) {
1207         this.locked = locked;
1208     }
1209     // ------------------------------------------------------ Protected Methods
1210 
1211     /**
1212      * Closes everything out.
1213      */
1214     protected void closeSocketAndStreams() {
1215         LOG.trace("enter HttpConnection.closeSockedAndStreams()");
1216 
1217         isOpen = false;
1218         
1219         // no longer care about previous responses...
1220         lastResponseInputStream = null;
1221 
1222         if (null != outputStream) {
1223             OutputStream temp = outputStream;
1224             outputStream = null;
1225             try {
1226                 temp.close();
1227             } catch (Exception ex) {
1228                 LOG.debug("Exception caught when closing output", ex);
1229                 // ignored
1230             }
1231         }
1232 
1233         if (null != inputStream) {
1234             InputStream temp = inputStream;
1235             inputStream = null;
1236             try {
1237                 temp.close();
1238             } catch (Exception ex) {
1239                 LOG.debug("Exception caught when closing input", ex);
1240                 // ignored
1241             }
1242         }
1243 
1244         if (null != socket) {
1245             Socket temp = socket;
1246             socket = null;
1247             try {
1248                 temp.close();
1249             } catch (Exception ex) {
1250                 LOG.debug("Exception caught when closing socket", ex);
1251                 // ignored
1252             }
1253         }
1254         
1255         tunnelEstablished = false;
1256         usingSecureSocket = false;
1257     }
1258 
1259     /**
1260      * Throws an {@link IllegalStateException} if the connection is already open.
1261      *
1262      * @throws IllegalStateException if connected
1263      */
1264     protected void assertNotOpen() throws IllegalStateException {
1265         if (isOpen) {
1266             throw new IllegalStateException("Connection is open");
1267         }
1268     }
1269 
1270     /**
1271      * Throws an {@link IllegalStateException} if the connection is not open.
1272      *
1273      * @throws IllegalStateException if not connected
1274      */
1275     protected void assertOpen() throws IllegalStateException {
1276         if (!isOpen) {
1277             throw new IllegalStateException("Connection is not open");
1278         }
1279     }
1280 
1281     /**
1282      * Gets the socket's sendBufferSize.
1283      * 
1284      * @return the size of the buffer for the socket OutputStream, -1 if the value
1285      * has not been set and the socket has not been opened
1286      * 
1287      * @throws SocketException if an error occurs while getting the socket value
1288      * 
1289      * @see Socket#getSendBufferSize()
1290      */
1291     public int getSendBufferSize() throws SocketException {
1292         if (socket == null) {
1293             return -1;
1294         } else {
1295             return socket.getSendBufferSize();
1296         }
1297     }
1298 
1299     /**
1300      * Sets the socket's sendBufferSize.
1301      * 
1302      * @param sendBufferSize the size to set for the socket OutputStream
1303      * 
1304      * @throws SocketException if an error occurs while setting the socket value
1305      * 
1306      * @see Socket#setSendBufferSize(int)
1307      * 
1308      * @deprecated Use {@link HttpConnectionParams#setSendBufferSize(int)},
1309      * {@link HttpConnection#getParams()}.
1310      */
1311     public void setSendBufferSize(int sendBufferSize) throws SocketException {
1312         this.params.setSendBufferSize(sendBufferSize);
1313     }
1314 
1315     // ------------------------------------------------------- Static Variable
1316 
1317     /** <tt>"\r\n"</tt>, as bytes. */
1318     private static final byte[] CRLF = new byte[] {(byte) 13, (byte) 10};
1319 
1320     /** Log object for this class. */
1321     private static final Log LOG = LogFactory.getLog(HttpConnection.class);
1322     
1323     // ----------------------------------------------------- Instance Variables
1324     
1325     /** My host. */
1326     private String hostName = null;
1327     
1328     /** My port. */
1329     private int portNumber = -1;
1330     
1331     /** My proxy host. */
1332     private String proxyHostName = null;
1333     
1334     /** My proxy port. */
1335     private int proxyPortNumber = -1;
1336     
1337     /** My client Socket. */
1338     private Socket socket = null;
1339     
1340     /** My InputStream. */
1341     private InputStream inputStream = null;
1342 
1343     /** My OutputStream. */
1344     private OutputStream outputStream = null;
1345     
1346     /** An {@link InputStream} for the response to an individual request. */
1347     private InputStream lastResponseInputStream = null;
1348     
1349     /** Whether or not the connection is connected. */
1350     protected boolean isOpen = false;
1351     
1352     /** the protocol being used */
1353     private Protocol protocolInUse;
1354     
1355     /** Collection of HTTP parameters associated with this HTTP connection*/
1356     private HttpConnectionParams params = new HttpConnectionParams();
1357     
1358     /** flag to indicate if this connection can be released, if locked the connection cannot be 
1359      * released */
1360     private boolean locked = false;
1361     
1362     /** Whether or not the socket is a secure one. */
1363     private boolean usingSecureSocket = false;
1364     
1365     /** Whether the connection is open via a secure tunnel or not */
1366     private boolean tunnelEstablished = false;
1367     
1368     /** the connection manager that created this connection or null */
1369     private HttpConnectionManager httpConnectionManager;
1370     
1371     /** The local interface on which the connection is created, or null for the default */
1372     private InetAddress localAddress;
1373 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpConnectionManager.html100644 0 0 33463 10661532627 27251 0ustar 0 0 HttpConnectionManager xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpConnectionManager.java,v 1.24 2004/07/05 22:46:58 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
34  
35  /**
36   * An interface for classes that manage HttpConnections.
37   * 
38   * @see org.apache.commons.httpclient.HttpConnection
39   * @see org.apache.commons.httpclient.HttpClient#HttpClient(HttpConnectionManager)
40   *
41   * @author Michael Becke
42   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
43   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
44   * 
45   * @since 2.0
46   */
47  public interface HttpConnectionManager {
48  
49      /**
50       * Gets an HttpConnection for a given host configuration. If a connection is
51       * not available this method will block until one is.
52       *
53       * The connection manager should be registered with any HttpConnection that
54       * is created.
55       *
56       * @param hostConfiguration the host configuration to use to configure the
57       * connection
58       * 
59       * @return an HttpConnection for the given configuration
60       * 
61       * @see HttpConnection#setHttpConnectionManager(HttpConnectionManager)
62       */
63      HttpConnection getConnection(HostConfiguration hostConfiguration);
64  
65      /**
66       * Gets an HttpConnection for a given host configuration. If a connection is
67       * not available, this method will block for at most the specified number of
68       * milliseconds or until a connection becomes available.
69       *
70       * The connection manager should be registered with any HttpConnection that
71       * is created.
72       *
73       * @param hostConfiguration the host configuration to use to configure the
74       * connection
75       * @param timeout - the time (in milliseconds) to wait for a connection to
76       * become available, 0 to specify an infinite timeout
77       * 
78       * @return an HttpConnection for the given configuraiton
79       * 
80       * @throws HttpException if no connection becomes available before the
81       * timeout expires
82       * 
83       * @see HttpConnection#setHttpConnectionManager(HttpConnectionManager)
84       * 
85       * @deprecated Use #getConnectionWithTimeout(HostConfiguration, long) 
86       */
87      HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout)
88          throws HttpException;
89  
90  	/**
91  	 * Gets an HttpConnection for a given host configuration. If a connection is
92  	 * not available, this method will block for at most the specified number of
93  	 * milliseconds or until a connection becomes available.
94  	 *
95  	 * The connection manager should be registered with any HttpConnection that
96  	 * is created.
97  	 *
98  	 * @param hostConfiguration the host configuration to use to configure the
99  	 * connection
100 	 * @param timeout - the time (in milliseconds) to wait for a connection to
101 	 * become available, 0 to specify an infinite timeout
102 	 * 
103 	 * @return an HttpConnection for the given configuraiton
104 	 * 
105 	 * @throws ConnectionPoolTimeoutException if no connection becomes available before the
106 	 * timeout expires
107 	 * 
108 	 * @see HttpConnection#setHttpConnectionManager(HttpConnectionManager)
109      * 
110      * @since 3.0
111 	 */
112 	HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout)
113 		throws ConnectionPoolTimeoutException;
114 
115     /**
116      * Releases the given HttpConnection for use by other requests.
117      *
118      * @param conn - The HttpConnection to make available.
119      */
120     void releaseConnection(HttpConnection conn);
121 
122     /**
123      * Closes connections that have been idle for at least the given amount of time.  Only
124      * connections that are currently owned, not checked out, are subject to idle timeouts.
125      * 
126      * @param idleTimeout the minimum idle time, in milliseconds, for connections to be closed
127      * 
128      * @since 3.0
129      */
130     void closeIdleConnections(long idleTimeout);
131     
132     /**
133      * Returns {@link HttpConnectionManagerParams parameters} associated 
134      * with this connection manager.
135      * 
136      * @since 3.0
137      * 
138      * @see HttpConnectionManagerParams
139      */
140     HttpConnectionManagerParams getParams();
141 
142     /**
143      * Assigns {@link HttpConnectionManagerParams parameters} for this 
144      * connection manager.
145      * 
146      * @since 3.0
147      * 
148      * @see HttpConnectionManagerParams
149      */
150     void setParams(final HttpConnectionManagerParams params);
151 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpConstants.html100644 0 0 67307 10661532627 25637 0ustar 0 0 HttpConstants xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpConstants.java,v 1.15 2004/04/18 23:51:35 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.UnsupportedEncodingException;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  
38  
39  /**
40   * HTTP content conversion routines.
41   *
42   * @author Oleg Kalnichevski
43   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
44   * 
45   * @deprecated use EncodingUtil class
46   */
47  public class HttpConstants {
48  
49      /** Character set used to encode HTTP protocol elements */
50      public static final String HTTP_ELEMENT_CHARSET = "US-ASCII";
51  
52      /** Default content encoding chatset */
53      public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1";
54  
55      /** Log object for this class. */
56      private static final Log LOG = LogFactory.getLog(HttpConstants.class);
57  
58      /**
59       * Converts the specified string to a byte array of HTTP element characters.
60       * This method is to be used when encoding content of HTTP elements (such as
61       * request headers)
62       *
63       * @param data the string to be encoded
64       * @return The resulting byte array.
65       */
66      public static byte[] getBytes(final String data) {
67          if (data == null) {
68              throw new IllegalArgumentException("Parameter may not be null");
69          }
70  
71          try {
72              return data.getBytes(HTTP_ELEMENT_CHARSET);
73          } catch (UnsupportedEncodingException e) {
74  
75              if (LOG.isWarnEnabled()) {
76                  LOG.warn("Unsupported encoding: " 
77                      + HTTP_ELEMENT_CHARSET 
78                      + ". System default encoding used");
79              }
80  
81              return data.getBytes();
82          }
83      }
84  
85      /**
86       * Converts the byte array of HTTP element characters to a string This
87       * method is to be used when decoding content of HTTP elements (such as
88       * response headers)
89       *
90       * @param data the byte array to be encoded
91       * @param offset the index of the first byte to encode
92       * @param length the number of bytes to encode 
93       * @return The resulting string.
94       */
95      public static String getString(final byte[] data, int offset, int length) {
96  
97          if (data == null) {
98              throw new IllegalArgumentException("Parameter may not be null");
99          }
100 
101         try {
102             return new String(data, offset, length, HTTP_ELEMENT_CHARSET);
103         } catch (UnsupportedEncodingException e) {
104 
105             if (LOG.isWarnEnabled()) {
106                 LOG.warn("Unsupported encoding: " 
107                     + HTTP_ELEMENT_CHARSET 
108                     + ". System default encoding used");
109             }
110 
111             return new String(data, offset, length);
112         }
113     }
114 
115     /**
116      * Converts the byte array of HTTP element characters to a string This
117      * method is to be used when decoding content of HTTP elements (such as
118      * response headers)
119      *
120      * @param data the byte array to be encoded
121      * @return The resulting string.
122      */
123     public static String getString(final byte[] data) {
124         return getString(data, 0, data.length);
125     }
126 
127     /**
128      * Converts the specified string to a byte array of HTTP content charachetrs
129      * This method is to be used when encoding content of HTTP request/response
130      * If the specified charset is not supported, default HTTP content encoding
131      * (ISO-8859-1) is applied
132      *
133      * @param data the string to be encoded
134      * @param charset the desired character encoding
135      * @return The resulting byte array.
136      */
137     public static byte[] getContentBytes(final String data, String charset) {
138 
139         if (data == null) {
140             throw new IllegalArgumentException("Parameter may not be null");
141         }
142 
143         if ((charset == null) || (charset.equals(""))) {
144             charset = DEFAULT_CONTENT_CHARSET;
145         }
146 
147         try {
148             return data.getBytes(charset);
149         } catch (UnsupportedEncodingException e) {
150 
151             if (LOG.isWarnEnabled()) {
152                 LOG.warn("Unsupported encoding: " 
153                     + charset 
154                     + ". HTTP default encoding used");
155             }
156 
157             try {
158                 return data.getBytes(DEFAULT_CONTENT_CHARSET);
159             } catch (UnsupportedEncodingException e2) {
160 
161                 if (LOG.isWarnEnabled()) {
162                     LOG.warn("Unsupported encoding: " 
163                         + DEFAULT_CONTENT_CHARSET 
164                         + ". System encoding used");
165                 }
166 
167                 return data.getBytes();
168             }
169         }
170     }
171 
172     /**
173      * Converts the byte array of HTTP content characters to a string This
174      * method is to be used when decoding content of HTTP request/response If
175      * the specified charset is not supported, default HTTP content encoding
176      * (ISO-8859-1) is applied
177      *
178      * @param data the byte array to be encoded
179      * @param offset the index of the first byte to encode
180      * @param length the number of bytes to encode 
181      * @param charset the desired character encoding
182      * @return The result of the conversion.
183      */
184     public static String getContentString(
185         final byte[] data, 
186         int offset, 
187         int length, 
188         String charset
189     ) {
190 
191         if (data == null) {
192             throw new IllegalArgumentException("Parameter may not be null");
193         }
194 
195         if ((charset == null) || (charset.equals(""))) {
196             charset = DEFAULT_CONTENT_CHARSET;
197         }
198 
199         try {
200             return new String(data, offset, length, charset);
201         } catch (UnsupportedEncodingException e) {
202 
203             if (LOG.isWarnEnabled()) {
204                 LOG.warn("Unsupported encoding: " + charset + ". Default HTTP encoding used");
205             }
206 
207             try {
208                 return new String(data, offset, length, DEFAULT_CONTENT_CHARSET);
209             } catch (UnsupportedEncodingException e2) {
210 
211                 if (LOG.isWarnEnabled()) {
212                     LOG.warn("Unsupported encoding: " 
213                         + DEFAULT_CONTENT_CHARSET 
214                         + ". System encoding used");
215                 }
216 
217                 return new String(data, offset, length);
218             }
219         }
220     }
221 
222 
223     /**
224      * Converts the byte array of HTTP content characters to a string This
225      * method is to be used when decoding content of HTTP request/response If
226      * the specified charset is not supported, default HTTP content encoding
227      * (ISO-8859-1) is applied
228      *
229      * @param data the byte array to be encoded
230      * @param charset the desired character encoding
231      * @return The result of the conversion.
232      */
233     public static String getContentString(final byte[] data, String charset) {
234         return getContentString(data, 0, data.length, charset);
235     }
236 
237     /**
238      * Converts the specified string to a byte array of HTTP content characters
239      * using default HTTP content encoding (ISO-8859-1) This method is to be
240      * used when encoding content of HTTP request/response
241      *
242      * @param data the string to be encoded
243      * @return The byte array as above.
244      */
245     public static byte[] getContentBytes(final String data) {
246         return getContentBytes(data, null);
247     }
248 
249     /**
250      * Converts the byte array of HTTP content characters to a string using
251      * default HTTP content encoding (ISO-8859-1) This method is to be used when
252      * decoding content of HTTP request/response
253      *
254      * @param data the byte array to be encoded
255      * @param offset the index of the first byte to encode
256      * @param length the number of bytes to encode 
257      * @return The string representation of the byte array.
258      */
259     public static String getContentString(final byte[] data, int offset, int length) {
260         return getContentString(data, offset, length, null);
261     }
262 
263     /**
264      * Converts the byte array of HTTP content characters to a string using
265      * default HTTP content encoding (ISO-8859-1) This method is to be used when
266      * decoding content of HTTP request/response
267      *
268      * @param data the byte array to be encoded
269      * @return The string representation of the byte array.
270      */
271     public static String getContentString(final byte[] data) {
272         return getContentString(data, null);
273     }
274 
275     /**
276      * Converts the specified string to byte array of ASCII characters.
277      *
278      * @param data the string to be encoded
279      * @return The string as a byte array.
280      */
281     public static byte[] getAsciiBytes(final String data) {
282 
283         if (data == null) {
284             throw new IllegalArgumentException("Parameter may not be null");
285         }
286 
287         try {
288             return data.getBytes("US-ASCII");
289         } catch (UnsupportedEncodingException e) {
290             throw new RuntimeException("HttpClient requires ASCII support");
291         }
292     }
293 
294     /**
295      * Converts the byte array of ASCII characters to a string. This method is
296      * to be used when decoding content of HTTP elements (such as response
297      * headers)
298      *
299      * @param data the byte array to be encoded
300      * @param offset the index of the first byte to encode
301      * @param length the number of bytes to encode 
302      * @return The string representation of the byte array
303      */
304     public static String getAsciiString(final byte[] data, int offset, int length) {
305 
306         if (data == null) {
307             throw new IllegalArgumentException("Parameter may not be null");
308         }
309 
310         try {
311             return new String(data, offset, length, "US-ASCII");
312         } catch (UnsupportedEncodingException e) {
313             throw new RuntimeException("HttpClient requires ASCII support");
314         }
315     }
316 
317     /**
318      * Converts the byte array of ASCII characters to a string. This method is
319      * to be used when decoding content of HTTP elements (such as response
320      * headers)
321      *
322      * @param data the byte array to be encoded
323      * @return The string representation of the byte array
324      */
325     public static String getAsciiString(final byte[] data) {
326         return getAsciiString(data, 0, data.length);
327     }
328 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpContentTooLargeException.html100644 0 0 4613 10661532627 30560 0ustar 0 0 HttpContentTooLargeException xref

1   package org.apache.commons.httpclient;
2   
3   /**
4    * Signals that the response content was larger than anticipated. 
5    * 
6    * @author Ortwin Gl?ck
7    */
8   public class HttpContentTooLargeException extends HttpException {
9       private int maxlen;
10  
11      public HttpContentTooLargeException(String message, int maxlen) {
12          super(message);
13          this.maxlen = maxlen;
14      }
15      
16      /**
17       * @return the maximum anticipated content length in bytes.
18       */
19      public int getMaxLength() {
20          return maxlen;
21      }
22  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpException.html100644 0 0 50304 10661532627 25606 0ustar 0 0 HttpException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpException.java,v 1.19 2004/09/30 18:53:20 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.io.PrintStream;
35  import java.io.PrintWriter;
36  import java.lang.reflect.Method;
37  
38  /**
39   * Signals that an HTTP or HttpClient exception has occurred.
40   * 
41   * @author Laura Werner
42   * 
43   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
44   */
45  public class HttpException extends IOException {
46  
47      /**
48       * Creates a new HttpException with a <tt>null</tt> detail message.
49       */
50      public HttpException() {
51          super();
52          this.cause = null;
53      }
54  
55      /**
56       * Creates a new HttpException with the specified detail message.
57       *
58       * @param message the exception detail message
59       */
60      public HttpException(String message) {
61          super(message);
62          this.cause = null;
63      }
64  
65      /**
66       * Creates a new HttpException with the specified detail message and cause.
67       * 
68       * @param message the exception detail message
69       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
70       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
71       * 
72       * @since 3.0
73       */
74      public HttpException(String message, Throwable cause) {
75          super(message);
76          this.cause = cause;
77          
78          // If we're running on JDK 1.4 or later, tell Throwable what the cause was
79          try {
80              Class[] paramsClasses = new Class[] { Throwable.class };
81              Method initCause = Throwable.class.getMethod("initCause", paramsClasses);
82              initCause.invoke(this, new Object[] { cause });
83          } catch (Exception e) {
84              // The setCause method must not be available
85          }
86      }
87  
88      /**
89       * Return the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
90       *         if the cause is unavailable, unknown, or not a <tt>Throwable</tt>.
91       * 
92       * @return the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
93       *         if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
94       * 
95       * @since 3.0
96       */
97      public Throwable getCause() {
98          return cause;
99      }
100 
101     /**
102      * Print this HttpException and its stack trace to the standard error stream.
103      * 
104      * @since 3.0
105      */
106     public void printStackTrace() {
107         printStackTrace(System.err);
108     }
109 
110     /**
111      * Print this HttpException and its stack trace to the specified print stream.
112      * 
113      * @param s the <tt>PrintStream</tt> to which the exception and its stack trace
114      * should be written
115      * 
116      * @since 3.0
117      */
118     public void printStackTrace(PrintStream s) {
119         try {
120             // JDK 1.4 has a nice printStackTrace method that prints the cause's stack
121             // trace too and prunes out duplicate stack frames.  Call it if possible,
122             // which is determined by checking whether JDK 1.4's getStackTrace method is present 
123             Class[] paramsClasses = new Class[] {  };
124             this.getClass().getMethod("getStackTrace", paramsClasses);
125             super.printStackTrace(s);
126         } catch (Exception ex) {
127             // If that didn't work, print it out ourselves
128             // First print this exception's stack trace.
129             super.printStackTrace(s);
130             if (cause != null) {
131                 // Print out the exception that caused this one.
132                 // This will recurse if the cause is another HttpException.
133                 s.print("Caused by: ");
134                 cause.printStackTrace(s);
135             }
136         }
137     }
138 
139     /**
140      * Print this HttpException and its stack trace to the specified print writer.
141      * 
142      * @param s the <tt>PrintWriter</tt> to which the exception and its stack trace
143      * should be written
144      * 
145      * @since 3.0
146      */
147     public void printStackTrace(PrintWriter s) {
148         try {
149             // JDK 1.4 has a nice printStackTrace method that prints the cause's stack
150             // trace too and prunes out duplicate stack frames.  Call it if possible,
151             // which is determined by checking whether JDK 1.4's getStackTrace method is present 
152             Class[] paramsClasses = new Class[] {  };
153             this.getClass().getMethod("getStackTrace", paramsClasses);
154             super.printStackTrace(s);
155         } catch (Exception ex) {
156             // If that didn't work, print it out ourselves
157             // First print this exception's stack trace.
158             super.printStackTrace(s);
159             if (cause != null) {
160                 // Print out the exception that caused this one.
161                 // This will recurse if the cause is another HttpException.
162                 s.print("Caused by: ");
163                 cause.printStackTrace(s);
164             }
165         }
166     }
167 
168     /**
169      * Sets the text description of the reason for an exception.
170      *
171      * @param reason The reason for the exception.
172      *
173      * @deprecated HttpClient no longer uses this for itself.  It is only
174      * provided for compatibility with existing clients, and will be removed
175      * in a future release.
176      */
177     public void setReason(String reason) {
178         this.reason = reason;
179     }
180 
181     /**
182      * Get the text description of the reason for an exception.
183      *
184      * @deprecated HttpClient no longer uses this for itself.  It is only
185      * provided for compatibility with existing clients, and will be removed
186      * in a future release.
187      */
188     public String getReason() {
189         return reason;
190     }
191 
192     /**
193      * Sets the status code description of the reason for an exception.
194      *
195      * @param code The reason for the exception.  This is intended to be an
196      *  HTTP status code.
197      *
198      * @deprecated HttpClient no longer uses this for itself.  It is only
199      * provided for compatibility with existing clients, and will be removed
200      * in a future release.
201      */
202     public void setReasonCode(int code) {
203         reasonCode = code;
204     }
205 
206     /**
207      * Get the status code description of the reason for an exception.
208      *
209      * @deprecated HttpClient no longer uses this for itself.  It is only
210      * provided for compatibility with existing clients, and will be removed
211      * in a future release.
212      */
213     public int getReasonCode() {
214         return this.reasonCode;
215     }
216 
217     /**
218      * A "reason" string provided for compatibility with older clients.
219      *
220      * @deprecated HttpClient no longer uses this field for itself.  It
221      * is only provided for compatibility with existing clients.
222      */
223     private String reason;
224 
225     /**
226      * Reason code for compatibility with older clients.
227      *
228      * @deprecated  HttpClient no longer uses this field for itself.
229      *  It is only provided for compatibility with existing clients.
230      */
231     private int reasonCode = HttpStatus.SC_OK;
232 
233     /** The original Throwable representing the cause of this error */
234     private final Throwable cause;
235 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpHost.html100644 0 0 46123 10661532627 24571 0ustar 0 0 HttpHost xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpHost.java,v 1.3 2005/01/14 21:16:40 olegk Exp $
3    * $Revision: 510587 $
4    * $Date: 2007-02-22 17:56:08 +0100 (Thu, 22 Feb 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import org.apache.commons.httpclient.protocol.Protocol;
34  import org.apache.commons.httpclient.util.LangUtils;
35  
36  /**
37   * Holds all of the variables needed to describe an HTTP connection to a host. This includes 
38   * remote host, port and protocol.
39   * 
40   * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
41   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
42   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
43   * @author Laura Werner
44   * 
45   * @since 3.0 
46   */
47  public class HttpHost implements Cloneable {
48  
49      /** The host to use. */
50      private String hostname = null;
51  
52      /** The port to use. */
53      private int port = -1;
54  
55      /** The protocol */
56      private Protocol protocol = null;
57  
58      /**
59       * Constructor for HttpHost.
60       *   
61       * @param hostname the hostname (IP or DNS name). Can be <code>null</code>.
62       * @param port the port. Value <code>-1</code> can be used to set default protocol port
63       * @param protocol the protocol. Value <code>null</code> can be used to set default protocol
64       */
65      public HttpHost(final String hostname, int port, final Protocol protocol) {
66          super();
67          if (hostname == null) {
68              throw new IllegalArgumentException("Host name may not be null");
69          }
70          if (protocol == null) {
71              throw new IllegalArgumentException("Protocol may not be null");
72          }
73          this.hostname = hostname;
74          this.protocol = protocol;
75          if (port >= 0) {
76              this.port = port;
77          } else {
78              this.port = this.protocol.getDefaultPort();
79          }
80      }
81  
82      /**
83       * Constructor for HttpHost.
84       *   
85       * @param hostname the hostname (IP or DNS name). Can be <code>null</code>.
86       * @param port the port. Value <code>-1</code> can be used to set default protocol port
87       */
88      public HttpHost(final String hostname, int port) {
89          this(hostname, port, Protocol.getProtocol("http"));
90      }
91      
92      /**
93       * Constructor for HttpHost.
94       *   
95       * @param hostname the hostname (IP or DNS name). Can be <code>null</code>.
96       */
97      public HttpHost(final String hostname) {
98          this(hostname, -1, Protocol.getProtocol("http"));
99      }
100     
101     /**
102      * URI constructor for HttpHost.
103      *   
104      * @param uri the URI.
105      */
106     public  HttpHost(final URI uri) throws URIException {
107         this(uri.getHost(), uri.getPort(), Protocol.getProtocol(uri.getScheme()));
108     }
109 
110     /**
111      * Copy constructor for HttpHost
112      * 
113      * @param httphost the HTTP host to copy details from
114      */
115     public HttpHost (final HttpHost httphost) {
116         super();
117         init(httphost);
118     }
119 
120 	private void init(final HttpHost httphost) {
121 		this.hostname = httphost.hostname;
122         this.port = httphost.port;
123         this.protocol = httphost.protocol;
124 	}
125 
126     /**
127      * @throws CloneNotSupportedException 
128      * @see java.lang.Object#clone()
129      */
130     public Object clone() throws CloneNotSupportedException {
131     	HttpHost copy = (HttpHost) super.clone();
132     	copy.init(this);
133         return copy;
134     }    
135     
136     /**
137      * Returns the host name (IP or DNS name).
138      * 
139      * @return the host name (IP or DNS name), or <code>null</code> if not set
140      */
141     public String getHostName() {
142         return this.hostname;
143     }
144 
145     /**
146      * Returns the port.
147      * 
148      * @return the host port, or <code>-1</code> if not set
149      */
150     public int getPort() {
151         return this.port;
152     }
153 
154     /**
155      * Returns the protocol.
156      * @return The protocol.
157      */
158     public Protocol getProtocol() {
159         return this.protocol;
160     }
161 
162     /**
163      * Return the host uri.
164      * 
165      * @return The host uri.
166      */
167     public String toURI() {
168         StringBuffer buffer = new StringBuffer(50);        
169         buffer.append(this.protocol.getScheme());
170         buffer.append("://");
171         buffer.append(this.hostname);
172         if (this.port != this.protocol.getDefaultPort()) {
173             buffer.append(':');
174             buffer.append(this.port);
175         }
176         return buffer.toString();
177     }
178 
179     /**
180      * @see java.lang.Object#toString()
181      */
182     public String toString() {
183         StringBuffer buffer = new StringBuffer(50);        
184         buffer.append(toURI());
185         return buffer.toString();
186     }    
187     
188     /**
189      * @see java.lang.Object#equals(java.lang.Object)
190      */
191     public boolean equals(final Object o) {
192         
193         if (o instanceof HttpHost) {
194             // shortcut if we're comparing with ourselves
195             if (o == this) { 
196                 return true;
197             }
198             HttpHost that = (HttpHost) o;
199             if (!this.hostname.equalsIgnoreCase(that.hostname)) {
200                 return false;
201             }
202             if (this.port != that.port) {
203                 return false;
204             }
205             if (!this.protocol.equals(that.protocol)) {
206                 return false;
207             }
208             // everything matches
209             return true;
210         } else {
211             return false;
212         }
213     }
214 
215     /**
216      * @see java.lang.Object#hashCode()
217      */
218     public int hashCode() {
219         int hash = LangUtils.HASH_SEED;
220         hash = LangUtils.hashCode(hash, this.hostname);
221         hash = LangUtils.hashCode(hash, this.port);
222         hash = LangUtils.hashCode(hash, this.protocol);
223         return hash;
224     }
225 
226 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpMethod.html100644 0 0 136714 10661532627 25122 0ustar 0 0 HttpMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethod.java,v 1.43 2004/10/07 16:14:15 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  
36  import org.apache.commons.httpclient.auth.AuthState;
37  import org.apache.commons.httpclient.params.HttpMethodParams;
38  
39  /**
40   * <p>
41   * HttpMethod interface represents a request to be sent via a 
42   * {@link HttpConnection HTTP connection} and a corresponding response.
43   * </p>
44   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
45   * @author Rod Waldhoff
46   * @author <a href="jsdever@apache.org">Jeff Dever</a>
47   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
48   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
49   *
50   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
51   * 
52   * @since 1.0
53   */
54  public interface HttpMethod {
55  
56      // ------------------------------------------- Property Setters and Getters
57  
58      /**
59       * Obtains the name of the HTTP method as used in the HTTP request line,
60       * for example <tt>"GET"</tt> or <tt>"POST"</tt>.
61       * 
62       * @return the name of this method
63       */
64      String getName();
65  
66      /**
67       * Gets the host configuration for this method.  The configuration specifies
68       * the server, port, protocol, and proxy server via which this method will
69       * send its HTTP request.
70       * 
71       * @deprecated no longer applicable 
72       * 
73       * @return the HostConfiguration or <code>null</code> if none is set
74       */
75      HostConfiguration getHostConfiguration();
76  
77      /**
78       * Sets the path of the HTTP method.
79       * It is responsibility of the caller to ensure that the path is
80       * properly encoded (URL safe).
81       * 
82       * @param path The path of the HTTP method. The path is expected
83       *             to be URL encoded.
84       */
85      void setPath(String path);
86  
87      /**
88       * Returns the path of the HTTP method.  
89       *
90       * Calling this method <em>after</em> the request has been executed will 
91       * return the <em>actual</em> path, following any redirects automatically
92       * handled by this HTTP method.
93       * 
94       * @return the path of the HTTP method, in URL encoded form
95       */
96      String getPath();
97  
98      /**
99       * Returns the URI for this method. The URI will be absolute if the host
100      * configuration has been set and relative otherwise.
101      * 
102      * @return the URI for this method
103      * 
104      * @throws URIException if a URI cannot be constructed
105      */
106     URI getURI() throws URIException;
107 
108     /**
109      * Sets the URI for this method. 
110      * 
111      * @param uri URI to be set 
112      * 
113      * @throws URIException if a URI cannot be set
114      * 
115      * @since 3.0
116      */
117     void setURI(URI uri) throws URIException;
118 
119     /**
120      * Defines how strictly the method follows the HTTP protocol specification.  
121      * (See RFC 2616 and other relevant RFCs.) In the strict mode the method precisely
122      * implements the requirements of the specification, whereas in non-strict mode 
123      * it attempts to mimic the exact behaviour of commonly used HTTP agents, 
124      * which many HTTP servers expect.
125      * 
126      * @param strictMode <tt>true</tt> for strict mode, <tt>false</tt> otherwise
127      * 
128      * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)} 
129      * to exercise a more granular control over HTTP protocol strictness.
130      * 
131      * @see #isStrictMode()
132      */
133     void setStrictMode(boolean strictMode);
134 
135     /**
136      * Returns the value of the strict mode flag.
137      *
138      * @return <tt>true</tt> if strict mode is enabled, <tt>false</tt> otherwise
139      * 
140      * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)} 
141      * to exercise a more granular control over HTTP protocol strictness.
142      * 
143      * @see #setStrictMode(boolean)
144      */
145     boolean isStrictMode();
146      
147     /**
148      * Sets the specified request header, overwriting any
149      * previous value.
150      * Note that header-name matching is case insensitive.
151      * @param headerName the header's name
152      * @param headerValue the header's value
153      *
154      * @see #setRequestHeader(Header)
155      * @see #getRequestHeader(String)
156      * @see #removeRequestHeader(String)
157      */
158     void setRequestHeader(String headerName, String headerValue);
159 
160     /**
161      * Sets the specified request header, overwriting any
162      * previous value.
163      * Note that header-name matching is case insensitive.
164      * @param header the header to be set
165      *
166      * @see #setRequestHeader(String,String)
167      * @see #getRequestHeader(String)
168      * @see #removeRequestHeader(String)
169      */
170     void setRequestHeader(Header header);
171 
172     /**
173      * Adds the specified request header, <em>not</em> overwriting any previous value.
174      * If the same header is added multiple times, perhaps with different values,
175      * multiple instances of that header will be sent in the HTTP request.
176      * Note that header-name matching is case insensitive.
177      * @param headerName the header's name
178      * @param headerValue the header's value
179      * 
180      * @see #addRequestHeader(Header)
181      * @see #getRequestHeader(String)
182      * @see #removeRequestHeader(String)
183      */
184     void addRequestHeader(String headerName, String headerValue);
185 
186     /**
187      * Adds the specified request header, <em>not</em> overwriting any previous value.
188      * If the same header is added multiple times, perhaps with different values,
189      * multiple instances of that header will be sent in the HTTP request.
190      * Note that header-name matching is case insensitive.
191      * @param header the header
192      * 
193      * @see #addRequestHeader(String,String)
194      * @see #getRequestHeader(String)
195      * @see #removeRequestHeader(String)
196      */
197     void addRequestHeader(Header header);
198 
199     /**
200      * Gets the request header with the given name.
201      * If there are multiple headers with the same name,
202      * there values will be combined with the ',' separator as specified by RFC2616.
203      * Note that header-name matching is case insensitive.
204      * @param headerName the header name
205      * @return the header
206      */
207     Header getRequestHeader(String headerName);
208 
209     /**
210      * Removes all request headers with the given name.
211      * Note that header-name matching is case insensitive.
212      * @param headerName the header name
213      */
214     void removeRequestHeader(String headerName);
215 
216     /**
217      * Removes the given request header.
218      * 
219      * @param header the header
220      * 
221      * @since 3.0
222      */
223     void removeRequestHeader(Header header);
224 
225     /**
226      * Returns <tt>true</tt> if the HTTP method should automatically follow HTTP redirects 
227      * (status code 302, etc.), <tt>false</tt> otherwise.
228      * 
229      * @return <tt>true</tt> if the method will automatically follow HTTP redirects, 
230      * <tt>false</tt> otherwise
231      */
232     boolean getFollowRedirects();
233 
234     /**
235      * Sets whether or not the HTTP method should automatically follow HTTP redirects 
236      * (status code 302, etc.)
237      * 
238      * @param followRedirects <tt>true</tt> if the method will automatically follow redirects,
239      * <tt>false</tt> otherwise.
240      */
241     void setFollowRedirects(boolean followRedirects);
242 
243     /**
244      * Sets the query string of the HTTP method.
245      * It is responsibility of the caller to ensure that the path is
246      * properly encoded (URL safe).  The string must not include an initial '?' character.
247      * 
248      * @param queryString the query to be used in the request, with no leading '?' character
249      * 
250      * @see #getQueryString()
251      * @see #setQueryString(NameValuePair[])
252      */
253     void setQueryString(String queryString);
254 
255     /**
256      * Sets the query string of this HTTP method.  The pairs are encoded as UTF-8 characters.  
257      * To use a different charset the parameters can be encoded manually using EncodingUtil 
258      * and set as a single String.
259      *
260      * @param params An array of <code>NameValuePair</code>s to use as the query string.
261      *               The name/value pairs will be automatically URL encoded and should not
262      *               have been encoded previously.
263      * 
264      * @see #getQueryString()
265      * @see #setQueryString(String)
266      * @see org.apache.commons.httpclient.util.EncodingUtil#formUrlEncode(NameValuePair[], String)
267      */
268     void setQueryString(NameValuePair[] params);
269 
270     /**
271      * Returns the query string of this HTTP method.
272      * 
273      * @return the query string in URL encoded form, without a leading '?'.
274      * 
275      * @see #setQueryString(NameValuePair[]) 
276      * @see #setQueryString(String)
277      */
278     String getQueryString();
279 
280     /**
281      * Returns the current request headers for this HTTP method.  The returned headers
282      * will be in the same order that they were added with <code>addRequestHeader</code>.
283      * If there are multiple request headers with the same name (e.g. <code>Cookie</code>),
284      * they will be returned as multiple entries in the array.
285      * 
286      * @return an array containing all of the request headers
287      * 
288      * @see #addRequestHeader(Header)
289      * @see #addRequestHeader(String,String)
290      */
291     Header[] getRequestHeaders();
292 
293     /**
294      * Returns the request headers with the given name. Note that header-name matching is
295      * case insensitive.
296      * @param headerName the name of the headers to be returned.
297      * @return an array of zero or more headers
298      * 
299      * @since 3.0
300      */
301     Header[] getRequestHeaders(String headerName);
302 
303     // ---------------------------------------------------------------- Queries
304 
305     /**
306      * Returns <tt>true</tt> the method is ready to execute, <tt>false</tt> otherwise.
307      * 
308      * @return <tt>true</tt> if the method is ready to execute, <tt>false</tt> otherwise.
309      */
310     boolean validate();
311 
312     /**
313      * Returns the status code associated with the latest response.
314      * 
315      * @return The status code from the most recent execution of this method.
316      *         If the method has not yet been executed, the result is undefined.
317      */
318     int getStatusCode();
319 
320     /**
321      * Returns the status text (or "reason phrase") associated with the latest
322      * response.
323      * 
324      * @return The status text from the most recent execution of this method.
325      *         If the method has not yet been executed, the result is undefined.
326      */
327     String getStatusText();
328 
329     /**
330      * Returns the response headers from the most recent execution of this request.
331      * 
332      * @return A newly-created array containing all of the response headers, 
333      *         in the order in which they appeared in the response.
334      */
335     Header[] getResponseHeaders();
336 
337     /**
338      * Returns the specified response header. Note that header-name matching is
339      * case insensitive.
340      * 
341      * @param headerName The name of the header to be returned.
342      * 
343      * @return The specified response header.  If the repsonse contained multiple
344      *         instances of the header, its values will be combined using the ','
345      *         separator as specified by RFC2616.
346      */
347     Header getResponseHeader(String headerName);
348 
349     /**
350      * Returns the response headers with the given name. Note that header-name matching is
351      * case insensitive.
352      * @param headerName the name of the headers to be returned.
353      * @return an array of zero or more headers
354      * 
355      * @since 3.0
356      */
357     Header[] getResponseHeaders(String headerName);
358 
359     /**
360      * Returns the response footers from the most recent execution of this request.
361      * 
362      * @return an array containing the response footers in the order that they
363      *         appeared in the response.  If the response had no footers,
364      *         an empty array will be returned.
365      */
366     Header[] getResponseFooters();
367 
368     /**
369      * Return the specified response footer. Note that footer-name matching is
370      * case insensitive.
371      * 
372      * @param footerName The name of the footer.
373      * @return The response footer.
374      */
375     Header getResponseFooter(String footerName);
376 
377     /**
378      * Returns the response body of the HTTP method, if any, as an array of bytes.
379      * If the method has not yet been executed or the response has no body, <code>null</code>
380      * is returned.  Note that this method does not propagate I/O exceptions.
381      * If an error occurs while reading the body, <code>null</code> will be returned.
382      * 
383      * @return The response body, or <code>null</code> if the
384      *         body is not available.
385      * 
386      * @throws IOException if an I/O (transport) problem occurs
387      */
388     byte[] getResponseBody() throws IOException;
389 
390     /**
391      * Returns the response body of the HTTP method, if any, as a {@link String}. 
392      * If response body is not available or cannot be read, <tt>null</tt> is returned.
393      * The raw bytes in the body are converted to a <code>String</code> using the
394      * character encoding specified in the response's <tt>Content-Type</tt> header, or
395      * ISO-8859-1 if the response did not specify a character set.
396      * <p>
397      * Note that this method does not propagate I/O exceptions.
398      * If an error occurs while reading the body, <code>null</code> will be returned.
399      *
400      * @return The response body converted to a <code>String</code>, or <code>null</code>
401      *         if the body is not available.
402      * 
403      * @throws IOException if an I/O (transport) problem occurs
404      */
405     String getResponseBodyAsString() throws IOException;
406 
407     /**
408      * Returns the response body of the HTTP method, if any, as an InputStream.
409      * If the response had no body or the method has not yet been executed,
410      * <code>null</code> is returned.  Additionally, <code>null</code> may be returned
411      * if {@link #releaseConnection} has been called or
412      * if this method was called previously and the resulting stream was closed. 
413      * 
414      * @return The response body, or <code>null</code> if it is not available 
415      * 
416      * @throws IOException if an I/O (transport) problem occurs
417      */
418     InputStream getResponseBodyAsStream() throws IOException;
419 
420     /**
421      * Returns <tt>true</tt> if the HTTP method has been already {@link #execute executed},
422      * but not {@link #recycle recycled}.
423      * 
424      * @return <tt>true</tt> if the method has been executed, <tt>false</tt> otherwise
425      */
426     boolean hasBeenUsed();
427 
428     // --------------------------------------------------------- Action Methods
429 
430     /**
431      * Executes this method using the specified <code>HttpConnection</code> and
432      * <code>HttpState</code>. 
433      *
434      * @param state the {@link HttpState state} information to associate with this method
435      * @param connection the {@link HttpConnection connection} used to execute
436      *        this HTTP method
437      *
438      * @throws IOException If an I/O (transport) error occurs. Some transport exceptions
439      *                     can be recovered from.
440      * @throws HttpException  If a protocol exception occurs. Usually protocol exceptions 
441      *                    cannot be recovered from.
442      *
443      * @return the integer status code if one was obtained, or <tt>-1</tt>
444      */
445     int execute(HttpState state, HttpConnection connection) 
446         throws HttpException, IOException;
447 
448     /**
449      * Aborts the execution of the HTTP method.
450      * 
451      * @see #execute(HttpState, HttpConnection)
452      * 
453      * @since 3.0
454      */
455     void abort();
456 
457     /**
458      * Recycles the HTTP method so that it can be used again.
459      * Note that all of the instance variables will be reset
460      * once this method has been called. This method will also
461      * release the connection being used by this HTTP method.
462      * 
463      * @see #releaseConnection()
464      * 
465      * @deprecated no longer supported and will be removed in the future
466      *             version of HttpClient
467      */
468     void recycle();
469 
470     /**
471      * Releases the connection being used by this HTTP method. In particular the
472      * connection is used to read the response (if there is one) and will be held
473      * until the response has been read. If the connection can be reused by other 
474      * HTTP methods it is NOT closed at this point.
475      * <p>
476      * After this method is called, {@link #getResponseBodyAsStream} will return
477      * <code>null</code>, and {@link #getResponseBody} and {@link #getResponseBodyAsString}
478      * <em>may</em> return <code>null</code>. 
479      */
480     void releaseConnection();
481 
482     /**
483      * Add a footer to this method's response.
484      * <p>
485      * <b>Note:</b> This method is for
486      * internal use only and should not be called by external clients.
487      * 
488      * @param footer the footer to add
489      * 
490      * @since 2.0
491      */
492     void addResponseFooter(Header footer);
493 
494     /** 
495      * Returns the Status-Line from the most recent response for this method,
496      * or <code>null</code> if the method has not been executed.
497      * 
498      * @return the status line, or <code>null</code> if the method has not been executed
499      * 
500      * @since 2.0
501      */
502     StatusLine getStatusLine();
503 
504     /**
505      * Returns <tt>true</tt> if the HTTP method should automatically handle HTTP 
506      * authentication challenges (status code 401, etc.), <tt>false</tt> otherwise
507      *
508      * @return <tt>true</tt> if authentication challenges will be processed 
509      * automatically, <tt>false</tt> otherwise.
510      * 
511      * @since 2.0
512      * 
513      * @see #setDoAuthentication(boolean)
514      */
515     boolean getDoAuthentication();
516 
517     /**
518      * Sets whether or not the HTTP method should automatically handle HTTP 
519      * authentication challenges (status code 401, etc.)
520      *
521      * @param doAuthentication <tt>true</tt> to process authentication challenges
522      * automatically, <tt>false</tt> otherwise.
523      * 
524      * @since 2.0
525      * 
526      * @see #getDoAuthentication()
527      */
528     void setDoAuthentication(boolean doAuthentication);
529 
530 
531     /**
532      * Returns {@link HttpMethodParams HTTP protocol parameters} associated with this method.
533      * 
534      * @since 3.0
535      * 
536      * @see HttpMethodParams
537      */
538     public HttpMethodParams getParams();
539 
540     /**
541      * Assigns {@link HttpMethodParams HTTP protocol parameters} for this method.
542      * 
543      * @since 3.0
544      * 
545      * @see HttpMethodParams
546      */
547     public void setParams(final HttpMethodParams params);
548 
549     /**
550      * Returns the target host {@link AuthState authentication state}
551      * 
552      * @return host authentication state
553      * 
554      * @since 3.0
555      */
556     public AuthState getHostAuthState();
557 
558     /**
559      * Returns the proxy {@link AuthState authentication state}
560      * 
561      * @return host authentication state
562      * 
563      * @since 3.0
564      */
565     public AuthState getProxyAuthState();
566 
567     /**
568      * Returns <tt>true</tt> if the HTTP has been transmitted to the target
569      * server in its entirety, <tt>false</tt> otherwise. This flag can be useful 
570      * for recovery logic. If the request has not been transmitted in its entirety,
571      * it is safe to retry the failed method.
572      * 
573      * @return <tt>true</tt> if the request has been sent, <tt>false</tt> otherwise
574      */
575     boolean isRequestSent();
576 
577 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpMethodBase.html100644 0 0 702070 10661532627 25707 0ustar 0 0 HttpMethodBase xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethodBase.java,v 1.222 2005/01/14 21:16:40 olegk Exp $
3    * $Revision: 539441 $
4    * $Date: 2007-05-18 14:56:55 +0200 (Fri, 18 May 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.ByteArrayInputStream;
34  import java.io.ByteArrayOutputStream;
35  import java.io.IOException;
36  import java.io.InputStream;
37  import java.io.InterruptedIOException;
38  import java.util.Collection;
39  
40  import org.apache.commons.httpclient.auth.AuthState;
41  import org.apache.commons.httpclient.cookie.CookiePolicy;
42  import org.apache.commons.httpclient.cookie.CookieSpec;
43  import org.apache.commons.httpclient.cookie.CookieVersionSupport;
44  import org.apache.commons.httpclient.cookie.MalformedCookieException;
45  import org.apache.commons.httpclient.params.HttpMethodParams;
46  import org.apache.commons.httpclient.protocol.Protocol;
47  import org.apache.commons.httpclient.util.EncodingUtil;
48  import org.apache.commons.httpclient.util.ExceptionUtil;
49  import org.apache.commons.logging.Log;
50  import org.apache.commons.logging.LogFactory;
51  
52  /**
53   * An abstract base implementation of HttpMethod.
54   * <p>
55   * At minimum, subclasses will need to override:
56   * <ul>
57   *   <li>{@link #getName} to return the approriate name for this method
58   *   </li>
59   * </ul>
60   * </p>
61   *
62   * <p>
63   * When a method requires additional request headers, subclasses will typically
64   * want to override:
65   * <ul>
66   *   <li>{@link #addRequestHeaders addRequestHeaders(HttpState,HttpConnection)}
67   *      to write those headers
68   *   </li>
69   * </ul>
70   * </p>
71   *
72   * <p>
73   * When a method expects specific response headers, subclasses may want to
74   * override:
75   * <ul>
76   *   <li>{@link #processResponseHeaders processResponseHeaders(HttpState,HttpConnection)}
77   *     to handle those headers
78   *   </li>
79   * </ul>
80   * </p>
81   *
82   *
83   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
84   * @author Rodney Waldhoff
85   * @author Sean C. Sullivan
86   * @author <a href="mailto:dion@apache.org">dIon Gillard</a>
87   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
88   * @author <a href="mailto:dims@apache.org">Davanum Srinivas</a>
89   * @author Ortwin Glueck
90   * @author Eric Johnson
91   * @author Michael Becke
92   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
93   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
94   * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
95   * @author Christian Kohlschuetter
96   *
97   * @version $Revision: 539441 $ $Date: 2007-05-18 14:56:55 +0200 (Fri, 18 May 2007) $
98   */
99  public abstract class HttpMethodBase implements HttpMethod {
100 
101     // -------------------------------------------------------------- Constants
102 
103     /** Log object for this class. */
104     private static final Log LOG = LogFactory.getLog(HttpMethodBase.class);
105 
106     // ----------------------------------------------------- Instance variables 
107 
108     /** Request headers, if any. */
109     private HeaderGroup requestHeaders = new HeaderGroup();
110 
111     /** The Status-Line from the response. */
112     protected StatusLine statusLine = null;
113 
114     /** Response headers, if any. */
115     private HeaderGroup responseHeaders = new HeaderGroup();
116 
117     /** Response trailer headers, if any. */
118     private HeaderGroup responseTrailerHeaders = new HeaderGroup();
119 
120     /** Path of the HTTP method. */
121     private String path = null;
122 
123     /** Query string of the HTTP method, if any. */
124     private String queryString = null;
125 
126     /** The response body of the HTTP method, assuming it has not be 
127      * intercepted by a sub-class. */
128     private InputStream responseStream = null;
129 
130     /** The connection that the response stream was read from. */
131     private HttpConnection responseConnection = null;
132 
133     /** Buffer for the response */
134     private byte[] responseBody = null;
135 
136     /** True if the HTTP method should automatically follow HTTP redirects.*/
137     private boolean followRedirects = false;
138 
139     /** True if the HTTP method should automatically handle
140     *  HTTP authentication challenges. */
141     private boolean doAuthentication = true;
142 
143     /** HTTP protocol parameters. */
144     private HttpMethodParams params = new HttpMethodParams();
145 
146     /** Host authentication state */
147     private AuthState hostAuthState = new AuthState();
148 
149     /** Proxy authentication state */
150     private AuthState proxyAuthState = new AuthState();
151 
152     /** True if this method has already been executed. */
153     private boolean used = false;
154 
155     /** Count of how many times did this HTTP method transparently handle 
156     * a recoverable exception. */
157     private int recoverableExceptionCount = 0;
158 
159     /** the host for this HTTP method, can be null */
160     private HttpHost httphost = null;
161 
162     /**
163      * Handles method retries
164      * 
165      * @deprecated no loner used
166      */
167     private MethodRetryHandler methodRetryHandler;
168 
169     /** True if the connection must be closed when no longer needed */
170     private boolean connectionCloseForced = false;
171 
172     /** Number of milliseconds to wait for 100-contunue response. */
173     private static final int RESPONSE_WAIT_TIME_MS = 3000;
174 
175     /** HTTP protocol version used for execution of this method. */
176     protected HttpVersion effectiveVersion = null;
177 
178     /** Whether the execution of this method has been aborted */
179     private volatile boolean aborted = false;
180 
181     /** Whether the HTTP request has been transmitted to the target
182      * server it its entirety */
183     private boolean requestSent = false;
184     
185     /** Actual cookie policy */
186     private CookieSpec cookiespec = null;
187 
188     /** Default initial size of the response buffer if content length is unknown. */
189     private static final int DEFAULT_INITIAL_BUFFER_SIZE = 4*1024; // 4 kB
190     
191     // ----------------------------------------------------------- Constructors
192 
193     /**
194      * No-arg constructor.
195      */
196     public HttpMethodBase() {
197     }
198 
199     /**
200      * Constructor specifying a URI.
201      * It is responsibility of the caller to ensure that URI elements
202      * (path & query parameters) are properly encoded (URL safe).
203      *
204      * @param uri either an absolute or relative URI. The URI is expected
205      *            to be URL-encoded
206      * 
207      * @throws IllegalArgumentException when URI is invalid
208      * @throws IllegalStateException when protocol of the absolute URI is not recognised
209      */
210     public HttpMethodBase(String uri) 
211         throws IllegalArgumentException, IllegalStateException {
212 
213         try {
214 
215             // create a URI and allow for null/empty uri values
216             if (uri == null || uri.equals("")) {
217                 uri = "/";
218             }
219             String charset = getParams().getUriCharset();
220             setURI(new URI(uri, true, charset));
221         } catch (URIException e) {
222             throw new IllegalArgumentException("Invalid uri '" 
223                 + uri + "': " + e.getMessage() 
224             );
225         }
226     }
227 
228     // ------------------------------------------- Property Setters and Getters
229 
230     /**
231      * Obtains the name of the HTTP method as used in the HTTP request line,
232      * for example <tt>"GET"</tt> or <tt>"POST"</tt>.
233      * 
234      * @return the name of this method
235      */
236     public abstract String getName();
237 
238     /**
239      * Returns the URI of the HTTP method
240      * 
241      * @return The URI
242      * 
243      * @throws URIException If the URI cannot be created.
244      * 
245      * @see org.apache.commons.httpclient.HttpMethod#getURI()
246      */
247     public URI getURI() throws URIException {
248         StringBuffer buffer = new StringBuffer();
249         if (this.httphost != null) {
250             buffer.append(this.httphost.getProtocol().getScheme());
251             buffer.append("://");
252             buffer.append(this.httphost.getHostName());
253             int port = this.httphost.getPort();
254             if (port != -1 && port != this.httphost.getProtocol().getDefaultPort()) {
255                 buffer.append(":");
256                 buffer.append(port);
257             }
258         }
259         buffer.append(this.path);
260         if (this.queryString != null) {
261             buffer.append('?');
262             buffer.append(this.queryString);
263         }
264         String charset = getParams().getUriCharset();
265         return new URI(buffer.toString(), true, charset);
266     }
267 
268     /**
269      * Sets the URI for this method. 
270      * 
271      * @param uri URI to be set 
272      * 
273      * @throws URIException if a URI cannot be set
274      * 
275      * @since 3.0
276      */
277     public void setURI(URI uri) throws URIException {
278         // only set the host if specified by the URI
279         if (uri.isAbsoluteURI()) {
280             this.httphost = new HttpHost(uri);
281         }
282         // set the path, defaulting to root
283         setPath(
284             uri.getPath() == null
285             ? "/"
286             : uri.getEscapedPath()
287         );
288         setQueryString(uri.getEscapedQuery());
289     } 
290 
291     /**
292      * Sets whether or not the HTTP method should automatically follow HTTP redirects 
293      * (status code 302, etc.)
294      * 
295      * @param followRedirects <tt>true</tt> if the method will automatically follow redirects,
296      * <tt>false</tt> otherwise.
297      */
298     public void setFollowRedirects(boolean followRedirects) {
299         this.followRedirects = followRedirects;
300     }
301 
302     /**
303      * Returns <tt>true</tt> if the HTTP method should automatically follow HTTP redirects 
304      * (status code 302, etc.), <tt>false</tt> otherwise.
305      * 
306      * @return <tt>true</tt> if the method will automatically follow HTTP redirects, 
307      * <tt>false</tt> otherwise.
308      */
309     public boolean getFollowRedirects() {
310         return this.followRedirects;
311     }
312 
313     /** Sets whether version 1.1 of the HTTP protocol should be used per default.
314      *
315      * @param http11 <tt>true</tt> to use HTTP/1.1, <tt>false</tt> to use 1.0
316      * 
317      * @deprecated Use {@link HttpMethodParams#setVersion(HttpVersion)}
318      */
319     public void setHttp11(boolean http11) {
320         if (http11) {
321             this.params.setVersion(HttpVersion.HTTP_1_1);
322         } else {
323             this.params.setVersion(HttpVersion.HTTP_1_0);
324         } 
325     }
326 
327     /**
328      * Returns <tt>true</tt> if the HTTP method should automatically handle HTTP 
329      * authentication challenges (status code 401, etc.), <tt>false</tt> otherwise
330      *
331      * @return <tt>true</tt> if authentication challenges will be processed 
332      * automatically, <tt>false</tt> otherwise.
333      * 
334      * @since 2.0
335      */
336     public boolean getDoAuthentication() {
337         return doAuthentication;
338     }
339 
340     /**
341      * Sets whether or not the HTTP method should automatically handle HTTP 
342      * authentication challenges (status code 401, etc.)
343      *
344      * @param doAuthentication <tt>true</tt> to process authentication challenges
345      * authomatically, <tt>false</tt> otherwise.
346      * 
347      * @since 2.0
348      */
349     public void setDoAuthentication(boolean doAuthentication) {
350         this.doAuthentication = doAuthentication;
351     }
352 
353     // ---------------------------------------------- Protected Utility Methods
354 
355     /**
356      * Returns <tt>true</tt> if version 1.1 of the HTTP protocol should be 
357      * used per default, <tt>false</tt> if version 1.0 should be used.
358      *
359      * @return <tt>true</tt> to use HTTP/1.1, <tt>false</tt> to use 1.0
360      * 
361      * @deprecated Use {@link HttpMethodParams#getVersion()}
362      */
363     public boolean isHttp11() {
364         return this.params.getVersion().equals(HttpVersion.HTTP_1_1);
365     }
366 
367     /**
368      * Sets the path of the HTTP method.
369      * It is responsibility of the caller to ensure that the path is
370      * properly encoded (URL safe).
371      *
372      * @param path the path of the HTTP method. The path is expected
373      *        to be URL-encoded
374      */
375     public void setPath(String path) {
376         this.path = path;
377     }
378 
379     /**
380      * Adds the specified request header, NOT overwriting any previous value.
381      * Note that header-name matching is case insensitive.
382      *
383      * @param header the header to add to the request
384      */
385     public void addRequestHeader(Header header) {
386         LOG.trace("HttpMethodBase.addRequestHeader(Header)");
387 
388         if (header == null) {
389             LOG.debug("null header value ignored");
390         } else {
391             getRequestHeaderGroup().addHeader(header);
392         }
393     }
394 
395     /**
396      * Use this method internally to add footers.
397      * 
398      * @param footer The footer to add.
399      */
400     public void addResponseFooter(Header footer) {
401         getResponseTrailerHeaderGroup().addHeader(footer);
402     }
403 
404     /**
405      * Gets the path of this HTTP method.
406      * Calling this method <em>after</em> the request has been executed will 
407      * return the <em>actual</em> path, following any redirects automatically
408      * handled by this HTTP method.
409      *
410      * @return the path to request or "/" if the path is blank.
411      */
412     public String getPath() {
413         return (path == null || path.equals("")) ? "/" : path;
414     }
415 
416     /**
417      * Sets the query string of this HTTP method. The caller must ensure that the string 
418      * is properly URL encoded. The query string should not start with the question 
419      * mark character.
420      *
421      * @param queryString the query string
422      * 
423      * @see EncodingUtil#formUrlEncode(NameValuePair[], String)
424      */
425     public void setQueryString(String queryString) {
426         this.queryString = queryString;
427     }
428 
429     /**
430      * Sets the query string of this HTTP method.  The pairs are encoded as UTF-8 characters.  
431      * To use a different charset the parameters can be encoded manually using EncodingUtil 
432      * and set as a single String.
433      *
434      * @param params an array of {@link NameValuePair}s to add as query string
435      *        parameters. The name/value pairs will be automcatically 
436      *        URL encoded
437      * 
438      * @see EncodingUtil#formUrlEncode(NameValuePair[], String)
439      * @see #setQueryString(String)
440      */
441     public void setQueryString(NameValuePair[] params) {
442         LOG.trace("enter HttpMethodBase.setQueryString(NameValuePair[])");
443         queryString = EncodingUtil.formUrlEncode(params, "UTF-8");
444     }
445 
446     /**
447      * Gets the query string of this HTTP method.
448      *
449      * @return The query string
450      */
451     public String getQueryString() {
452         return queryString;
453     }
454 
455     /**
456      * Set the specified request header, overwriting any previous value. Note
457      * that header-name matching is case-insensitive.
458      *
459      * @param headerName the header's name
460      * @param headerValue the header's value
461      */
462     public void setRequestHeader(String headerName, String headerValue) {
463         Header header = new Header(headerName, headerValue);
464         setRequestHeader(header);
465     }
466 
467     /**
468      * Sets the specified request header, overwriting any previous value.
469      * Note that header-name matching is case insensitive.
470      * 
471      * @param header the header
472      */
473     public void setRequestHeader(Header header) {
474         
475         Header[] headers = getRequestHeaderGroup().getHeaders(header.getName());
476         
477         for (int i = 0; i < headers.length; i++) {
478             getRequestHeaderGroup().removeHeader(headers[i]);
479         }
480         
481         getRequestHeaderGroup().addHeader(header);
482         
483     }
484 
485     /**
486      * Returns the specified request header. Note that header-name matching is
487      * case insensitive. <tt>null</tt> will be returned if either
488      * <i>headerName</i> is <tt>null</tt> or there is no matching header for
489      * <i>headerName</i>.
490      * 
491      * @param headerName The name of the header to be returned.
492      *
493      * @return The specified request header.
494      * 
495      * @since 3.0
496      */
497     public Header getRequestHeader(String headerName) {
498         if (headerName == null) {
499             return null;
500         } else {
501             return getRequestHeaderGroup().getCondensedHeader(headerName);
502         }
503     }
504 
505     /**
506      * Returns an array of the requests headers that the HTTP method currently has
507      *
508      * @return an array of my request headers.
509      */
510     public Header[] getRequestHeaders() {
511         return getRequestHeaderGroup().getAllHeaders();
512     }
513 
514     /**
515      * @see org.apache.commons.httpclient.HttpMethod#getRequestHeaders(java.lang.String)
516      */
517     public Header[] getRequestHeaders(String headerName) {
518         return getRequestHeaderGroup().getHeaders(headerName);
519     }
520 
521     /**
522      * Gets the {@link HeaderGroup header group} storing the request headers.
523      * 
524      * @return a HeaderGroup
525      * 
526      * @since 2.0beta1
527      */
528     protected HeaderGroup getRequestHeaderGroup() {
529         return requestHeaders;
530     }
531 
532     /**
533      * Gets the {@link HeaderGroup header group} storing the response trailer headers 
534      * as per RFC 2616 section 3.6.1.
535      * 
536      * @return a HeaderGroup
537      * 
538      * @since 2.0beta1
539      */
540     protected HeaderGroup getResponseTrailerHeaderGroup() {
541         return responseTrailerHeaders;
542     }
543 
544     /**
545      * Gets the {@link HeaderGroup header group} storing the response headers.
546      * 
547      * @return a HeaderGroup
548      * 
549      * @since 2.0beta1
550      */
551     protected HeaderGroup getResponseHeaderGroup() {
552         return responseHeaders;
553     }
554     
555     /**
556      * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders(java.lang.String)
557      * 
558      * @since 3.0
559      */
560     public Header[] getResponseHeaders(String headerName) {
561         return getResponseHeaderGroup().getHeaders(headerName);
562     }
563 
564     /**
565      * Returns the response status code.
566      *
567      * @return the status code associated with the latest response.
568      */
569     public int getStatusCode() {
570         return statusLine.getStatusCode();
571     }
572 
573     /**
574      * Provides access to the response status line.
575      *
576      * @return the status line object from the latest response.
577      * @since 2.0
578      */
579     public StatusLine getStatusLine() {
580         return statusLine;
581     }
582 
583     /**
584      * Checks if response data is available.
585      * @return <tt>true</tt> if response data is available, <tt>false</tt> otherwise.
586      */
587     private boolean responseAvailable() {
588         return (responseBody != null) || (responseStream != null);
589     }
590 
591     /**
592      * Returns an array of the response headers that the HTTP method currently has
593      * in the order in which they were read.
594      *
595      * @return an array of response headers.
596      */
597     public Header[] getResponseHeaders() {
598         return getResponseHeaderGroup().getAllHeaders();
599     }
600 
601     /**
602      * Gets the response header associated with the given name. Header name
603      * matching is case insensitive. <tt>null</tt> will be returned if either
604      * <i>headerName</i> is <tt>null</tt> or there is no matching header for
605      * <i>headerName</i>.
606      *
607      * @param headerName the header name to match
608      *
609      * @return the matching header
610      */
611     public Header getResponseHeader(String headerName) {        
612         if (headerName == null) {
613             return null;
614         } else {
615             return getResponseHeaderGroup().getCondensedHeader(headerName);
616         }        
617     }
618 
619 
620     /**
621      * Return the length (in bytes) of the response body, as specified in a
622      * <tt>Content-Length</tt> header.
623      *
624      * <p>
625      * Return <tt>-1</tt> when the content-length is unknown.
626      * </p>
627      *
628      * @return content length, if <tt>Content-Length</tt> header is available. 
629      *          <tt>0</tt> indicates that the request has no body.
630      *          If <tt>Content-Length</tt> header is not present, the method 
631      *          returns  <tt>-1</tt>.
632      */
633     public long getResponseContentLength() {
634         Header[] headers = getResponseHeaderGroup().getHeaders("Content-Length");
635         if (headers.length == 0) {
636             return -1;
637         }
638         if (headers.length > 1) {
639             LOG.warn("Multiple content-length headers detected");
640         }
641         for (int i = headers.length - 1; i >= 0; i--) {
642             Header header = headers[i];
643             try {
644                 return Long.parseLong(header.getValue());
645             } catch (NumberFormatException e) {
646                 if (LOG.isWarnEnabled()) {
647                     LOG.warn("Invalid content-length value: " + e.getMessage());
648                 }
649             }
650             // See if we can have better luck with another header, if present
651         }
652         return -1;
653     }
654 
655 
656     /**
657      * Returns the response body of the HTTP method, if any, as an array of bytes.
658      * If response body is not available or cannot be read, returns <tt>null</tt>.
659      * Buffers the response and this method can be called several times yielding
660      * the same result each time.
661      * 
662      * Note: This will cause the entire response body to be buffered in memory. A
663      * malicious server may easily exhaust all the VM memory. It is strongly
664      * recommended, to use getResponseAsStream if the content length of the response
665      * is unknown or resonably large.
666      *  
667      * @return The response body.
668      * 
669      * @throws IOException If an I/O (transport) problem occurs while obtaining the 
670      * response body.
671      */
672     public byte[] getResponseBody() throws IOException {
673         if (this.responseBody == null) {
674             InputStream instream = getResponseBodyAsStream();
675             if (instream != null) {
676                 long contentLength = getResponseContentLength();
677                 if (contentLength > Integer.MAX_VALUE) { //guard below cast from overflow
678                     throw new IOException("Content too large to be buffered: "+ contentLength +" bytes");
679                 }
680                 int limit = getParams().getIntParameter(HttpMethodParams.BUFFER_WARN_TRIGGER_LIMIT, 1024*1024);
681                 if ((contentLength == -1) || (contentLength > limit)) {
682                     LOG.warn("Going to buffer response body of large or unknown size. "
683                             +"Using getResponseBodyAsStream instead is recommended.");
684                 }
685                 LOG.debug("Buffering response body");
686                 ByteArrayOutputStream outstream = new ByteArrayOutputStream(
687                         contentLength > 0 ? (int) contentLength : DEFAULT_INITIAL_BUFFER_SIZE);
688                 byte[] buffer = new byte[4096];
689                 int len;
690                 while ((len = instream.read(buffer)) > 0) {
691                     outstream.write(buffer, 0, len);
692                 }
693                 outstream.close();
694                 setResponseStream(null);
695                 this.responseBody = outstream.toByteArray();
696             }
697         }
698         return this.responseBody;
699     }
700 
701     /**
702      * Returns the response body of the HTTP method, if any, as an array of bytes.
703      * If response body is not available or cannot be read, returns <tt>null</tt>.
704      * Buffers the response and this method can be called several times yielding
705      * the same result each time.
706      * 
707      * Note: This will cause the entire response body to be buffered in memory. This method is
708      * safe if the content length of the response is unknown, because the amount of memory used
709      * is limited.<p>
710      * 
711      * If the response is large this method involves lots of array copying and many object 
712      * allocations, which makes it unsuitable for high-performance / low-footprint applications.
713      * Those applications should use {@link #getResponseBodyAsStream()}.
714      * 
715      * @param maxlen the maximum content length to accept (number of bytes). 
716      * @return The response body.
717      * 
718      * @throws IOException If an I/O (transport) problem occurs while obtaining the 
719      * response body.
720      */
721     public byte[] getResponseBody(int maxlen) throws IOException {
722         if (maxlen < 0) throw new IllegalArgumentException("maxlen must be positive");
723         if (this.responseBody == null) {
724             InputStream instream = getResponseBodyAsStream();
725             if (instream != null) {
726                 // we might already know that the content is larger
727                 long contentLength = getResponseContentLength();
728                 if ((contentLength != -1) && (contentLength > maxlen)) {
729                     throw new HttpContentTooLargeException(
730                             "Content-Length is " + contentLength, maxlen);
731                 }
732                 
733                 LOG.debug("Buffering response body");
734                 ByteArrayOutputStream rawdata = new ByteArrayOutputStream(
735                         contentLength > 0 ? (int) contentLength : DEFAULT_INITIAL_BUFFER_SIZE);
736                 byte[] buffer = new byte[2048];
737                 int pos = 0;
738                 int len;
739                 do {
740                     len = instream.read(buffer, 0, Math.min(buffer.length, maxlen-pos));
741                     if (len == -1) break;
742                     rawdata.write(buffer, 0, len);
743                     pos += len;
744                 } while (pos < maxlen);
745                 
746                 setResponseStream(null);
747                 // check if there is even more data
748                 if (pos == maxlen) {
749                     if (instream.read() != -1)
750                         throw new HttpContentTooLargeException(
751                                 "Content-Length not known but larger than "
752                                 + maxlen, maxlen);
753                 }
754                 this.responseBody = rawdata.toByteArray();
755             }
756         }
757         return this.responseBody;
758     }
759 
760     /**
761      * Returns the response body of the HTTP method, if any, as an {@link InputStream}. 
762      * If response body is not available, returns <tt>null</tt>. If the response has been
763      * buffered this method returns a new stream object on every call. If the response
764      * has not been buffered the returned stream can only be read once.
765      * 
766      * @return The response body or <code>null</code>.
767      * 
768      * @throws IOException If an I/O (transport) problem occurs while obtaining the 
769      * response body.
770      */
771     public InputStream getResponseBodyAsStream() throws IOException {
772         if (responseStream != null) {
773             return responseStream;
774         }
775         if (responseBody != null) {
776             InputStream byteResponseStream = new ByteArrayInputStream(responseBody);
777             LOG.debug("re-creating response stream from byte array");
778             return byteResponseStream;
779         }
780         return null;
781     }
782 
783     /**
784      * Returns the response body of the HTTP method, if any, as a {@link String}. 
785      * If response body is not available or cannot be read, returns <tt>null</tt>
786      * The string conversion on the data is done using the character encoding specified
787      * in <tt>Content-Type</tt> header. Buffers the response and this method can be 
788      * called several times yielding the same result each time.
789      * 
790      * Note: This will cause the entire response body to be buffered in memory. A
791      * malicious server may easily exhaust all the VM memory. It is strongly
792      * recommended, to use getResponseAsStream if the content length of the response
793      * is unknown or resonably large.
794      * 
795      * @return The response body or <code>null</code>.
796      * 
797      * @throws IOException If an I/O (transport) problem occurs while obtaining the 
798      * response body.
799      */
800     public String getResponseBodyAsString() throws IOException {
801         byte[] rawdata = null;
802         if (responseAvailable()) {
803             rawdata = getResponseBody();
804         }
805         if (rawdata != null) {
806             return EncodingUtil.getString(rawdata, getResponseCharSet());
807         } else {
808             return null;
809         }
810     }
811     
812     /**
813      * Returns the response body of the HTTP method, if any, as a {@link String}. 
814      * If response body is not available or cannot be read, returns <tt>null</tt>
815      * The string conversion on the data is done using the character encoding specified
816      * in <tt>Content-Type</tt> header. Buffers the response and this method can be 
817      * called several times yielding the same result each time.</p>
818      * 
819      * Note: This will cause the entire response body to be buffered in memory. This method is
820      * safe if the content length of the response is unknown, because the amount of memory used
821      * is limited.<p>
822      * 
823      * If the response is large this method involves lots of array copying and many object 
824      * allocations, which makes it unsuitable for high-performance / low-footprint applications.
825      * Those applications should use {@link #getResponseBodyAsStream()}.
826      * 
827      * @param maxlen the maximum content length to accept (number of bytes). Note that,
828      * depending on the encoding, this is not equal to the number of characters.
829      * @return The response body or <code>null</code>.
830      * 
831      * @throws IOException If an I/O (transport) problem occurs while obtaining the 
832      * response body.
833      */
834     public String getResponseBodyAsString(int maxlen) throws IOException {
835         if (maxlen < 0) throw new IllegalArgumentException("maxlen must be positive");
836         byte[] rawdata = null;
837         if (responseAvailable()) {
838             rawdata = getResponseBody(maxlen);
839         }
840         if (rawdata != null) {
841             return EncodingUtil.getString(rawdata, getResponseCharSet());
842         } else {
843             return null;
844         }
845     }
846 
847     /**
848      * Returns an array of the response footers that the HTTP method currently has
849      * in the order in which they were read.
850      *
851      * @return an array of footers
852      */
853     public Header[] getResponseFooters() {
854         return getResponseTrailerHeaderGroup().getAllHeaders();
855     }
856 
857     /**
858      * Gets the response footer associated with the given name.
859      * Footer name matching is case insensitive.
860      * <tt>null</tt> will be returned if either <i>footerName</i> is
861      * <tt>null</tt> or there is no matching footer for <i>footerName</i>
862      * or there are no footers available.  If there are multiple footers
863      * with the same name, there values will be combined with the ',' separator
864      * as specified by RFC2616.
865      * 
866      * @param footerName the footer name to match
867      * @return the matching footer
868      */
869     public Header getResponseFooter(String footerName) {
870         if (footerName == null) {
871             return null;
872         } else {
873             return getResponseTrailerHeaderGroup().getCondensedHeader(footerName);
874         }
875     }
876 
877     /**
878      * Sets the response stream.
879      * @param responseStream The new response stream.
880      */
881     protected void setResponseStream(InputStream responseStream) {
882         this.responseStream = responseStream;
883     }
884 
885     /**
886      * Returns a stream from which the body of the current response may be read.
887      * If the method has not yet been executed, if <code>responseBodyConsumed</code>
888      * has been called, or if the stream returned by a previous call has been closed,
889      * <code>null</code> will be returned.
890      *
891      * @return the current response stream
892      */
893     protected InputStream getResponseStream() {
894         return responseStream;
895     }
896     
897     /**
898      * Returns the status text (or "reason phrase") associated with the latest
899      * response.
900      * 
901      * @return The status text.
902      */
903     public String getStatusText() {
904         return statusLine.getReasonPhrase();
905     }
906 
907     /**
908      * Defines how strictly HttpClient follows the HTTP protocol specification  
909      * (RFC 2616 and other relevant RFCs). In the strict mode HttpClient precisely
910      * implements the requirements of the specification, whereas in non-strict mode 
911      * it attempts to mimic the exact behaviour of commonly used HTTP agents, 
912      * which many HTTP servers expect.
913      * 
914      * @param strictMode <tt>true</tt> for strict mode, <tt>false</tt> otherwise
915      * 
916      * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)}
917      * to exercise a more granular control over HTTP protocol strictness.
918      */
919     public void setStrictMode(boolean strictMode) {
920         if (strictMode) {
921             this.params.makeStrict();
922         } else {
923             this.params.makeLenient();
924         }
925     }
926 
927     /**
928      * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)}
929      * to exercise a more granular control over HTTP protocol strictness.
930      *
931      * @return <tt>false</tt>
932      */
933     public boolean isStrictMode() {
934         return false;
935     }
936 
937     /**
938      * Adds the specified request header, NOT overwriting any previous value.
939      * Note that header-name matching is case insensitive.
940      *
941      * @param headerName the header's name
942      * @param headerValue the header's value
943      */
944     public void addRequestHeader(String headerName, String headerValue) {
945         addRequestHeader(new Header(headerName, headerValue));
946     }
947 
948     /**
949      * Tests if the connection should be force-closed when no longer needed.
950      * 
951      * @return <code>true</code> if the connection must be closed
952      */
953     protected boolean isConnectionCloseForced() {
954         return this.connectionCloseForced;
955     }
956 
957     /**
958      * Sets whether or not the connection should be force-closed when no longer 
959      * needed. This value should only be set to <code>true</code> in abnormal 
960      * circumstances, such as HTTP protocol violations. 
961      * 
962      * @param b <code>true</code> if the connection must be closed, <code>false</code>
963      * otherwise.
964      */
965     protected void setConnectionCloseForced(boolean b) {
966         if (LOG.isDebugEnabled()) {
967             LOG.debug("Force-close connection: " + b);
968         }
969         this.connectionCloseForced = b;
970     }
971 
972     /**
973      * Tests if the connection should be closed after the method has been executed.
974      * The connection will be left open when using HTTP/1.1 or if <tt>Connection: 
975      * keep-alive</tt> header was sent.
976      * 
977      * @param conn the connection in question
978      * 
979      * @return boolean true if we should close the connection.
980      */
981     protected boolean shouldCloseConnection(HttpConnection conn) {
982         // Connection must be closed due to an abnormal circumstance 
983         if (isConnectionCloseForced()) {
984             LOG.debug("Should force-close connection.");
985             return true;
986         }
987 
988         Header connectionHeader = null;
989         // In case being connected via a proxy server
990         if (!conn.isTransparent()) {
991             // Check for 'proxy-connection' directive
992             connectionHeader = responseHeaders.getFirstHeader("proxy-connection");
993         }
994         // In all cases Check for 'connection' directive
995         // some non-complaint proxy servers send it instread of
996         // expected 'proxy-connection' directive
997         if (connectionHeader == null) {
998             connectionHeader = responseHeaders.getFirstHeader("connection");
999         }
1000         // In case the response does not contain any explict connection
1001         // directives, check whether the request does
1002         if (connectionHeader == null) {
1003             connectionHeader = requestHeaders.getFirstHeader("connection");
1004         }
1005         if (connectionHeader != null) {
1006             if (connectionHeader.getValue().equalsIgnoreCase("close")) {
1007                 if (LOG.isDebugEnabled()) {
1008                     LOG.debug("Should close connection in response to directive: " 
1009                         + connectionHeader.getValue());
1010                 }
1011                 return true;
1012             } else if (connectionHeader.getValue().equalsIgnoreCase("keep-alive")) {
1013                 if (LOG.isDebugEnabled()) {
1014                     LOG.debug("Should NOT close connection in response to directive: " 
1015                         + connectionHeader.getValue());
1016                 }
1017                 return false;
1018             } else {
1019                 if (LOG.isDebugEnabled()) {
1020                     LOG.debug("Unknown directive: " + connectionHeader.toExternalForm());
1021                 }
1022             }
1023         }
1024         LOG.debug("Resorting to protocol version default close connection policy");
1025         // missing or invalid connection header, do the default
1026         if (this.effectiveVersion.greaterEquals(HttpVersion.HTTP_1_1)) {
1027             if (LOG.isDebugEnabled()) {
1028                 LOG.debug("Should NOT close connection, using " + this.effectiveVersion.toString());
1029             }
1030         } else {
1031             if (LOG.isDebugEnabled()) {
1032                 LOG.debug("Should close connection, using " + this.effectiveVersion.toString());
1033             }
1034         }
1035         return this.effectiveVersion.lessEquals(HttpVersion.HTTP_1_0);
1036     }
1037     
1038     /**
1039      * Tests if the this method is ready to be executed.
1040      * 
1041      * @param state the {@link HttpState state} information associated with this method
1042      * @param conn the {@link HttpConnection connection} to be used
1043      * @throws HttpException If the method is in invalid state.
1044      */
1045     private void checkExecuteConditions(HttpState state, HttpConnection conn)
1046     throws HttpException {
1047 
1048         if (state == null) {
1049             throw new IllegalArgumentException("HttpState parameter may not be null");
1050         }
1051         if (conn == null) {
1052             throw new IllegalArgumentException("HttpConnection parameter may not be null");
1053         }
1054         if (this.aborted) {
1055             throw new IllegalStateException("Method has been aborted");
1056         }
1057         if (!validate()) {
1058             throw new ProtocolException("HttpMethodBase object not valid");
1059         }
1060     }
1061 
1062     /**
1063      * Executes this method using the specified <code>HttpConnection</code> and
1064      * <code>HttpState</code>. 
1065      *
1066      * @param state {@link HttpState state} information to associate with this
1067      *        request. Must be non-null.
1068      * @param conn the {@link HttpConnection connection} to used to execute
1069      *        this HTTP method. Must be non-null.
1070      *
1071      * @return the integer status code if one was obtained, or <tt>-1</tt>
1072      *
1073      * @throws IOException if an I/O (transport) error occurs
1074      * @throws HttpException  if a protocol exception occurs.
1075      */
1076     public int execute(HttpState state, HttpConnection conn)
1077         throws HttpException, IOException {
1078                 
1079         LOG.trace("enter HttpMethodBase.execute(HttpState, HttpConnection)");
1080 
1081         // this is our connection now, assign it to a local variable so 
1082         // that it can be released later
1083         this.responseConnection = conn;
1084 
1085         checkExecuteConditions(state, conn);
1086         this.statusLine = null;
1087         this.connectionCloseForced = false;
1088 
1089         conn.setLastResponseInputStream(null);
1090 
1091         // determine the effective protocol version
1092         if (this.effectiveVersion == null) {
1093             this.effectiveVersion = this.params.getVersion(); 
1094         }
1095 
1096         writeRequest(state, conn);
1097         this.requestSent = true;
1098         readResponse(state, conn);
1099         // the method has successfully executed
1100         used = true; 
1101 
1102         return statusLine.getStatusCode();
1103     }
1104 
1105     /**
1106      * Aborts the execution of this method.
1107      * 
1108      * @since 3.0
1109      */
1110     public void abort() {
1111         if (this.aborted) {
1112             return;
1113         }
1114         this.aborted = true;
1115         HttpConnection conn = this.responseConnection; 
1116         if (conn != null) {
1117             conn.close();
1118         }
1119     }
1120 
1121     /**
1122      * Returns <tt>true</tt> if the HTTP method has been already {@link #execute executed},
1123      * but not {@link #recycle recycled}.
1124      * 
1125      * @return <tt>true</tt> if the method has been executed, <tt>false</tt> otherwise
1126      */
1127     public boolean hasBeenUsed() {
1128         return used;
1129     }
1130 
1131     /**
1132      * Recycles the HTTP method so that it can be used again.
1133      * Note that all of the instance variables will be reset
1134      * once this method has been called. This method will also
1135      * release the connection being used by this HTTP method.
1136      * 
1137      * @see #releaseConnection()
1138      * 
1139      * @deprecated no longer supported and will be removed in the future
1140      *             version of HttpClient
1141      */
1142     public void recycle() {
1143         LOG.trace("enter HttpMethodBase.recycle()");
1144 
1145         releaseConnection();
1146 
1147         path = null;
1148         followRedirects = false;
1149         doAuthentication = true;
1150         queryString = null;
1151         getRequestHeaderGroup().clear();
1152         getResponseHeaderGroup().clear();
1153         getResponseTrailerHeaderGroup().clear();
1154         statusLine = null;
1155         effectiveVersion = null;
1156         aborted = false;
1157         used = false;
1158         params = new HttpMethodParams();
1159         responseBody = null;
1160         recoverableExceptionCount = 0;
1161         connectionCloseForced = false;
1162         hostAuthState.invalidate();
1163         proxyAuthState.invalidate();
1164         cookiespec = null;
1165         requestSent = false;
1166     }
1167 
1168     /**
1169      * Releases the connection being used by this HTTP method. In particular the
1170      * connection is used to read the response(if there is one) and will be held
1171      * until the response has been read. If the connection can be reused by other 
1172      * HTTP methods it is NOT closed at this point.
1173      *
1174      * @since 2.0
1175      */
1176     public void releaseConnection() {
1177         try {
1178             if (this.responseStream != null) {
1179                 try {
1180                     // FYI - this may indirectly invoke responseBodyConsumed.
1181                     this.responseStream.close();
1182                 } catch (IOException ignore) {
1183                 }
1184             }
1185         } finally {
1186             ensureConnectionRelease();
1187         }
1188     }
1189 
1190     /**
1191      * Remove the request header associated with the given name. Note that
1192      * header-name matching is case insensitive.
1193      *
1194      * @param headerName the header name
1195      */
1196     public void removeRequestHeader(String headerName) {
1197         
1198         Header[] headers = getRequestHeaderGroup().getHeaders(headerName);
1199         for (int i = 0; i < headers.length; i++) {
1200             getRequestHeaderGroup().removeHeader(headers[i]);
1201         }
1202         
1203     }
1204     
1205     /**
1206      * Removes the given request header.
1207      * 
1208      * @param header the header
1209      */
1210     public void removeRequestHeader(final Header header) {
1211         if (header == null) {
1212             return;
1213         }
1214         getRequestHeaderGroup().removeHeader(header);
1215     }
1216 
1217     // ---------------------------------------------------------------- Queries
1218 
1219     /**
1220      * Returns <tt>true</tt> the method is ready to execute, <tt>false</tt> otherwise.
1221      * 
1222      * @return This implementation always returns <tt>true</tt>.
1223      */
1224     public boolean validate() {
1225         return true;
1226     }
1227 
1228 
1229     /** 
1230      * Returns the actual cookie policy
1231      * 
1232      * @param state HTTP state. TODO: to be removed in the future
1233      * 
1234      * @return cookie spec
1235      */
1236     private CookieSpec getCookieSpec(final HttpState state) {
1237     	if (this.cookiespec == null) {
1238     		int i = state.getCookiePolicy();
1239     		if (i == -1) {
1240         		this.cookiespec = CookiePolicy.getCookieSpec(this.params.getCookiePolicy());
1241     		} else {
1242         		this.cookiespec = CookiePolicy.getSpecByPolicy(i);
1243     		}
1244     		this.cookiespec.setValidDateFormats(
1245             		(Collection)this.params.getParameter(HttpMethodParams.DATE_PATTERNS));
1246     	}
1247     	return this.cookiespec;
1248     }
1249 
1250     /**
1251      * Generates <tt>Cookie</tt> request headers for those {@link Cookie cookie}s
1252      * that match the given host, port and path.
1253      *
1254      * @param state the {@link HttpState state} information associated with this method
1255      * @param conn the {@link HttpConnection connection} used to execute
1256      *        this HTTP method
1257      *
1258      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1259      *                     can be recovered from.
1260      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
1261      *                    cannot be recovered from.
1262      */
1263     protected void addCookieRequestHeader(HttpState state, HttpConnection conn)
1264         throws IOException, HttpException {
1265 
1266         LOG.trace("enter HttpMethodBase.addCookieRequestHeader(HttpState, "
1267                   + "HttpConnection)");
1268 
1269         Header[] cookieheaders = getRequestHeaderGroup().getHeaders("Cookie");
1270         for (int i = 0; i < cookieheaders.length; i++) {
1271             Header cookieheader = cookieheaders[i];
1272             if (cookieheader.isAutogenerated()) {
1273                 getRequestHeaderGroup().removeHeader(cookieheader);
1274             }
1275         }
1276 
1277         CookieSpec matcher = getCookieSpec(state);
1278         String host = this.params.getVirtualHost();
1279         if (host == null) {
1280             host = conn.getHost();
1281         }
1282         Cookie[] cookies = matcher.match(host, conn.getPort(),
1283             getPath(), conn.isSecure(), state.getCookies());
1284         if ((cookies != null) && (cookies.length > 0)) {
1285             if (getParams().isParameterTrue(HttpMethodParams.SINGLE_COOKIE_HEADER)) {
1286                 // In strict mode put all cookies on the same header
1287                 String s = matcher.formatCookies(cookies);
1288                 getRequestHeaderGroup().addHeader(new Header("Cookie", s, true));
1289             } else {
1290                 // In non-strict mode put each cookie on a separate header
1291                 for (int i = 0; i < cookies.length; i++) {
1292                     String s = matcher.formatCookie(cookies[i]);
1293                     getRequestHeaderGroup().addHeader(new Header("Cookie", s, true));
1294                 }
1295             }
1296             if (matcher instanceof CookieVersionSupport) {
1297                 CookieVersionSupport versupport = (CookieVersionSupport) matcher;
1298                 int ver = versupport.getVersion();
1299                 boolean needVersionHeader = false;
1300                 for (int i = 0; i < cookies.length; i++) {
1301                     if (ver != cookies[i].getVersion()) {
1302                         needVersionHeader = true;
1303                     }
1304                 }
1305                 if (needVersionHeader) {
1306                     // Advertise cookie version support
1307                     getRequestHeaderGroup().addHeader(versupport.getVersionHeader());
1308                 }
1309             }
1310         }
1311     }
1312 
1313     /**
1314      * Generates <tt>Host</tt> request header, as long as no <tt>Host</tt> request
1315      * header already exists.
1316      *
1317      * @param state the {@link HttpState state} information associated with this method
1318      * @param conn the {@link HttpConnection connection} used to execute
1319      *        this HTTP method
1320      *
1321      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1322      *                     can be recovered from.
1323      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
1324      *                    cannot be recovered from.
1325      */
1326     protected void addHostRequestHeader(HttpState state, HttpConnection conn)
1327     throws IOException, HttpException {
1328         LOG.trace("enter HttpMethodBase.addHostRequestHeader(HttpState, "
1329                   + "HttpConnection)");
1330 
1331         // Per 19.6.1.1 of RFC 2616, it is legal for HTTP/1.0 based
1332         // applications to send the Host request-header.
1333         // TODO: Add the ability to disable the sending of this header for
1334         //       HTTP/1.0 requests.
1335         String host = this.params.getVirtualHost();
1336         if (host != null) {
1337             LOG.debug("Using virtual host name: " + host);
1338         } else {
1339             host = conn.getHost();
1340         }
1341         int port = conn.getPort();
1342 
1343         // Note: RFC 2616 uses the term "internet host name" for what goes on the
1344         // host line.  It would seem to imply that host should be blank if the
1345         // host is a number instead of an name.  Based on the behavior of web
1346         // browsers, and the fact that RFC 2616 never defines the phrase "internet
1347         // host name", and the bad behavior of HttpClient that follows if we
1348         // send blank, I interpret this as a small misstatement in the RFC, where
1349         // they meant to say "internet host".  So IP numbers get sent as host
1350         // entries too. -- Eric Johnson 12/13/2002
1351         if (LOG.isDebugEnabled()) {
1352             LOG.debug("Adding Host request header");
1353         }
1354 
1355         //appends the port only if not using the default port for the protocol
1356         if (conn.getProtocol().getDefaultPort() != port) {
1357             host += (":" + port);
1358         }
1359 
1360         setRequestHeader("Host", host);
1361     }
1362 
1363     /**
1364      * Generates <tt>Proxy-Connection: Keep-Alive</tt> request header when 
1365      * communicating via a proxy server.
1366      *
1367      * @param state the {@link HttpState state} information associated with this method
1368      * @param conn the {@link HttpConnection connection} used to execute
1369      *        this HTTP method
1370      *
1371      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1372      *                     can be recovered from.
1373      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
1374      *                    cannot be recovered from.
1375      */
1376     protected void addProxyConnectionHeader(HttpState state,
1377                                             HttpConnection conn)
1378     throws IOException, HttpException {
1379         LOG.trace("enter HttpMethodBase.addProxyConnectionHeader("
1380                   + "HttpState, HttpConnection)");
1381         if (!conn.isTransparent()) {
1382         	if (getRequestHeader("Proxy-Connection") == null) {
1383                 addRequestHeader("Proxy-Connection", "Keep-Alive");
1384         	}
1385         }
1386     }
1387 
1388     /**
1389      * Generates all the required request {@link Header header}s 
1390      * to be submitted via the given {@link HttpConnection connection}.
1391      *
1392      * <p>
1393      * This implementation adds <tt>User-Agent</tt>, <tt>Host</tt>,
1394      * <tt>Cookie</tt>, <tt>Authorization</tt>, <tt>Proxy-Authorization</tt>
1395      * and <tt>Proxy-Connection</tt> headers, when appropriate.
1396      * </p>
1397      *
1398      * <p>
1399      * Subclasses may want to override this method to to add additional
1400      * headers, and may choose to invoke this implementation (via
1401      * <tt>super</tt>) to add the "standard" headers.
1402      * </p>
1403      *
1404      * @param state the {@link HttpState state} information associated with this method
1405      * @param conn the {@link HttpConnection connection} used to execute
1406      *        this HTTP method
1407      *
1408      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1409      *                     can be recovered from.
1410      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
1411      *                    cannot be recovered from.
1412      *
1413      * @see #writeRequestHeaders
1414      */
1415     protected void addRequestHeaders(HttpState state, HttpConnection conn)
1416     throws IOException, HttpException {
1417         LOG.trace("enter HttpMethodBase.addRequestHeaders(HttpState, "
1418             + "HttpConnection)");
1419 
1420         addUserAgentRequestHeader(state, conn);
1421         addHostRequestHeader(state, conn);
1422         addCookieRequestHeader(state, conn);
1423         addProxyConnectionHeader(state, conn);
1424     }
1425 
1426     /**
1427      * Generates default <tt>User-Agent</tt> request header, as long as no
1428      * <tt>User-Agent</tt> request header already exists.
1429      *
1430      * @param state the {@link HttpState state} information associated with this method
1431      * @param conn the {@link HttpConnection connection} used to execute
1432      *        this HTTP method
1433      *
1434      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1435      *                     can be recovered from.
1436      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
1437      *                    cannot be recovered from.
1438      */
1439     protected void addUserAgentRequestHeader(HttpState state,
1440                                              HttpConnection conn)
1441     throws IOException, HttpException {
1442         LOG.trace("enter HttpMethodBase.addUserAgentRequestHeaders(HttpState, "
1443             + "HttpConnection)");
1444 
1445         if (getRequestHeader("User-Agent") == null) {
1446             String agent = (String)getParams().getParameter(HttpMethodParams.USER_AGENT);
1447             if (agent == null) {
1448                 agent = "Jakarta Commons-HttpClient";
1449             }
1450             setRequestHeader("User-Agent", agent);
1451         }
1452     }
1453 
1454     /**
1455      * Throws an {@link IllegalStateException} if the HTTP method has been already
1456      * {@link #execute executed}, but not {@link #recycle recycled}.
1457      *
1458      * @throws IllegalStateException if the method has been used and not
1459      *      recycled
1460      */
1461     protected void checkNotUsed() throws IllegalStateException {
1462         if (used) {
1463             throw new IllegalStateException("Already used.");
1464         }
1465     }
1466 
1467     /**
1468      * Throws an {@link IllegalStateException} if the HTTP method has not been
1469      * {@link #execute executed} since last {@link #recycle recycle}.
1470      *
1471      *
1472      * @throws IllegalStateException if not used
1473      */
1474     protected void checkUsed()  throws IllegalStateException {
1475         if (!used) {
1476             throw new IllegalStateException("Not Used.");
1477         }
1478     }
1479 
1480     // ------------------------------------------------- Static Utility Methods
1481 
1482     /**
1483      * Generates HTTP request line according to the specified attributes.
1484      *
1485      * @param connection the {@link HttpConnection connection} used to execute
1486      *        this HTTP method
1487      * @param name the method name generate a request for
1488      * @param requestPath the path string for the request
1489      * @param query the query string for the request
1490      * @param version the protocol version to use (e.g. HTTP/1.0)
1491      *
1492      * @return HTTP request line
1493      */
1494     protected static String generateRequestLine(HttpConnection connection,
1495         String name, String requestPath, String query, String version) {
1496         LOG.trace("enter HttpMethodBase.generateRequestLine(HttpConnection, "
1497             + "String, String, String, String)");
1498 
1499         StringBuffer buf = new StringBuffer();
1500         // Append method name
1501         buf.append(name);
1502         buf.append(" ");
1503         // Absolute or relative URL?
1504         if (!connection.isTransparent()) {
1505             Protocol protocol = connection.getProtocol();
1506             buf.append(protocol.getScheme().toLowerCase());
1507             buf.append("://");
1508             buf.append(connection.getHost());
1509             if ((connection.getPort() != -1) 
1510                 && (connection.getPort() != protocol.getDefaultPort())
1511             ) {
1512                 buf.append(":");
1513                 buf.append(connection.getPort());
1514             }
1515         }
1516         // Append path, if any
1517         if (requestPath == null) {
1518             buf.append("/");
1519         } else {
1520             if (!connection.isTransparent() && !requestPath.startsWith("/")) {
1521                 buf.append("/");
1522             }
1523             buf.append(requestPath);
1524         }
1525         // Append query, if any
1526         if (query != null) {
1527             if (query.indexOf("?") != 0) {
1528                 buf.append("?");
1529             }
1530             buf.append(query);
1531         }
1532         // Append protocol
1533         buf.append(" ");
1534         buf.append(version);
1535         buf.append("\r\n");
1536         
1537         return buf.toString();
1538     }
1539     
1540     /**
1541      * This method is invoked immediately after 
1542      * {@link #readResponseBody(HttpState,HttpConnection)} and can be overridden by
1543      * sub-classes in order to provide custom body processing.
1544      *
1545      * <p>
1546      * This implementation does nothing.
1547      * </p>
1548      *
1549      * @param state the {@link HttpState state} information associated with this method
1550      * @param conn the {@link HttpConnection connection} used to execute
1551      *        this HTTP method
1552      *
1553      * @see #readResponse
1554      * @see #readResponseBody
1555      */
1556     protected void processResponseBody(HttpState state, HttpConnection conn) {
1557     }
1558 
1559     /**
1560      * This method is invoked immediately after 
1561      * {@link #readResponseHeaders(HttpState,HttpConnection)} and can be overridden by
1562      * sub-classes in order to provide custom response headers processing.
1563 
1564      * <p>
1565      * This implementation will handle the <tt>Set-Cookie</tt> and
1566      * <tt>Set-Cookie2</tt> headers, if any, adding the relevant cookies to
1567      * the given {@link HttpState}.
1568      * </p>
1569      *
1570      * @param state the {@link HttpState state} information associated with this method
1571      * @param conn the {@link HttpConnection connection} used to execute
1572      *        this HTTP method
1573      *
1574      * @see #readResponse
1575      * @see #readResponseHeaders
1576      */
1577     protected void processResponseHeaders(HttpState state,
1578         HttpConnection conn) {
1579         LOG.trace("enter HttpMethodBase.processResponseHeaders(HttpState, "
1580             + "HttpConnection)");
1581 
1582         CookieSpec parser = getCookieSpec(state);
1583 
1584         // process set-cookie headers
1585         Header[] headers = getResponseHeaderGroup().getHeaders("set-cookie");
1586         processCookieHeaders(parser, headers, state, conn);
1587 
1588         // see if the cookie spec supports cookie versioning.
1589         if (parser instanceof CookieVersionSupport) {
1590             CookieVersionSupport versupport = (CookieVersionSupport) parser;
1591             if (versupport.getVersion() > 0) {
1592                 // process set-cookie2 headers.
1593                 // Cookie2 will replace equivalent Cookie instances
1594                 headers = getResponseHeaderGroup().getHeaders("set-cookie2");
1595                 processCookieHeaders(parser, headers, state, conn);
1596             }
1597         }
1598     }
1599 
1600     /**
1601      * This method processes the specified cookie headers. It is invoked from
1602      * within {@link #processResponseHeaders(HttpState,HttpConnection)}
1603      *
1604      * @param headers cookie {@link Header}s to be processed
1605      * @param state the {@link HttpState state} information associated with
1606      *        this HTTP method
1607      * @param conn the {@link HttpConnection connection} used to execute
1608      *        this HTTP method
1609      */
1610     protected void processCookieHeaders(
1611             final CookieSpec parser, 
1612             final Header[] headers, 
1613             final HttpState state, 
1614             final HttpConnection conn) {
1615         LOG.trace("enter HttpMethodBase.processCookieHeaders(Header[], HttpState, "
1616                   + "HttpConnection)");
1617 
1618         String host = this.params.getVirtualHost();
1619         if (host == null) {
1620             host = conn.getHost();
1621         }
1622         for (int i = 0; i < headers.length; i++) {
1623             Header header = headers[i];
1624             Cookie[] cookies = null;
1625             try {
1626                 cookies = parser.parse(
1627                   host,
1628                   conn.getPort(),
1629                   getPath(),
1630                   conn.isSecure(),
1631                   header);
1632             } catch (MalformedCookieException e) {
1633                 if (LOG.isWarnEnabled()) {
1634                     LOG.warn("Invalid cookie header: \"" 
1635                         + header.getValue() 
1636                         + "\". " + e.getMessage());
1637                 }
1638             }
1639             if (cookies != null) {
1640                 for (int j = 0; j < cookies.length; j++) {
1641                     Cookie cookie = cookies[j];
1642                     try {
1643                         parser.validate(
1644                           host,
1645                           conn.getPort(),
1646                           getPath(),
1647                           conn.isSecure(),
1648                           cookie);
1649                         state.addCookie(cookie);
1650                         if (LOG.isDebugEnabled()) {
1651                             LOG.debug("Cookie accepted: \"" 
1652                                 + parser.formatCookie(cookie) + "\"");
1653                         }
1654                     } catch (MalformedCookieException e) {
1655                         if (LOG.isWarnEnabled()) {
1656                             LOG.warn("Cookie rejected: \"" + parser.formatCookie(cookie) 
1657                                 + "\". " + e.getMessage());
1658                         }
1659                     }
1660                 }
1661             }
1662         }
1663     }
1664 
1665     /**
1666      * This method is invoked immediately after 
1667      * {@link #readStatusLine(HttpState,HttpConnection)} and can be overridden by
1668      * sub-classes in order to provide custom response status line processing.
1669      *
1670      * @param state the {@link HttpState state} information associated with this method
1671      * @param conn the {@link HttpConnection connection} used to execute
1672      *        this HTTP method
1673      *
1674      * @see #readResponse
1675      * @see #readStatusLine
1676      */
1677     protected void processStatusLine(HttpState state, HttpConnection conn) {
1678     }
1679 
1680     /**
1681      * Reads the response from the given {@link HttpConnection connection}.
1682      *
1683      * <p>
1684      * The response is processed as the following sequence of actions:
1685      *
1686      * <ol>
1687      * <li>
1688      * {@link #readStatusLine(HttpState,HttpConnection)} is
1689      * invoked to read the request line.
1690      * </li>
1691      * <li>
1692      * {@link #processStatusLine(HttpState,HttpConnection)}
1693      * is invoked, allowing the method to process the status line if
1694      * desired.
1695      * </li>
1696      * <li>
1697      * {@link #readResponseHeaders(HttpState,HttpConnection)} is invoked to read
1698      * the associated headers.
1699      * </li>
1700      * <li>
1701      * {@link #processResponseHeaders(HttpState,HttpConnection)} is invoked, allowing
1702      * the method to process the headers if desired.
1703      * </li>
1704      * <li>
1705      * {@link #readResponseBody(HttpState,HttpConnection)} is
1706      * invoked to read the associated body (if any).
1707      * </li>
1708      * <li>
1709      * {@link #processResponseBody(HttpState,HttpConnection)} is invoked, allowing the
1710      * method to process the response body if desired.
1711      * </li>
1712      * </ol>
1713      *
1714      * Subclasses may want to override one or more of the above methods to to
1715      * customize the processing. (Or they may choose to override this method
1716      * if dramatically different processing is required.)
1717      * </p>
1718      *
1719      * @param state the {@link HttpState state} information associated with this method
1720      * @param conn the {@link HttpConnection connection} used to execute
1721      *        this HTTP method
1722      *
1723      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1724      *                     can be recovered from.
1725      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
1726      *                    cannot be recovered from.
1727      */
1728     protected void readResponse(HttpState state, HttpConnection conn)
1729     throws IOException, HttpException {
1730         LOG.trace(
1731         "enter HttpMethodBase.readResponse(HttpState, HttpConnection)");
1732         // Status line & line may have already been received
1733         // if 'expect - continue' handshake has been used
1734         while (this.statusLine == null) {
1735             readStatusLine(state, conn);
1736             processStatusLine(state, conn);
1737             readResponseHeaders(state, conn);
1738             processResponseHeaders(state, conn);
1739             
1740             int status = this.statusLine.getStatusCode();
1741             if ((status >= 100) && (status < 200)) {
1742                 if (LOG.isInfoEnabled()) {
1743                     LOG.info("Discarding unexpected response: " + this.statusLine.toString()); 
1744                 }
1745                 this.statusLine = null;
1746             }
1747         }
1748         readResponseBody(state, conn);
1749         processResponseBody(state, conn);
1750     }
1751 
1752     /**
1753      * Read the response body from the given {@link HttpConnection}.
1754      *
1755      * <p>
1756      * The current implementation wraps the socket level stream with
1757      * an appropriate stream for the type of response (chunked, content-length,
1758      * or auto-close).  If there is no response body, the connection associated
1759      * with the request will be returned to the connection manager.
1760      * </p>
1761      *
1762      * <p>
1763      * Subclasses may want to override this method to to customize the
1764      * processing.
1765      * </p>
1766      *
1767      * @param state the {@link HttpState state} information associated with this method
1768      * @param conn the {@link HttpConnection connection} used to execute
1769      *        this HTTP method
1770      *
1771      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1772      *                     can be recovered from.
1773      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
1774      *                    cannot be recovered from.
1775      *
1776      * @see #readResponse
1777      * @see #processResponseBody
1778      */
1779     protected void readResponseBody(HttpState state, HttpConnection conn)
1780     throws IOException, HttpException {
1781         LOG.trace(
1782             "enter HttpMethodBase.readResponseBody(HttpState, HttpConnection)");
1783 
1784         // assume we are not done with the connection if we get a stream
1785         InputStream stream = readResponseBody(conn);
1786         if (stream == null) {
1787             // done using the connection!
1788             responseBodyConsumed();
1789         } else {
1790             conn.setLastResponseInputStream(stream);
1791             setResponseStream(stream);
1792         }
1793     }
1794 
1795     /**
1796      * Returns the response body as an {@link InputStream input stream}
1797      * corresponding to the values of the <tt>Content-Length</tt> and 
1798      * <tt>Transfer-Encoding</tt> headers. If no response body is available
1799      * returns <tt>null</tt>.
1800      * <p>
1801      *
1802      * @see #readResponse
1803      * @see #processResponseBody
1804      *
1805      * @param conn the {@link HttpConnection connection} used to execute
1806      *        this HTTP method
1807      *
1808      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1809      *                     can be recovered from.
1810      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
1811      *                    cannot be recovered from.
1812      */
1813     private InputStream readResponseBody(HttpConnection conn)
1814         throws HttpException, IOException {
1815 
1816         LOG.trace("enter HttpMethodBase.readResponseBody(HttpConnection)");
1817 
1818         responseBody = null;
1819         InputStream is = conn.getResponseInputStream();
1820         if (Wire.CONTENT_WIRE.enabled()) {
1821             is = new WireLogInputStream(is, Wire.CONTENT_WIRE);
1822         }
1823         boolean canHaveBody = canResponseHaveBody(statusLine.getStatusCode());
1824         InputStream result = null;
1825         Header transferEncodingHeader = responseHeaders.getFirstHeader("Transfer-Encoding");
1826         // We use Transfer-Encoding if present and ignore Content-Length.
1827         // RFC2616, 4.4 item number 3
1828         if (transferEncodingHeader != null) {
1829 
1830             String transferEncoding = transferEncodingHeader.getValue();
1831             if (!"chunked".equalsIgnoreCase(transferEncoding) 
1832                 && !"identity".equalsIgnoreCase(transferEncoding)) {
1833                 if (LOG.isWarnEnabled()) {
1834                     LOG.warn("Unsupported transfer encoding: " + transferEncoding);
1835                 }
1836             }
1837             HeaderElement[] encodings = transferEncodingHeader.getElements();
1838             // The chunked encoding must be the last one applied
1839             // RFC2616, 14.41
1840             int len = encodings.length;            
1841             if ((len > 0) && ("chunked".equalsIgnoreCase(encodings[len - 1].getName()))) { 
1842                 // if response body is empty
1843                 if (conn.isResponseAvailable(conn.getParams().getSoTimeout())) {
1844                     result = new ChunkedInputStream(is, this);
1845                 } else {
1846                     if (getParams().isParameterTrue(HttpMethodParams.STRICT_TRANSFER_ENCODING)) {
1847                         throw new ProtocolException("Chunk-encoded body declared but not sent");
1848                     } else {
1849                         LOG.warn("Chunk-encoded body missing");
1850                     }
1851                 }
1852             } else {
1853                 LOG.info("Response content is not chunk-encoded");
1854                 // The connection must be terminated by closing 
1855                 // the socket as per RFC 2616, 3.6
1856                 setConnectionCloseForced(true);
1857                 result = is;  
1858             }
1859         } else {
1860             long expectedLength = getResponseContentLength();
1861             if (expectedLength == -1) {
1862                 if (canHaveBody && this.effectiveVersion.greaterEquals(HttpVersion.HTTP_1_1)) {
1863                     Header connectionHeader = responseHeaders.getFirstHeader("Connection");
1864                     String connectionDirective = null;
1865                     if (connectionHeader != null) {
1866                         connectionDirective = connectionHeader.getValue();
1867                     }
1868                     if (!"close".equalsIgnoreCase(connectionDirective)) {
1869                         LOG.info("Response content length is not known");
1870                         setConnectionCloseForced(true);
1871                     }
1872                 }
1873                 result = is;            
1874             } else {
1875                 result = new ContentLengthInputStream(is, expectedLength);
1876             }
1877         } 
1878 
1879         // See if the response is supposed to have a response body
1880         if (!canHaveBody) {
1881             result = null;
1882         }
1883         // if there is a result - ALWAYS wrap it in an observer which will
1884         // close the underlying stream as soon as it is consumed, and notify
1885         // the watcher that the stream has been consumed.
1886         if (result != null) {
1887 
1888             result = new AutoCloseInputStream(
1889                 result,
1890                 new ResponseConsumedWatcher() {
1891                     public void responseConsumed() {
1892                         responseBodyConsumed();
1893                     }
1894                 }
1895             );
1896         }
1897 
1898         return result;
1899     }
1900 
1901     /**
1902      * Reads the response headers from the given {@link HttpConnection connection}.
1903      *
1904      * <p>
1905      * Subclasses may want to override this method to to customize the
1906      * processing.
1907      * </p>
1908      *
1909      * <p>
1910      * "It must be possible to combine the multiple header fields into one
1911      * "field-name: field-value" pair, without changing the semantics of the
1912      * message, by appending each subsequent field-value to the first, each
1913      * separated by a comma." - HTTP/1.0 (4.3)
1914      * </p>
1915      *
1916      * @param state the {@link HttpState state} information associated with this method
1917      * @param conn the {@link HttpConnection connection} used to execute
1918      *        this HTTP method
1919      *
1920      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1921      *                     can be recovered from.
1922      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
1923      *                    cannot be recovered from.
1924      *
1925      * @see #readResponse
1926      * @see #processResponseHeaders
1927      */
1928     protected void readResponseHeaders(HttpState state, HttpConnection conn)
1929     throws IOException, HttpException {
1930         LOG.trace("enter HttpMethodBase.readResponseHeaders(HttpState,"
1931             + "HttpConnection)");
1932 
1933         getResponseHeaderGroup().clear();
1934         
1935         Header[] headers = HttpParser.parseHeaders(
1936             conn.getResponseInputStream(), getParams().getHttpElementCharset());
1937         // Wire logging moved to HttpParser
1938         getResponseHeaderGroup().setHeaders(headers);
1939     }
1940 
1941     /**
1942      * Read the status line from the given {@link HttpConnection}, setting my
1943      * {@link #getStatusCode status code} and {@link #getStatusText status
1944      * text}.
1945      *
1946      * <p>
1947      * Subclasses may want to override this method to to customize the
1948      * processing.
1949      * </p>
1950      *
1951      * @param state the {@link HttpState state} information associated with this method
1952      * @param conn the {@link HttpConnection connection} used to execute
1953      *        this HTTP method
1954      *
1955      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1956      *                     can be recovered from.
1957      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
1958      *                    cannot be recovered from.
1959      *
1960      * @see StatusLine
1961      */
1962     protected void readStatusLine(HttpState state, HttpConnection conn)
1963     throws IOException, HttpException {
1964         LOG.trace("enter HttpMethodBase.readStatusLine(HttpState, HttpConnection)");
1965 
1966         final int maxGarbageLines = getParams().
1967             getIntParameter(HttpMethodParams.STATUS_LINE_GARBAGE_LIMIT, Integer.MAX_VALUE);
1968 
1969         //read out the HTTP status string
1970         int count = 0;
1971         String s;
1972         do {
1973             s = conn.readLine(getParams().getHttpElementCharset());
1974             if (s == null && count == 0) {
1975                 // The server just dropped connection on us
1976                 throw new NoHttpResponseException("The server " + conn.getHost() + 
1977                     " failed to respond");
1978             }
1979             if (Wire.HEADER_WIRE.enabled()) {
1980                 Wire.HEADER_WIRE.input(s + "\r\n");
1981             }
1982             if (s != null && StatusLine.startsWithHTTP(s)) {
1983                 // Got one
1984                 break;
1985             } else if (s == null || count >= maxGarbageLines) {
1986                 // Giving up
1987                 throw new ProtocolException("The server " + conn.getHost() + 
1988                         " failed to respond with a valid HTTP response");
1989             }
1990             count++;
1991         } while(true);
1992 
1993         //create the status line from the status string
1994         statusLine = new StatusLine(s);
1995 
1996         //check for a valid HTTP-Version
1997         String versionStr = statusLine.getHttpVersion();
1998         if (getParams().isParameterFalse(HttpMethodParams.UNAMBIGUOUS_STATUS_LINE) 
1999            && versionStr.equals("HTTP")) {
2000             getParams().setVersion(HttpVersion.HTTP_1_0);
2001             if (LOG.isWarnEnabled()) {
2002                 LOG.warn("Ambiguous status line (HTTP protocol version missing):" +
2003                 statusLine.toString());
2004             }
2005         } else {
2006             this.effectiveVersion = HttpVersion.parse(versionStr);
2007         }
2008 
2009     }
2010 
2011     // ------------------------------------------------------ Protected Methods
2012 
2013     /**
2014      * <p>
2015      * Sends the request via the given {@link HttpConnection connection}.
2016      * </p>
2017      *
2018      * <p>
2019      * The request is written as the following sequence of actions:
2020      * </p>
2021      *
2022      * <ol>
2023      * <li>
2024      * {@link #writeRequestLine(HttpState, HttpConnection)} is invoked to 
2025      * write the request line.
2026      * </li>
2027      * <li>
2028      * {@link #writeRequestHeaders(HttpState, HttpConnection)} is invoked 
2029      * to write the associated headers.
2030      * </li>
2031      * <li>
2032      * <tt>\r\n</tt> is sent to close the head part of the request.
2033      * </li>
2034      * <li>
2035      * {@link #writeRequestBody(HttpState, HttpConnection)} is invoked to 
2036      * write the body part of the request.
2037      * </li>
2038      * </ol>
2039      *
2040      * <p>
2041      * Subclasses may want to override one or more of the above methods to to
2042      * customize the processing. (Or they may choose to override this method
2043      * if dramatically different processing is required.)
2044      * </p>
2045      *
2046      * @param state the {@link HttpState state} information associated with this method
2047      * @param conn the {@link HttpConnection connection} used to execute
2048      *        this HTTP method
2049      *
2050      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
2051      *                     can be recovered from.
2052      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
2053      *                    cannot be recovered from.
2054      */
2055     protected void writeRequest(HttpState state, HttpConnection conn)
2056     throws IOException, HttpException {
2057         LOG.trace(
2058             "enter HttpMethodBase.writeRequest(HttpState, HttpConnection)");
2059         writeRequestLine(state, conn);
2060         writeRequestHeaders(state, conn);
2061         conn.writeLine(); // close head
2062         if (Wire.HEADER_WIRE.enabled()) {
2063             Wire.HEADER_WIRE.output("\r\n");
2064         }
2065 
2066         HttpVersion ver = getParams().getVersion();
2067         Header expectheader = getRequestHeader("Expect");
2068         String expectvalue = null;
2069         if (expectheader != null) {
2070             expectvalue = expectheader.getValue();
2071         }
2072         if ((expectvalue != null) 
2073          && (expectvalue.compareToIgnoreCase("100-continue") == 0)) {
2074             if (ver.greaterEquals(HttpVersion.HTTP_1_1)) {
2075 
2076                 // make sure the status line and headers have been sent
2077                 conn.flushRequestOutputStream();
2078                 
2079                 int readTimeout = conn.getParams().getSoTimeout();
2080                 try {
2081                     conn.setSocketTimeout(RESPONSE_WAIT_TIME_MS);
2082                     readStatusLine(state, conn);
2083                     processStatusLine(state, conn);
2084                     readResponseHeaders(state, conn);
2085                     processResponseHeaders(state, conn);
2086 
2087                     if (this.statusLine.getStatusCode() == HttpStatus.SC_CONTINUE) {
2088                         // Discard status line
2089                         this.statusLine = null;
2090                         LOG.debug("OK to continue received");
2091                     } else {
2092                         return;
2093                     }
2094                 } catch (InterruptedIOException e) {
2095                     if (!ExceptionUtil.isSocketTimeoutException(e)) {
2096                         throw e;
2097                     }
2098                     // Most probably Expect header is not recongnized
2099                     // Remove the header to signal the method 
2100                     // that it's okay to go ahead with sending data
2101                     removeRequestHeader("Expect");
2102                     LOG.info("100 (continue) read timeout. Resume sending the request");
2103                 } finally {
2104                     conn.setSocketTimeout(readTimeout);
2105                 }
2106                 
2107             } else {
2108                 removeRequestHeader("Expect");
2109                 LOG.info("'Expect: 100-continue' handshake is only supported by "
2110                     + "HTTP/1.1 or higher");
2111             }
2112         }
2113 
2114         writeRequestBody(state, conn);
2115         // make sure the entire request body has been sent
2116         conn.flushRequestOutputStream();
2117     }
2118 
2119     /**
2120      * Writes the request body to the given {@link HttpConnection connection}.
2121      *
2122      * <p>
2123      * This method should return <tt>true</tt> if the request body was actually
2124      * sent (or is empty), or <tt>false</tt> if it could not be sent for some
2125      * reason.
2126      * </p>
2127      *
2128      * <p>
2129      * This implementation writes nothing and returns <tt>true</tt>.
2130      * </p>
2131      *
2132      * @param state the {@link HttpState state} information associated with this method
2133      * @param conn the {@link HttpConnection connection} used to execute
2134      *        this HTTP method
2135      *
2136      * @return <tt>true</tt>
2137      *
2138      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
2139      *                     can be recovered from.
2140      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
2141      *                    cannot be recovered from.
2142      */
2143     protected boolean writeRequestBody(HttpState state, HttpConnection conn)
2144     throws IOException, HttpException {
2145         return true;
2146     }
2147 
2148     /**
2149      * Writes the request headers to the given {@link HttpConnection connection}.
2150      *
2151      * <p>
2152      * This implementation invokes {@link #addRequestHeaders(HttpState,HttpConnection)},
2153      * and then writes each header to the request stream.
2154      * </p>
2155      *
2156      * <p>
2157      * Subclasses may want to override this method to to customize the
2158      * processing.
2159      * </p>
2160      *
2161      * @param state the {@link HttpState state} information associated with this method
2162      * @param conn the {@link HttpConnection connection} used to execute
2163      *        this HTTP method
2164      *
2165      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
2166      *                     can be recovered from.
2167      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
2168      *                    cannot be recovered from.
2169      *
2170      * @see #addRequestHeaders
2171      * @see #getRequestHeaders
2172      */
2173     protected void writeRequestHeaders(HttpState state, HttpConnection conn)
2174     throws IOException, HttpException {
2175         LOG.trace("enter HttpMethodBase.writeRequestHeaders(HttpState,"
2176             + "HttpConnection)");
2177         addRequestHeaders(state, conn);
2178 
2179         String charset = getParams().getHttpElementCharset();
2180         
2181         Header[] headers = getRequestHeaders();
2182         for (int i = 0; i < headers.length; i++) {
2183             String s = headers[i].toExternalForm();
2184             if (Wire.HEADER_WIRE.enabled()) {
2185                 Wire.HEADER_WIRE.output(s);
2186             }
2187             conn.print(s, charset);
2188         }
2189     }
2190 
2191     /**
2192      * Writes the request line to the given {@link HttpConnection connection}.
2193      *
2194      * <p>
2195      * Subclasses may want to override this method to to customize the
2196      * processing.
2197      * </p>
2198      *
2199      * @param state the {@link HttpState state} information associated with this method
2200      * @param conn the {@link HttpConnection connection} used to execute
2201      *        this HTTP method
2202      *
2203      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
2204      *                     can be recovered from.
2205      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
2206      *                    cannot be recovered from.
2207      *
2208      * @see #generateRequestLine
2209      */
2210     protected void writeRequestLine(HttpState state, HttpConnection conn)
2211     throws IOException, HttpException {
2212         LOG.trace(
2213             "enter HttpMethodBase.writeRequestLine(HttpState, HttpConnection)");
2214         String requestLine = getRequestLine(conn);
2215         if (Wire.HEADER_WIRE.enabled()) {
2216             Wire.HEADER_WIRE.output(requestLine);
2217         }
2218         conn.print(requestLine, getParams().getHttpElementCharset());
2219     }
2220 
2221     /**
2222      * Returns the request line.
2223      * 
2224      * @param conn the {@link HttpConnection connection} used to execute
2225      *        this HTTP method
2226      * 
2227      * @return The request line.
2228      */
2229     private String getRequestLine(HttpConnection conn) {
2230         return  HttpMethodBase.generateRequestLine(conn, getName(),
2231                 getPath(), getQueryString(), this.effectiveVersion.toString());
2232     }
2233 
2234     /**
2235      * Returns {@link HttpMethodParams HTTP protocol parameters} associated with this method.
2236      *
2237      * @return HTTP parameters.
2238      *
2239      * @since 3.0
2240      */
2241     public HttpMethodParams getParams() {
2242         return this.params;
2243     }
2244 
2245     /**
2246      * Assigns {@link HttpMethodParams HTTP protocol parameters} for this method.
2247      * 
2248      * @since 3.0
2249      * 
2250      * @see HttpMethodParams
2251      */
2252     public void setParams(final HttpMethodParams params) {
2253         if (params == null) {
2254             throw new IllegalArgumentException("Parameters may not be null");
2255         }
2256         this.params = params;
2257     }
2258 
2259     /**
2260      * Returns the HTTP version used with this method (may be <tt>null</tt>
2261      * if undefined, that is, the method has not been executed)
2262      *
2263      * @return HTTP version.
2264      *
2265      * @since 3.0
2266      */
2267     public HttpVersion getEffectiveVersion() {
2268         return this.effectiveVersion;
2269     }
2270 
2271     /**
2272      * Per RFC 2616 section 4.3, some response can never contain a message
2273      * body.
2274      *
2275      * @param status - the HTTP status code
2276      *
2277      * @return <tt>true</tt> if the message may contain a body, <tt>false</tt> if it can not
2278      *         contain a message body
2279      */
2280     private static boolean canResponseHaveBody(int status) {
2281         LOG.trace("enter HttpMethodBase.canResponseHaveBody(int)");
2282 
2283         boolean result = true;
2284 
2285         if ((status >= 100 && status <= 199) || (status == 204)
2286             || (status == 304)) { // NOT MODIFIED
2287             result = false;
2288         }
2289 
2290         return result;
2291     }
2292 
2293     /**
2294      * Returns proxy authentication realm, if it has been used during authentication process. 
2295      * Otherwise returns <tt>null</tt>.
2296      * 
2297      * @return proxy authentication realm
2298      * 
2299      * @deprecated use #getProxyAuthState()
2300      */
2301     public String getProxyAuthenticationRealm() {
2302         return this.proxyAuthState.getRealm();
2303     }
2304 
2305     /**
2306      * Returns authentication realm, if it has been used during authentication process. 
2307      * Otherwise returns <tt>null</tt>.
2308      * 
2309      * @return authentication realm
2310      * 
2311      * @deprecated use #getHostAuthState()
2312      */
2313     public String getAuthenticationRealm() {
2314         return this.hostAuthState.getRealm();
2315     }
2316 
2317     /**
2318      * Returns the character set from the <tt>Content-Type</tt> header.
2319      * 
2320      * @param contentheader The content header.
2321      * @return String The character set.
2322      */
2323     protected String getContentCharSet(Header contentheader) {
2324         LOG.trace("enter getContentCharSet( Header contentheader )");
2325         String charset = null;
2326         if (contentheader != null) {
2327             HeaderElement values[] = contentheader.getElements();
2328             // I expect only one header element to be there
2329             // No more. no less
2330             if (values.length == 1) {
2331                 NameValuePair param = values[0].getParameterByName("charset");
2332                 if (param != null) {
2333                     // If I get anything "funny" 
2334                     // UnsupportedEncondingException will result
2335                     charset = param.getValue();
2336                 }
2337             }
2338         }
2339         if (charset == null) {
2340             charset = getParams().getContentCharset();
2341             if (LOG.isDebugEnabled()) {
2342                 LOG.debug("Default charset used: " + charset);
2343             }
2344         }
2345         return charset;
2346     }
2347 
2348 
2349     /**
2350      * Returns the character encoding of the request from the <tt>Content-Type</tt> header.
2351      * 
2352      * @return String The character set.
2353      */
2354     public String getRequestCharSet() {
2355         return getContentCharSet(getRequestHeader("Content-Type"));
2356     }
2357 
2358 
2359     /**  
2360      * Returns the character encoding of the response from the <tt>Content-Type</tt> header.
2361      * 
2362      * @return String The character set.
2363      */
2364     public String getResponseCharSet() {
2365         return getContentCharSet(getResponseHeader("Content-Type"));
2366     }
2367 
2368     /**
2369      * @deprecated no longer used
2370      * 
2371      * Returns the number of "recoverable" exceptions thrown and handled, to
2372      * allow for monitoring the quality of the connection.
2373      *
2374      * @return The number of recoverable exceptions handled by the method.
2375      */
2376     public int getRecoverableExceptionCount() {
2377         return recoverableExceptionCount;
2378     }
2379 
2380     /**
2381      * A response has been consumed.
2382      *
2383      * <p>The default behavior for this class is to check to see if the connection
2384      * should be closed, and close if need be, and to ensure that the connection
2385      * is returned to the connection manager - if and only if we are not still
2386      * inside the execute call.</p>
2387      *
2388      */
2389     protected void responseBodyConsumed() {
2390 
2391         // make sure this is the initial invocation of the notification,
2392         // ignore subsequent ones.
2393         responseStream = null;
2394         if (responseConnection != null) {
2395             responseConnection.setLastResponseInputStream(null);
2396 
2397             // At this point, no response data should be available.
2398             // If there is data available, regard the connection as being
2399             // unreliable and close it.
2400             
2401             if (shouldCloseConnection(responseConnection)) {
2402                 responseConnection.close();
2403             } else {
2404                 try {
2405                     if(responseConnection.isResponseAvailable()) {
2406                         boolean logExtraInput =
2407                             getParams().isParameterTrue(HttpMethodParams.WARN_EXTRA_INPUT);
2408 
2409                         if(logExtraInput) {
2410                             LOG.warn("Extra response data detected - closing connection");
2411                         } 
2412                         responseConnection.close();
2413                     }
2414                 }
2415                 catch (IOException e) {
2416                     LOG.warn(e.getMessage());
2417                     responseConnection.close();
2418                 }
2419             }
2420         }
2421         this.connectionCloseForced = false;
2422         ensureConnectionRelease();
2423     }
2424 
2425     /**
2426      * Insure that the connection is released back to the pool.
2427      */
2428     private void ensureConnectionRelease() {
2429         if (responseConnection != null) {
2430             responseConnection.releaseConnection();
2431             responseConnection = null;
2432         }
2433     }
2434 
2435     /**
2436      * Returns the {@link HostConfiguration host configuration}.
2437      * 
2438      * @return the host configuration
2439      * 
2440      * @deprecated no longer applicable
2441      */
2442     public HostConfiguration getHostConfiguration() {
2443         HostConfiguration hostconfig = new HostConfiguration();
2444         hostconfig.setHost(this.httphost);
2445         return hostconfig;
2446     }
2447     /**
2448      * Sets the {@link HostConfiguration host configuration}.
2449      * 
2450      * @param hostconfig The hostConfiguration to set
2451      * 
2452      * @deprecated no longer applicable
2453      */
2454     public void setHostConfiguration(final HostConfiguration hostconfig) {
2455         if (hostconfig != null) {
2456             this.httphost = new HttpHost(
2457                     hostconfig.getHost(),
2458                     hostconfig.getPort(),
2459                     hostconfig.getProtocol());
2460         } else {
2461             this.httphost = null;
2462         }
2463     }
2464 
2465     /**
2466      * Returns the {@link MethodRetryHandler retry handler} for this HTTP method
2467      * 
2468      * @return the methodRetryHandler
2469      * 
2470      * @deprecated use {@link HttpMethodParams}
2471      */
2472     public MethodRetryHandler getMethodRetryHandler() {
2473         return methodRetryHandler;
2474     }
2475 
2476     /**
2477      * Sets the {@link MethodRetryHandler retry handler} for this HTTP method
2478      * 
2479      * @param handler the methodRetryHandler to use when this method executed
2480      * 
2481      * @deprecated use {@link HttpMethodParams}
2482      */
2483     public void setMethodRetryHandler(MethodRetryHandler handler) {
2484         methodRetryHandler = handler;
2485     }
2486 
2487     /**
2488      * This method is a dirty hack intended to work around 
2489      * current (2.0) design flaw that prevents the user from
2490      * obtaining correct status code, headers and response body from the 
2491      * preceding HTTP CONNECT method.
2492      * 
2493      * TODO: Remove this crap as soon as possible
2494      */
2495     void fakeResponse(
2496         StatusLine statusline, 
2497         HeaderGroup responseheaders,
2498         InputStream responseStream
2499     ) {
2500         // set used so that the response can be read
2501         this.used = true;
2502         this.statusLine = statusline;
2503         this.responseHeaders = responseheaders;
2504         this.responseBody = null;
2505         this.responseStream = responseStream;
2506     }
2507     
2508     /**
2509      * Returns the target host {@link AuthState authentication state}
2510      * 
2511      * @return host authentication state
2512      * 
2513      * @since 3.0
2514      */
2515     public AuthState getHostAuthState() {
2516         return this.hostAuthState;
2517     }
2518 
2519     /**
2520      * Returns the proxy {@link AuthState authentication state}
2521      * 
2522      * @return host authentication state
2523      * 
2524      * @since 3.0
2525      */
2526     public AuthState getProxyAuthState() {
2527         return this.proxyAuthState;
2528     }
2529     
2530     /**
2531      * Tests whether the execution of this method has been aborted
2532      * 
2533      * @return <tt>true</tt> if the execution of this method has been aborted,
2534      *  <tt>false</tt> otherwise
2535      * 
2536      * @since 3.0
2537      */
2538     public boolean isAborted() {
2539         return this.aborted;
2540     }
2541     
2542     /**
2543      * Returns <tt>true</tt> if the HTTP has been transmitted to the target
2544      * server in its entirety, <tt>false</tt> otherwise. This flag can be useful 
2545      * for recovery logic. If the request has not been transmitted in its entirety,
2546      * it is safe to retry the failed method.
2547      * 
2548      * @return <tt>true</tt> if the request has been sent, <tt>false</tt> otherwise
2549      */
2550     public boolean isRequestSent() {
2551         return this.requestSent;
2552     }
2553     
2554 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpMethodDirector.html100644 0 0 260372 10661532627 26614 0ustar 0 0 HttpMethodDirector xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethodDirector.java,v 1.34 2005/01/14 19:40:39 olegk Exp $
3    * $Revision: 486658 $
4    * $Date: 2006-12-13 15:05:50 +0100 (Wed, 13 Dec 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.util.Collection;
35  import java.util.HashSet;
36  import java.util.Iterator;
37  import java.util.Map;
38  import java.util.Set;
39  
40  import org.apache.commons.httpclient.auth.AuthChallengeException;
41  import org.apache.commons.httpclient.auth.AuthChallengeParser;
42  import org.apache.commons.httpclient.auth.AuthChallengeProcessor;
43  import org.apache.commons.httpclient.auth.AuthScheme;
44  import org.apache.commons.httpclient.auth.AuthState;
45  import org.apache.commons.httpclient.auth.AuthenticationException;
46  import org.apache.commons.httpclient.auth.CredentialsProvider;
47  import org.apache.commons.httpclient.auth.CredentialsNotAvailableException;
48  import org.apache.commons.httpclient.auth.AuthScope;
49  import org.apache.commons.httpclient.auth.MalformedChallengeException;
50  import org.apache.commons.httpclient.params.HostParams;
51  import org.apache.commons.httpclient.params.HttpClientParams;
52  import org.apache.commons.httpclient.params.HttpConnectionParams;
53  import org.apache.commons.httpclient.params.HttpMethodParams;
54  import org.apache.commons.httpclient.params.HttpParams;
55  import org.apache.commons.logging.Log;
56  import org.apache.commons.logging.LogFactory;
57  
58  /**
59   * Handles the process of executing a method including authentication, redirection and retries.
60   * 
61   * @since 3.0
62   */
63  class HttpMethodDirector {
64  
65      /** The www authenticate challange header. */
66      public static final String WWW_AUTH_CHALLENGE = "WWW-Authenticate";
67  
68      /** The www authenticate response header. */
69      public static final String WWW_AUTH_RESP = "Authorization";
70  
71      /** The proxy authenticate challange header. */
72      public static final String PROXY_AUTH_CHALLENGE = "Proxy-Authenticate";
73  
74      /** The proxy authenticate response header. */
75      public static final String PROXY_AUTH_RESP = "Proxy-Authorization";
76  
77      private static final Log LOG = LogFactory.getLog(HttpMethodDirector.class);
78  
79      private ConnectMethod connectMethod;
80      
81      private HttpState state;
82  	
83      private HostConfiguration hostConfiguration;
84      
85      private HttpConnectionManager connectionManager;
86      
87      private HttpClientParams params;
88      
89      private HttpConnection conn;
90      
91      /** A flag to indicate if the connection should be released after the method is executed. */
92      private boolean releaseConnection = false;
93  
94      /** Authentication processor */
95      private AuthChallengeProcessor authProcessor = null;
96  
97      private Set redirectLocations = null; 
98      
99      public HttpMethodDirector(
100         final HttpConnectionManager connectionManager,
101         final HostConfiguration hostConfiguration,
102         final HttpClientParams params,
103         final HttpState state
104     ) {
105         super();
106         this.connectionManager = connectionManager;
107         this.hostConfiguration = hostConfiguration;
108         this.params = params;
109         this.state = state;
110         this.authProcessor = new AuthChallengeProcessor(this.params);
111     }
112     
113 	
114     /**
115      * Executes the method associated with this method director.
116      * 
117      * @throws IOException
118      * @throws HttpException
119      */
120     public void executeMethod(final HttpMethod method) throws IOException, HttpException {
121         if (method == null) {
122             throw new IllegalArgumentException("Method may not be null");
123         }
124         // Link all parameter collections to form the hierarchy:
125         // Global -> HttpClient -> HostConfiguration -> HttpMethod
126         this.hostConfiguration.getParams().setDefaults(this.params);
127         method.getParams().setDefaults(this.hostConfiguration.getParams());
128         
129         // Generate default request headers
130         Collection defaults = (Collection)this.hostConfiguration.getParams().
131 			getParameter(HostParams.DEFAULT_HEADERS);
132         if (defaults != null) {
133         	Iterator i = defaults.iterator();
134         	while (i.hasNext()) {
135         		method.addRequestHeader((Header)i.next());
136         	}
137         }
138         
139         try {
140             int maxRedirects = this.params.getIntParameter(HttpClientParams.MAX_REDIRECTS, 100);
141 
142             for (int redirectCount = 0;;) {
143 
144                 // make sure the connection we have is appropriate
145                 if (this.conn != null && !hostConfiguration.hostEquals(this.conn)) {
146                     this.conn.setLocked(false);
147                     this.conn.releaseConnection();
148                     this.conn = null;
149                 }
150         
151                 // get a connection, if we need one
152                 if (this.conn == null) {
153                     this.conn = connectionManager.getConnectionWithTimeout(
154                         hostConfiguration,
155                         this.params.getConnectionManagerTimeout() 
156                     );
157                     this.conn.setLocked(true);
158                     if (this.params.isAuthenticationPreemptive()
159                      || this.state.isAuthenticationPreemptive()) 
160                     {
161                         LOG.debug("Preemptively sending default basic credentials");
162                         method.getHostAuthState().setPreemptive();
163                         method.getHostAuthState().setAuthAttempted(true);
164                         if (this.conn.isProxied() && !this.conn.isSecure()) {
165                             method.getProxyAuthState().setPreemptive();
166                             method.getProxyAuthState().setAuthAttempted(true);
167                         }
168                     }
169                 }
170                 authenticate(method);
171                 executeWithRetry(method);
172                 if (this.connectMethod != null) {
173                     fakeResponse(method);
174                     break;
175                 }
176                 
177                 boolean retry = false;
178                 if (isRedirectNeeded(method)) {
179                     if (processRedirectResponse(method)) {
180                         retry = true;
181                         ++redirectCount;
182                         if (redirectCount >= maxRedirects) {
183                             LOG.error("Narrowly avoided an infinite loop in execute");
184                             throw new RedirectException("Maximum redirects ("
185                                 + maxRedirects + ") exceeded");
186                         }
187                         if (LOG.isDebugEnabled()) {
188                             LOG.debug("Execute redirect " + redirectCount + " of " + maxRedirects);
189                         }
190                     }
191                 }
192                 if (isAuthenticationNeeded(method)) {
193                     if (processAuthenticationResponse(method)) {
194                         LOG.debug("Retry authentication");
195                         retry = true;
196                     }
197                 }
198                 if (!retry) {
199                     break;
200                 }
201                 // retry - close previous stream.  Caution - this causes
202                 // responseBodyConsumed to be called, which may also close the
203                 // connection.
204                 if (method.getResponseBodyAsStream() != null) {
205                     method.getResponseBodyAsStream().close();
206                 }
207 
208             } //end of retry loop
209         } finally {
210             if (this.conn != null) {
211                 this.conn.setLocked(false);
212             }
213             // If the response has been fully processed, return the connection
214             // to the pool.  Use this flag, rather than other tests (like
215             // responseStream == null), as subclasses, might reset the stream,
216             // for example, reading the entire response into a file and then
217             // setting the file as the stream.
218             if (
219                 (releaseConnection || method.getResponseBodyAsStream() == null) 
220                 && this.conn != null
221             ) {
222                 this.conn.releaseConnection();
223             }
224         }
225 
226     }
227 
228     
229     private void authenticate(final HttpMethod method) {
230         try {
231             if (this.conn.isProxied() && !this.conn.isSecure()) {
232                 authenticateProxy(method);
233             }
234             authenticateHost(method);
235         } catch (AuthenticationException e) {
236             LOG.error(e.getMessage(), e);
237         }
238     }
239 
240 
241     private boolean cleanAuthHeaders(final HttpMethod method, final String name) {
242         Header[] authheaders = method.getRequestHeaders(name);
243         boolean clean = true;
244         for (int i = 0; i < authheaders.length; i++) {
245             Header authheader = authheaders[i];
246             if (authheader.isAutogenerated()) {
247                 method.removeRequestHeader(authheader);
248             } else {
249                 clean = false;
250             }
251         }
252         return clean;
253     }
254     
255 
256     private void authenticateHost(final HttpMethod method) throws AuthenticationException {
257         // Clean up existing authentication headers
258         if (!cleanAuthHeaders(method, WWW_AUTH_RESP)) {
259             // User defined authentication header(s) present
260             return;
261         }
262         AuthState authstate = method.getHostAuthState();
263         AuthScheme authscheme = authstate.getAuthScheme();
264         if (authscheme == null) {
265             return;
266         }
267         if (authstate.isAuthRequested() || !authscheme.isConnectionBased()) {
268             String host = method.getParams().getVirtualHost();
269             if (host == null) {
270                 host = conn.getHost();
271             }
272             int port = conn.getPort();
273             AuthScope authscope = new AuthScope(
274                 host, port, 
275                 authscheme.getRealm(), 
276                 authscheme.getSchemeName());  
277             if (LOG.isDebugEnabled()) {
278                 LOG.debug("Authenticating with " + authscope);
279             }
280             Credentials credentials = this.state.getCredentials(authscope);
281             if (credentials != null) {
282                 String authstring = authscheme.authenticate(credentials, method);
283                 if (authstring != null) {
284                     method.addRequestHeader(new Header(WWW_AUTH_RESP, authstring, true));
285                 }
286             } else {
287                 if (LOG.isWarnEnabled()) {
288                     LOG.warn("Required credentials not available for " + authscope);
289                     if (method.getHostAuthState().isPreemptive()) {
290                         LOG.warn("Preemptive authentication requested but no default " +
291                             "credentials available"); 
292                     }
293                 }
294             }
295         }
296     }
297 
298 
299     private void authenticateProxy(final HttpMethod method) throws AuthenticationException {
300         // Clean up existing authentication headers
301         if (!cleanAuthHeaders(method, PROXY_AUTH_RESP)) {
302             // User defined authentication header(s) present
303             return;
304         }
305         AuthState authstate = method.getProxyAuthState();
306         AuthScheme authscheme = authstate.getAuthScheme();
307         if (authscheme == null) {
308             return;
309         }
310         if (authstate.isAuthRequested() || !authscheme.isConnectionBased()) {
311             AuthScope authscope = new AuthScope(
312                 conn.getProxyHost(), conn.getProxyPort(), 
313                 authscheme.getRealm(), 
314                 authscheme.getSchemeName());  
315             if (LOG.isDebugEnabled()) {
316                 LOG.debug("Authenticating with " + authscope);
317             }
318             Credentials credentials = this.state.getProxyCredentials(authscope);
319             if (credentials != null) {
320                 String authstring = authscheme.authenticate(credentials, method);
321                 if (authstring != null) {
322                     method.addRequestHeader(new Header(PROXY_AUTH_RESP, authstring, true));
323                 }
324             } else {
325                 if (LOG.isWarnEnabled()) {
326                     LOG.warn("Required proxy credentials not available for " + authscope);
327                     if (method.getProxyAuthState().isPreemptive()) {
328                         LOG.warn("Preemptive authentication requested but no default " +
329                             "proxy credentials available"); 
330                     }
331                 }
332             }
333         }
334     }
335     
336     
337     /**
338      * Applies connection parameters specified for a given method
339      * 
340      * @param method HTTP method
341      * 
342      * @throws IOException if an I/O occurs setting connection parameters 
343      */
344     private void applyConnectionParams(final HttpMethod method) throws IOException {
345         int timeout = 0;
346         // see if a timeout is given for this method
347         Object param = method.getParams().getParameter(HttpMethodParams.SO_TIMEOUT);
348         if (param == null) {
349             // if not, use the default value
350             param = this.conn.getParams().getParameter(HttpConnectionParams.SO_TIMEOUT);
351         }
352         if (param != null) {
353             timeout = ((Integer)param).intValue();
354         }
355         this.conn.setSocketTimeout(timeout);                    
356     }
357     
358     /**
359      * Executes a method with the current hostConfiguration.
360      *
361      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions 
362      * can be recovered from.
363      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
364      * cannot be recovered from.
365      */
366     private void executeWithRetry(final HttpMethod method) 
367         throws IOException, HttpException {
368         
369         /** How many times did this transparently handle a recoverable exception? */
370         int execCount = 0;
371         // loop until the method is successfully processed, the retryHandler 
372         // returns false or a non-recoverable exception is thrown
373         try {
374             while (true) {
375                 execCount++;
376                 try {
377 
378                     if (LOG.isTraceEnabled()) {
379                         LOG.trace("Attempt number " + execCount + " to process request");
380                     }
381                     if (this.conn.getParams().isStaleCheckingEnabled()) {
382                         this.conn.closeIfStale();
383                     }
384                     if (!this.conn.isOpen()) {
385                         // this connection must be opened before it can be used
386                         // This has nothing to do with opening a secure tunnel
387                         this.conn.open();
388                         if (this.conn.isProxied() && this.conn.isSecure() 
389                         && !(method instanceof ConnectMethod)) {
390                             // we need to create a secure tunnel before we can execute the real method
391                             if (!executeConnect()) {
392                                 // abort, the connect method failed
393                                 return;
394                             }
395                         }
396                     }
397                     applyConnectionParams(method);                    
398                     method.execute(state, this.conn);
399                     break;
400                 } catch (HttpException e) {
401                     // filter out protocol exceptions which cannot be recovered from
402                     throw e;
403                 } catch (IOException e) {
404                     LOG.debug("Closing the connection.");
405                     this.conn.close();
406                     // test if this method should be retried
407                     // ========================================
408                     // this code is provided for backward compatibility with 2.0
409                     // will be removed in the next major release
410                     if (method instanceof HttpMethodBase) {
411                         MethodRetryHandler handler = 
412                             ((HttpMethodBase)method).getMethodRetryHandler();
413                         if (handler != null) {
414                             if (!handler.retryMethod(
415                                     method,
416                                     this.conn, 
417                                     new HttpRecoverableException(e.getMessage()),
418                                     execCount, 
419                                     method.isRequestSent())) {
420                                 LOG.debug("Method retry handler returned false. "
421                                         + "Automatic recovery will not be attempted");
422                                 throw e;
423                             }
424                         }
425                     }
426                     // ========================================
427                     HttpMethodRetryHandler handler = 
428                         (HttpMethodRetryHandler)method.getParams().getParameter(
429                                 HttpMethodParams.RETRY_HANDLER);
430                     if (handler == null) {
431                         handler = new DefaultHttpMethodRetryHandler();
432                     }
433                     if (!handler.retryMethod(method, e, execCount)) {
434                         LOG.debug("Method retry handler returned false. "
435                                 + "Automatic recovery will not be attempted");
436                         throw e;
437                     }
438                     if (LOG.isInfoEnabled()) {
439                         LOG.info("I/O exception ("+ e.getClass().getName() +") caught when processing request: "
440                                 + e.getMessage());
441                     }
442                     if (LOG.isDebugEnabled()) {
443                         LOG.debug(e.getMessage(), e);
444                     }
445                     LOG.info("Retrying request");
446                 }
447             }
448         } catch (IOException e) {
449             if (this.conn.isOpen()) {
450                 LOG.debug("Closing the connection.");
451                 this.conn.close();
452             }
453             releaseConnection = true;
454             throw e;
455         } catch (RuntimeException e) {
456             if (this.conn.isOpen()) {
457                 LOG.debug("Closing the connection.");
458                 this.conn.close();
459             }
460             releaseConnection = true;
461             throw e;
462         }
463     }
464     
465     /**
466      * Executes a ConnectMethod to establish a tunneled connection.
467      * 
468      * @return <code>true</code> if the connect was successful
469      * 
470      * @throws IOException
471      * @throws HttpException
472      */
473     private boolean executeConnect() 
474         throws IOException, HttpException {
475 
476         this.connectMethod = new ConnectMethod(this.hostConfiguration);
477         this.connectMethod.getParams().setDefaults(this.hostConfiguration.getParams());
478         
479         int code;
480         for (;;) {
481             if (!this.conn.isOpen()) {
482                 this.conn.open();
483             }
484             if (this.params.isAuthenticationPreemptive()
485                     || this.state.isAuthenticationPreemptive()) {
486                 LOG.debug("Preemptively sending default basic credentials");
487                 this.connectMethod.getProxyAuthState().setPreemptive();
488                 this.connectMethod.getProxyAuthState().setAuthAttempted(true);
489             }
490             try {
491                 authenticateProxy(this.connectMethod);
492             } catch (AuthenticationException e) {
493                 LOG.error(e.getMessage(), e);
494             }
495             applyConnectionParams(this.connectMethod);                    
496             this.connectMethod.execute(state, this.conn);
497             code = this.connectMethod.getStatusCode();
498             boolean retry = false;
499             AuthState authstate = this.connectMethod.getProxyAuthState(); 
500             authstate.setAuthRequested(code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED);
501             if (authstate.isAuthRequested()) {
502                 if (processAuthenticationResponse(this.connectMethod)) {
503                     retry = true;
504                 }
505             }
506             if (!retry) {
507                 break;
508             }
509             if (this.connectMethod.getResponseBodyAsStream() != null) {
510                 this.connectMethod.getResponseBodyAsStream().close();
511             }
512         }
513         if ((code >= 200) && (code < 300)) {
514             this.conn.tunnelCreated();
515             // Drop the connect method, as it is no longer needed
516             this.connectMethod = null;
517             return true;
518         } else {
519             this.conn.close();
520             return false;
521         }
522     }
523 
524     /**
525      * Fake response
526      * @param method
527      * @return
528      */
529     
530     private void fakeResponse(final HttpMethod method)
531         throws IOException, HttpException {
532         // What is to follow is an ugly hack.
533         // I REALLY hate having to resort to such
534         // an appalling trick
535         // The only feasible solution is to split monolithic
536         // HttpMethod into HttpRequest/HttpResponse pair.
537         // That would allow to execute CONNECT method 
538         // behind the scene and return CONNECT HttpResponse 
539         // object in response to the original request that 
540         // contains the correct status line, headers & 
541         // response body.
542         LOG.debug("CONNECT failed, fake the response for the original method");
543         // Pass the status, headers and response stream to the wrapped
544         // method.
545         // To ensure that the connection is not released more than once
546         // this method is still responsible for releasing the connection. 
547         // This will happen when the response body is consumed, or when
548         // the wrapped method closes the response connection in 
549         // releaseConnection().
550         if (method instanceof HttpMethodBase) {
551             ((HttpMethodBase) method).fakeResponse(
552                 this.connectMethod.getStatusLine(),
553                 this.connectMethod.getResponseHeaderGroup(),
554                 this.connectMethod.getResponseBodyAsStream()
555             );
556             method.getProxyAuthState().setAuthScheme(
557                 this.connectMethod.getProxyAuthState().getAuthScheme());
558             this.connectMethod = null;
559         } else {
560             releaseConnection = true;
561             LOG.warn(
562                 "Unable to fake response on method as it is not derived from HttpMethodBase.");
563         }
564     }
565     
566 	/**
567 	 * Process the redirect response.
568      * 
569 	 * @return <code>true</code> if the redirect was successful
570 	 */
571 	private boolean processRedirectResponse(final HttpMethod method)
572      throws RedirectException {
573 		//get the location header to find out where to redirect to
574 		Header locationHeader = method.getResponseHeader("location");
575 		if (locationHeader == null) {
576 			// got a redirect response, but no location header
577 			LOG.error("Received redirect response " + method.getStatusCode()
578 					+ " but no location header");
579 			return false;
580 		}
581 		String location = locationHeader.getValue();
582 		if (LOG.isDebugEnabled()) {
583 			LOG.debug("Redirect requested to location '" + location + "'");
584 		}
585         
586 		//rfc2616 demands the location value be a complete URI
587 		//Location       = "Location" ":" absoluteURI
588 		URI redirectUri = null;
589 		URI currentUri = null;
590 
591 		try {
592 			currentUri = new URI(
593 				this.conn.getProtocol().getScheme(),
594 				null,
595                 this.conn.getHost(), 
596                 this.conn.getPort(), 
597 				method.getPath()
598 			);
599 			
600             String charset = method.getParams().getUriCharset();
601             redirectUri = new URI(location, true, charset);
602 			
603             if (redirectUri.isRelativeURI()) {
604 				if (this.params.isParameterTrue(HttpClientParams.REJECT_RELATIVE_REDIRECT)) {
605 					LOG.warn("Relative redirect location '" + location + "' not allowed");
606 					return false;
607 				} else { 
608 					//location is incomplete, use current values for defaults
609 					LOG.debug("Redirect URI is not absolute - parsing as relative");
610 					redirectUri = new URI(currentUri, redirectUri);
611 				}
612 			} else {
613                 // Reset the default params
614                 method.getParams().setDefaults(this.params);
615             }
616             method.setURI(redirectUri);
617             hostConfiguration.setHost(redirectUri);
618 		} catch (URIException ex) {
619             throw new InvalidRedirectLocationException(
620                     "Invalid redirect location: " + location, location, ex);
621 		}
622 
623         if (this.params.isParameterFalse(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS)) {
624             if (this.redirectLocations == null) {
625                 this.redirectLocations = new HashSet();
626             }
627             this.redirectLocations.add(currentUri);
628             try {
629                 if(redirectUri.hasQuery()) {
630                     redirectUri.setQuery(null);
631                 }
632             } catch (URIException e) {
633                 // Should never happen
634                 return false;
635             }
636 
637             if (this.redirectLocations.contains(redirectUri)) {
638                 throw new CircularRedirectException("Circular redirect to '" +
639                     redirectUri + "'");
640             }
641         }
642 
643 		if (LOG.isDebugEnabled()) {
644 			LOG.debug("Redirecting from '" + currentUri.getEscapedURI()
645 				+ "' to '" + redirectUri.getEscapedURI());
646 		}
647         //And finally invalidate the actual authentication scheme
648         method.getHostAuthState().invalidate(); 
649 		return true;
650 	}
651 
652 	/**
653 	 * Processes a response that requires authentication
654 	 *
655 	 * @param method the current {@link HttpMethod HTTP method}
656 	 *
657 	 * @return <tt>true</tt> if the authentication challenge can be responsed to,
658      *   (that is, at least one of the requested authentication scheme is supported, 
659      *   and matching credentials have been found), <tt>false</tt> otherwise.
660 	 */
661 	private boolean processAuthenticationResponse(final HttpMethod method) {
662 		LOG.trace("enter HttpMethodBase.processAuthenticationResponse("
663 			+ "HttpState, HttpConnection)");
664 
665 		try {
666             switch (method.getStatusCode()) {
667                 case HttpStatus.SC_UNAUTHORIZED:
668                     return processWWWAuthChallenge(method);
669                 case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
670                     return processProxyAuthChallenge(method);
671                 default:
672                     return false;
673             }
674         } catch (Exception e) {
675             if (LOG.isErrorEnabled()) {
676                 LOG.error(e.getMessage(), e);
677             }
678             return false;
679         }
680 	}
681 
682     private boolean processWWWAuthChallenge(final HttpMethod method)
683         throws MalformedChallengeException, AuthenticationException  
684     {
685         AuthState authstate = method.getHostAuthState();
686         Map challenges = AuthChallengeParser.parseChallenges(
687             method.getResponseHeaders(WWW_AUTH_CHALLENGE));
688         if (challenges.isEmpty()) {
689             LOG.debug("Authentication challenge(s) not found");
690             return false; 
691         }
692         AuthScheme authscheme = null;
693         try {
694             authscheme = this.authProcessor.processChallenge(authstate, challenges);
695         } catch (AuthChallengeException e) {
696             if (LOG.isWarnEnabled()) {
697                 LOG.warn(e.getMessage());
698             }
699         }
700         if (authscheme == null) {
701             return false;
702         }
703         String host = method.getParams().getVirtualHost();
704         if (host == null) {
705             host = conn.getHost();
706         }
707         int port = conn.getPort();
708         AuthScope authscope = new AuthScope(
709             host, port, 
710             authscheme.getRealm(), 
711             authscheme.getSchemeName());
712         
713         if (LOG.isDebugEnabled()) {
714             LOG.debug("Authentication scope: " + authscope);
715         }
716         if (authstate.isAuthAttempted() && authscheme.isComplete()) {
717             // Already tried and failed
718             Credentials credentials = promptForCredentials(
719                 authscheme, method.getParams(), authscope);
720             if (credentials == null) {
721                 if (LOG.isInfoEnabled()) {
722                     LOG.info("Failure authenticating with " + authscope);
723                 }
724                 return false;
725             } else {
726                 return true;
727             }
728         } else {
729             authstate.setAuthAttempted(true);
730             Credentials credentials = this.state.getCredentials(authscope);
731             if (credentials == null) {
732                 credentials = promptForCredentials(
733                     authscheme, method.getParams(), authscope);
734             }
735             if (credentials == null) {
736                 if (LOG.isInfoEnabled()) {
737                     LOG.info("No credentials available for " + authscope); 
738                 }
739                 return false;
740             } else {
741                 return true;
742             }
743         }
744     }
745 
746     private boolean processProxyAuthChallenge(final HttpMethod method)
747         throws MalformedChallengeException, AuthenticationException
748     {  
749         AuthState authstate = method.getProxyAuthState();
750         Map proxyChallenges = AuthChallengeParser.parseChallenges(
751             method.getResponseHeaders(PROXY_AUTH_CHALLENGE));
752         if (proxyChallenges.isEmpty()) {
753             LOG.debug("Proxy authentication challenge(s) not found");
754             return false; 
755         }
756         AuthScheme authscheme = null;
757         try {
758             authscheme = this.authProcessor.processChallenge(authstate, proxyChallenges);
759         } catch (AuthChallengeException e) {
760             if (LOG.isWarnEnabled()) {
761                 LOG.warn(e.getMessage());
762             }
763         }
764         if (authscheme == null) {
765             return false;
766         }
767         AuthScope authscope = new AuthScope(
768             conn.getProxyHost(), conn.getProxyPort(), 
769             authscheme.getRealm(), 
770             authscheme.getSchemeName());  
771 
772         if (LOG.isDebugEnabled()) {
773             LOG.debug("Proxy authentication scope: " + authscope);
774         }
775         if (authstate.isAuthAttempted() && authscheme.isComplete()) {
776             // Already tried and failed
777             Credentials credentials = promptForProxyCredentials(
778                 authscheme, method.getParams(), authscope);
779             if (credentials == null) {
780                 if (LOG.isInfoEnabled()) {
781                     LOG.info("Failure authenticating with " + authscope);
782                 }
783                 return false;
784             } else {
785                 return true;
786             }
787         } else {
788             authstate.setAuthAttempted(true);
789             Credentials credentials = this.state.getProxyCredentials(authscope);
790             if (credentials == null) {
791                 credentials = promptForProxyCredentials(
792                     authscheme, method.getParams(), authscope);
793             }
794             if (credentials == null) {
795                 if (LOG.isInfoEnabled()) {
796                     LOG.info("No credentials available for " + authscope); 
797                 }
798                 return false;
799             } else {
800                 return true;
801             }
802         }
803     }
804 
805     /**
806      * Tests if the {@link HttpMethod method} requires a redirect to another location.
807      * 
808      * @param method HTTP method
809      * 
810      * @return boolean <tt>true</tt> if a retry is needed, <tt>false</tt> otherwise.
811      */
812 	private boolean isRedirectNeeded(final HttpMethod method) {
813 		switch (method.getStatusCode()) {
814 			case HttpStatus.SC_MOVED_TEMPORARILY:
815 			case HttpStatus.SC_MOVED_PERMANENTLY:
816 			case HttpStatus.SC_SEE_OTHER:
817 			case HttpStatus.SC_TEMPORARY_REDIRECT:
818 				LOG.debug("Redirect required");
819                 if (method.getFollowRedirects()) {
820                     return true;
821                 } else {
822                     return false;
823                 }
824 			default:
825 				return false;
826 		} //end of switch
827 	}
828 
829     /**
830      * Tests if the {@link HttpMethod method} requires authentication.
831      * 
832      * @param method HTTP method
833      * 
834      * @return boolean <tt>true</tt> if a retry is needed, <tt>false</tt> otherwise.
835      */
836     private boolean isAuthenticationNeeded(final HttpMethod method) {
837         method.getHostAuthState().setAuthRequested(
838                 method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED);
839         method.getProxyAuthState().setAuthRequested(
840                 method.getStatusCode() == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED);
841         if (method.getHostAuthState().isAuthRequested() || 
842             method.getProxyAuthState().isAuthRequested()) {
843             LOG.debug("Authorization required");
844             if (method.getDoAuthentication()) { //process authentication response
845                 return true;
846             } else { //let the client handle the authenticaiton
847                 LOG.info("Authentication requested but doAuthentication is "
848                         + "disabled");
849                 return false;
850             }
851         } else {
852             return false;
853         }
854     }
855 
856     private Credentials promptForCredentials(
857         final AuthScheme authScheme,
858         final HttpParams params, 
859         final AuthScope authscope)
860     {
861         LOG.debug("Credentials required");
862         Credentials creds = null;
863         CredentialsProvider credProvider = 
864             (CredentialsProvider)params.getParameter(CredentialsProvider.PROVIDER);
865         if (credProvider != null) {
866             try {
867                 creds = credProvider.getCredentials(
868                     authScheme, authscope.getHost(), authscope.getPort(), false);
869             } catch (CredentialsNotAvailableException e) {
870                 LOG.warn(e.getMessage());
871             }
872             if (creds != null) {
873                 this.state.setCredentials(authscope, creds);
874                 if (LOG.isDebugEnabled()) {
875                     LOG.debug(authscope + " new credentials given");
876                 }
877             }
878         } else {
879             LOG.debug("Credentials provider not available");
880         }
881         return creds;
882     }
883 
884     private Credentials promptForProxyCredentials(
885         final AuthScheme authScheme,
886         final HttpParams params,
887         final AuthScope authscope) 
888     {
889         LOG.debug("Proxy credentials required");
890         Credentials creds = null;
891         CredentialsProvider credProvider = 
892             (CredentialsProvider)params.getParameter(CredentialsProvider.PROVIDER);
893         if (credProvider != null) {
894             try {
895                 creds = credProvider.getCredentials(
896                     authScheme, authscope.getHost(), authscope.getPort(), true);
897             } catch (CredentialsNotAvailableException e) {
898                 LOG.warn(e.getMessage());
899             }
900             if (creds != null) {
901                 this.state.setProxyCredentials(authscope, creds);
902                 if (LOG.isDebugEnabled()) {
903                     LOG.debug(authscope + " new credentials given");
904                 }
905             }
906         } else {
907             LOG.debug("Proxy credentials provider not available");
908         }
909         return creds;
910     }
911 
912     /**
913      * @return
914      */
915     public HostConfiguration getHostConfiguration() {
916         return hostConfiguration;
917     }
918 
919     /**
920      * @return
921      */
922     public HttpState getState() {
923         return state;
924     }
925 
926     /**
927      * @return
928      */
929     public HttpConnectionManager getConnectionManager() {
930         return connectionManager;
931     }
932 
933     /**
934      * @return
935      */
936     public HttpParams getParams() {
937         return this.params;
938     }
939 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpMethodRetryHandler.html100644 0 0 15153 10661532627 27417 0ustar 0 0 HttpMethodRetryHandler xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethodRetryHandler.java,v 1.2 2004/09/14 20:11:31 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  
35  /**
36   * A handler for determining if an HttpMethod should be retried after a 
37   * recoverable exception during execution.
38   * 
39   * <p>
40   * Classes implementing this interface must synchronize access to shared
41   * data as methods of this interfrace may be executed from multiple threads 
42   * </p>
43   * 
44   * @see HttpMethod#execute(HttpState, HttpConnection)
45   * 
46   * @author Michael Becke
47   * @author <a href="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a>
48   */
49  public interface HttpMethodRetryHandler {
50  
51      /**
52       * Determines if a method should be retried after an HttpRecoverableException
53       * occurs during execution.
54       * 
55       * @param method the method being executed
56       * @param exception the exception that occurred
57       * @param executionCount the number of times this method has been 
58       * unsuccessfully executed
59       * 
60       * @return <code>true</code> if the method should be retried, <code>false</code>
61       * otherwise
62       */
63      boolean retryMethod(HttpMethod method, IOException exception, int executionCount);
64  
65  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpParser.html100644 0 0 51214 10661532627 25105 0ustar 0 0 HttpParser xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpParser.java,v 1.13 2005/01/11 13:57:06 oglueck Exp $
3    * $Revision: 533405 $
4    * $Date: 2007-04-28 20:19:29 +0200 (Sat, 28 Apr 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.io.ByteArrayOutputStream;
36  import java.util.ArrayList;
37  
38  import org.apache.commons.httpclient.util.EncodingUtil;
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  
42  /**
43   * A utility class for parsing http header values according to
44   * RFC-2616 Section 4 and 19.3.
45   * 
46   * @author Michael Becke
47   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
48   * 
49   * @since 2.0beta1
50   */
51  public class HttpParser {
52  
53      /** Log object for this class. */
54      private static final Log LOG = LogFactory.getLog(HttpParser.class);
55      
56      /**
57       * Constructor for HttpParser.
58       */
59      private HttpParser() { }
60  
61      /**
62       * Return byte array from an (unchunked) input stream.
63       * Stop reading when <tt>"\n"</tt> terminator encountered 
64       * If the stream ends before the line terminator is found,
65       * the last part of the string will still be returned. 
66       * If no input data available, <code>null</code> is returned.
67       *
68       * @param inputStream the stream to read from
69       *
70       * @throws IOException if an I/O problem occurs
71       * @return a byte array from the stream
72       */
73      public static byte[] readRawLine(InputStream inputStream) throws IOException {
74          LOG.trace("enter HttpParser.readRawLine()");
75  
76          ByteArrayOutputStream buf = new ByteArrayOutputStream();
77          int ch;
78          while ((ch = inputStream.read()) >= 0) {
79              buf.write(ch);
80              if (ch == '\n') { // be tolerant (RFC-2616 Section 19.3)
81                  break;
82              }
83          }
84          if (buf.size() == 0) {
85              return null;
86          }
87          return buf.toByteArray();
88      }
89  
90      /**
91       * Read up to <tt>"\n"</tt> from an (unchunked) input stream.
92       * If the stream ends before the line terminator is found,
93       * the last part of the string will still be returned.
94       * If no input data available, <code>null</code> is returned.
95       *
96       * @param inputStream the stream to read from
97       * @param charset charset of HTTP protocol elements
98       *
99       * @throws IOException if an I/O problem occurs
100      * @return a line from the stream
101      * 
102      * @since 3.0
103      */
104     public static String readLine(InputStream inputStream, String charset) throws IOException {
105         LOG.trace("enter HttpParser.readLine(InputStream, String)");
106         byte[] rawdata = readRawLine(inputStream);
107         if (rawdata == null) {
108             return null;
109         }
110         // strip CR and LF from the end
111         int len = rawdata.length;
112         int offset = 0;
113         if (len > 0) {
114             if (rawdata[len - 1] == '\n') {
115                 offset++;
116                 if (len > 1) {
117                     if (rawdata[len - 2] == '\r') {
118                         offset++;
119                     }
120                 }
121             }
122         }
123         final String result =
124             EncodingUtil.getString(rawdata, 0, len - offset, charset);
125         if (Wire.HEADER_WIRE.enabled()) {
126             String logoutput = result;
127             if (offset == 2)
128                 logoutput = result + "\r\n";
129             else if (offset == 1)
130                 logoutput = result + "\n";
131             Wire.HEADER_WIRE.input(logoutput);
132         }
133         return result;
134     }
135 
136     /**
137      * Read up to <tt>"\n"</tt> from an (unchunked) input stream.
138      * If the stream ends before the line terminator is found,
139      * the last part of the string will still be returned.
140      * If no input data available, <code>null</code> is returned
141      *
142      * @param inputStream the stream to read from
143      *
144      * @throws IOException if an I/O problem occurs
145      * @return a line from the stream
146      * 
147      * @deprecated use #readLine(InputStream, String)
148      */
149 
150     public static String readLine(InputStream inputStream) throws IOException {
151         LOG.trace("enter HttpParser.readLine(InputStream)");
152         return readLine(inputStream, "US-ASCII");
153     }
154     
155     /**
156      * Parses headers from the given stream.  Headers with the same name are not
157      * combined.
158      * 
159      * @param is the stream to read headers from
160      * @param charset the charset to use for reading the data
161      * 
162      * @return an array of headers in the order in which they were parsed
163      * 
164      * @throws IOException if an IO error occurs while reading from the stream
165      * @throws HttpException if there is an error parsing a header value
166      * 
167      * @since 3.0
168      */
169     public static Header[] parseHeaders(InputStream is, String charset) throws IOException, HttpException {
170         LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)");
171 
172         ArrayList headers = new ArrayList();
173         String name = null;
174         StringBuffer value = null;
175         for (; ;) {
176             String line = HttpParser.readLine(is, charset);
177             if ((line == null) || (line.trim().length() < 1)) {
178                 break;
179             }
180 
181             // Parse the header name and value
182             // Check for folded headers first
183             // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2
184             // discussion on folded headers
185             if ((line.charAt(0) == ' ') || (line.charAt(0) == '\t')) {
186                 // we have continuation folded header
187                 // so append value
188                 if (value != null) {
189                     value.append(' ');
190                     value.append(line.trim());
191                 }
192             } else {
193                 // make sure we save the previous name,value pair if present
194                 if (name != null) {
195                     headers.add(new Header(name, value.toString()));
196                 }
197 
198                 // Otherwise we should have normal HTTP header line
199                 // Parse the header name and value
200                 int colon = line.indexOf(":");
201                 if (colon < 0) {
202                     throw new ProtocolException("Unable to parse header: " + line);
203                 }
204                 name = line.substring(0, colon).trim();
205                 value = new StringBuffer(line.substring(colon + 1).trim());
206             }
207 
208         }
209 
210         // make sure we save the last name,value pair if present
211         if (name != null) {
212             headers.add(new Header(name, value.toString()));
213         }
214         
215         return (Header[]) headers.toArray(new Header[headers.size()]);    
216     }
217 
218     /**
219      * Parses headers from the given stream.  Headers with the same name are not
220      * combined.
221      * 
222      * @param is the stream to read headers from
223      * 
224      * @return an array of headers in the order in which they were parsed
225      * 
226      * @throws IOException if an IO error occurs while reading from the stream
227      * @throws HttpException if there is an error parsing a header value
228      * 
229      * @deprecated use #parseHeaders(InputStream, String)
230      */
231     public static Header[] parseHeaders(InputStream is) throws IOException, HttpException {
232         LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)");
233         return parseHeaders(is, "US-ASCII");
234     }
235 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpRecoverableException.html100644 0 0 15044 10661532627 27762 0ustar 0 0 HttpRecoverableException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpRecoverableException.java,v 1.15 2004/07/05 22:46:58 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * <p>
35   * Signals that an HTTP or HttpClient exception has occurred.  This
36   * exception may have been caused by a transient error and the request
37   * may be retried.  It may be possible to retrieve the underlying transient
38   * error via the inherited {@link HttpException#getCause()} method.
39   * </p>
40   * 
41   * @deprecated no longer used
42   * 
43   * @author Unascribed
44   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
45   */
46  public class HttpRecoverableException extends HttpException {
47  
48      /**
49       * Creates a new HttpRecoverableException with a <tt>null</tt> detail message.
50       */
51      public HttpRecoverableException() {
52          super();
53      }
54  
55      /**
56       * Creates a new HttpRecoverableException with the specified detail message.
57       *
58       * @param message exception message
59       */
60      public HttpRecoverableException(String message) {
61          super(message);
62      }
63  
64  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpState.html100644 0 0 153116 10661532627 24755 0ustar 0 0 HttpState xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpState.java,v 1.38 2004/12/20 11:50:54 olegk Exp $
3    * $Revision: 561099 $
4    * $Date: 2007-07-30 21:41:17 +0200 (Mon, 30 Jul 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.util.ArrayList;
34  import java.util.Date;
35  import java.util.HashMap;
36  import java.util.Map;
37  import java.util.List;
38  import java.util.Iterator;
39  import org.apache.commons.httpclient.cookie.CookieSpec;
40  import org.apache.commons.httpclient.cookie.CookiePolicy;
41  import org.apache.commons.httpclient.auth.AuthScope; 
42  import org.apache.commons.logging.Log;
43  import org.apache.commons.logging.LogFactory;
44  
45  /**
46   * <p>
47   * A container for HTTP attributes that may persist from request
48   * to request, such as {@link Cookie cookies} and authentication
49   * {@link Credentials credentials}.
50   * </p>
51   * 
52   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
53   * @author Rodney Waldhoff
54   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
55   * @author Sean C. Sullivan
56   * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
57   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
58   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
59   * @author <a href="mailto:adrian@intencha.com">Adrian Sutton</a>
60   * 
61   * @version $Revision: 561099 $ $Date: 2007-07-30 21:41:17 +0200 (Mon, 30 Jul 2007) $
62   * 
63   */
64  public class HttpState {
65  
66      // ----------------------------------------------------- Instance Variables
67  
68      /**
69       * Map of {@link Credentials credentials} by realm that this 
70       * HTTP state contains.
71       */
72      protected HashMap credMap = new HashMap();
73  
74      /**
75       * Map of {@link Credentials proxy credentials} by realm that this
76       * HTTP state contains
77       */
78      protected HashMap proxyCred = new HashMap();
79  
80      /**
81       * Array of {@link Cookie cookies} that this HTTP state contains.
82       */
83      protected ArrayList cookies = new ArrayList();
84  
85      private boolean preemptive = false;
86  
87      private int cookiePolicy = -1;
88      // -------------------------------------------------------- Class Variables
89  
90      /**
91       * The boolean system property name to turn on preemptive authentication.
92       * @deprecated This field and feature will be removed following HttpClient 3.0.
93       */
94      public static final String PREEMPTIVE_PROPERTY = "httpclient.authentication.preemptive";
95  
96      /**
97       * The default value for {@link #PREEMPTIVE_PROPERTY}.
98       * @deprecated This field and feature will be removed following HttpClient 3.0.
99       */
100     public static final String PREEMPTIVE_DEFAULT = "false";
101     
102     /** Log object for this class. */
103     private static final Log LOG = LogFactory.getLog(HttpState.class);
104 
105     /**
106      * Default constructor.
107      */
108     public HttpState() {
109         super();
110     }
111 
112     // ------------------------------------------------------------- Properties
113 
114     /**
115      * Adds an {@link Cookie HTTP cookie}, replacing any existing equivalent cookies.
116      * If the given cookie has already expired it will not be added, but existing 
117      * values will still be removed.
118      * 
119      * @param cookie the {@link Cookie cookie} to be added
120      * 
121      * @see #addCookies(Cookie[])
122      * 
123      */
124     public synchronized void addCookie(Cookie cookie) {
125         LOG.trace("enter HttpState.addCookie(Cookie)");
126 
127         if (cookie != null) {
128             // first remove any old cookie that is equivalent
129             for (Iterator it = cookies.iterator(); it.hasNext();) {
130                 Cookie tmp = (Cookie) it.next();
131                 if (cookie.equals(tmp)) {
132                     it.remove();
133                     break;
134                 }
135             }
136             if (!cookie.isExpired()) {
137                 cookies.add(cookie);
138             }
139         }
140     }
141 
142     /**
143      * Adds an array of {@link Cookie HTTP cookies}. Cookies are added individually and 
144      * in the given array order. If any of the given cookies has already expired it will 
145      * not be added, but existing values will still be removed.
146      * 
147      * @param cookies the {@link Cookie cookies} to be added
148      * 
149      * @see #addCookie(Cookie)
150      * 
151      * 
152      */
153     public synchronized void addCookies(Cookie[] cookies) {
154         LOG.trace("enter HttpState.addCookies(Cookie[])");
155 
156         if (cookies != null) {
157             for (int i = 0; i < cookies.length; i++) {
158                 this.addCookie(cookies[i]);
159             }
160         }
161     }
162 
163     /**
164      * Returns an array of {@link Cookie cookies} that this HTTP
165      * state currently contains.
166      * 
167      * @return an array of {@link Cookie cookies}.
168      * 
169      * @see #getCookies(String, int, String, boolean)
170      * 
171      */
172     public synchronized Cookie[] getCookies() {
173         LOG.trace("enter HttpState.getCookies()");
174         return (Cookie[]) (cookies.toArray(new Cookie[cookies.size()]));
175     }
176 
177     /**
178      * Returns an array of {@link Cookie cookies} in this HTTP 
179      * state that match the given request parameters.
180      * 
181      * @param domain the request domain
182      * @param port the request port
183      * @param path the request path
184      * @param secure <code>true</code> when using HTTPS
185      * 
186      * @return an array of {@link Cookie cookies}.
187      * 
188      * @see #getCookies()
189      * 
190      * @deprecated use CookieSpec#match(String, int, String, boolean, Cookie)
191      */
192     public synchronized Cookie[] getCookies(
193         String domain, 
194         int port, 
195         String path, 
196         boolean secure
197     ) {
198         LOG.trace("enter HttpState.getCookies(String, int, String, boolean)");
199 
200         CookieSpec matcher = CookiePolicy.getDefaultSpec();
201         ArrayList list = new ArrayList(cookies.size());
202         for (int i = 0, m = cookies.size(); i < m; i++) {
203             Cookie cookie = (Cookie) (cookies.get(i));
204             if (matcher.match(domain, port, path, secure, cookie)) {
205                 list.add(cookie);
206             }
207         }
208         return (Cookie[]) (list.toArray(new Cookie[list.size()]));
209     }
210 
211     /**
212      * Removes all of {@link Cookie cookies} in this HTTP state
213      * that have expired according to the current system time.
214      * 
215      * @see #purgeExpiredCookies(java.util.Date)
216      * 
217      */
218     public synchronized boolean purgeExpiredCookies() {
219         LOG.trace("enter HttpState.purgeExpiredCookies()");
220         return purgeExpiredCookies(new Date());
221     }
222 
223     /**
224      * Removes all of {@link Cookie cookies} in this HTTP state
225      * that have expired by the specified {@link java.util.Date date}. 
226      * 
227      * @param date The {@link java.util.Date date} to compare against.
228      * 
229      * @return true if any cookies were purged.
230      * 
231      * @see Cookie#isExpired(java.util.Date)
232      * 
233      * @see #purgeExpiredCookies()
234      */
235     public synchronized boolean purgeExpiredCookies(Date date) {
236         LOG.trace("enter HttpState.purgeExpiredCookies(Date)");
237         boolean removed = false;
238         Iterator it = cookies.iterator();
239         while (it.hasNext()) {
240             if (((Cookie) (it.next())).isExpired(date)) {
241                 it.remove();
242                 removed = true;
243             }
244         }
245         return removed;
246     }
247 
248 
249     /**
250      * Returns the current {@link CookiePolicy cookie policy} for this
251      * HTTP state.
252      * 
253      * @return The {@link CookiePolicy cookie policy}.
254      * 
255      * @deprecated Use 
256      *  {@link org.apache.commons.httpclient.params.HttpMethodParams#getCookiePolicy()},
257      *  {@link HttpMethod#getParams()}.     
258      */
259     
260     public int getCookiePolicy() {
261         return this.cookiePolicy;
262     }
263     
264 
265     /**
266      * Defines whether preemptive authentication should be 
267      * attempted.
268      * 
269      * @param value <tt>true</tt> if preemptive authentication should be 
270      * attempted, <tt>false</tt> otherwise. 
271      * 
272      * @deprecated Use 
273      * {@link org.apache.commons.httpclient.params.HttpClientParams#setAuthenticationPreemptive(boolean)}, 
274      * {@link HttpClient#getParams()}.
275      */
276     
277     public void setAuthenticationPreemptive(boolean value) {
278         this.preemptive = value;
279     }
280 
281 
282     /**
283      * Returns <tt>true</tt> if preemptive authentication should be 
284      * attempted, <tt>false</tt> otherwise.
285      * 
286      * @return boolean flag.
287      * 
288      * @deprecated Use 
289      * {@link org.apache.commons.httpclient.params.HttpClientParams#isAuthenticationPreemptive()}, 
290      * {@link HttpClient#getParams()}.
291      */
292     
293     public boolean isAuthenticationPreemptive() {
294         return this.preemptive;
295     }
296     
297 
298     /**
299      * Sets the current {@link CookiePolicy cookie policy} for this HTTP
300      * state to one of the following supported policies: 
301      * {@link CookiePolicy#COMPATIBILITY}, 
302      * {@link CookiePolicy#NETSCAPE_DRAFT} or
303      * {@link CookiePolicy#RFC2109}.
304      * 
305      * @param policy new {@link CookiePolicy cookie policy}
306      * 
307      * @deprecated 
308      *  Use {@link org.apache.commons.httpclient.params.HttpMethodParams#setCookiePolicy(String)},
309      *  {@link HttpMethod#getParams()}.     
310      */
311     
312     public void setCookiePolicy(int policy) {
313         this.cookiePolicy = policy;
314     }
315 
316     /** 
317      * Sets the {@link Credentials credentials} for the given authentication 
318      * realm on the given host. The <code>null</code> realm signifies default 
319      * credentials for the given host, which should be used when no 
320      * {@link Credentials credentials} have been explictly supplied for the 
321      * challenging realm. The <code>null</code> host signifies default 
322      * credentials, which should be used when no {@link Credentials credentials} 
323      * have been explictly supplied for the challenging host. Any previous 
324      * credentials for the given realm on the given host will be overwritten.
325      * 
326      * @param realm the authentication realm
327      * @param host the host the realm belongs to
328      * @param credentials the authentication {@link Credentials credentials} 
329      * for the given realm.
330      * 
331      * @see #getCredentials(String, String)
332      * @see #setProxyCredentials(String, String, Credentials) 
333      * 
334      * @deprecated use #setCredentials(AuthScope, Credentials)
335      */
336     
337     public synchronized void setCredentials(String realm, String host, Credentials credentials) {
338         LOG.trace("enter HttpState.setCredentials(String, String, Credentials)");
339         credMap.put(new AuthScope(host, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME), credentials);
340     }
341 
342     /** 
343      * Sets the {@link Credentials credentials} for the given authentication 
344      * scope. Any previous credentials for the given scope will be overwritten.
345      * 
346      * @param authscope the {@link AuthScope authentication scope}
347      * @param credentials the authentication {@link Credentials credentials} 
348      * for the given scope.
349      * 
350      * @see #getCredentials(AuthScope)
351      * @see #setProxyCredentials(AuthScope, Credentials) 
352      * 
353      * @since 3.0
354      */
355     public synchronized void setCredentials(final AuthScope authscope, final Credentials credentials) {
356         if (authscope == null) {
357             throw new IllegalArgumentException("Authentication scope may not be null");
358         }
359         LOG.trace("enter HttpState.setCredentials(AuthScope, Credentials)");
360         credMap.put(authscope, credentials);
361     }
362 
363     /**
364      * Find matching {@link Credentials credentials} for the given authentication scope.
365      *
366      * @param map the credentials hash map
367      * @param token the {@link AuthScope authentication scope}
368      * @return the credentials 
369      * 
370      */
371     private static Credentials matchCredentials(final HashMap map, final AuthScope authscope) {
372         // see if we get a direct hit
373         Credentials creds = (Credentials)map.get(authscope);
374         if (creds == null) {
375             // Nope.
376             // Do a full scan
377             int bestMatchFactor  = -1;
378             AuthScope bestMatch  = null;
379             Iterator items = map.keySet().iterator();
380             while (items.hasNext()) {
381                 AuthScope current = (AuthScope)items.next();
382                 int factor = authscope.match(current);
383                 if (factor > bestMatchFactor) {
384                     bestMatchFactor = factor;
385                     bestMatch = current;
386                 }
387             }
388             if (bestMatch != null) {
389                 creds = (Credentials)map.get(bestMatch);
390             }
391         }
392         return creds;
393     }
394     
395     /**
396      * Get the {@link Credentials credentials} for the given authentication scope on the 
397      * given host.
398      *
399      * If the <i>realm</i> exists on <i>host</i>, return the coresponding credentials.
400      * If the <i>host</i> exists with a <tt>null</tt> <i>realm</i>, return the corresponding
401      * credentials.
402      * If the <i>realm</i> exists with a <tt>null</tt> <i>host</i>, return the
403      * corresponding credentials.  If the <i>realm</i> does not exist, return
404      * the default Credentials.  If there are no default credentials, return
405      * <code>null</code>.
406      *
407      * @param realm the authentication realm
408      * @param host the host the realm is on
409      * @return the credentials 
410      * 
411      * @see #setCredentials(String, String, Credentials)
412      * 
413      * @deprecated use #getCredentials(AuthScope)
414      */
415     
416     public synchronized Credentials getCredentials(String realm, String host) {
417         LOG.trace("enter HttpState.getCredentials(String, String");
418         return matchCredentials(this.credMap, 
419             new AuthScope(host, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME));
420     }
421 
422     /**
423      * Get the {@link Credentials credentials} for the given authentication scope.
424      *
425      * @param authscope the {@link AuthScope authentication scope}
426      * @return the credentials 
427      * 
428      * @see #setCredentials(AuthScope, Credentials)
429      * 
430      * @since 3.0
431      */
432     public synchronized Credentials getCredentials(final AuthScope authscope) {
433         if (authscope == null) {
434             throw new IllegalArgumentException("Authentication scope may not be null");
435         }
436         LOG.trace("enter HttpState.getCredentials(AuthScope)");
437         return matchCredentials(this.credMap, authscope);
438     }
439 
440     /**
441      * Sets the {@link Credentials credentials} for the given proxy authentication 
442      * realm on the given proxy host. The <code>null</code> proxy realm signifies 
443      * default credentials for the given proxy host, which should be used when no 
444      * {@link Credentials credentials} have been explictly supplied for the 
445      * challenging proxy realm. The <code>null</code> proxy host signifies default 
446      * credentials, which should be used when no {@link Credentials credentials} 
447      * have been explictly supplied for the challenging proxy host. Any previous 
448      * credentials for the given proxy realm on the given proxy host will be 
449      * overwritten.
450      *
451      * @param realm the authentication realm
452      * @param proxyHost the proxy host
453      * @param credentials the authentication credentials for the given realm
454      * 
455      * @see #getProxyCredentials(AuthScope)
456      * @see #setCredentials(AuthScope, Credentials)
457      * 
458      * @deprecated use #setProxyCredentials(AuthScope, Credentials)
459      */
460     public synchronized void setProxyCredentials(
461         String realm, 
462         String proxyHost, 
463         Credentials credentials
464     ) {
465         LOG.trace("enter HttpState.setProxyCredentials(String, String, Credentials");
466         proxyCred.put(new AuthScope(proxyHost, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME), credentials);
467     }
468 
469     /** 
470      * Sets the {@link Credentials proxy credentials} for the given authentication 
471      * realm. Any previous credentials for the given realm will be overwritten.
472      * 
473      * @param authscope the {@link AuthScope authentication scope}
474      * @param credentials the authentication {@link Credentials credentials} 
475      * for the given realm.
476      * 
477      * @see #getProxyCredentials(AuthScope)
478      * @see #setCredentials(AuthScope, Credentials) 
479      * 
480      * @since 3.0
481      */
482     public synchronized void setProxyCredentials(final AuthScope authscope, 
483         final Credentials credentials)
484     {
485         if (authscope == null) {
486             throw new IllegalArgumentException("Authentication scope may not be null");
487         }
488         LOG.trace("enter HttpState.setProxyCredentials(AuthScope, Credentials)");
489         proxyCred.put(authscope, credentials);
490     }
491 
492     /**
493      * Get the {@link Credentials credentials} for the proxy host with the given 
494      * authentication scope.
495      *
496      * If the <i>realm</i> exists on <i>host</i>, return the coresponding credentials.
497      * If the <i>host</i> exists with a <tt>null</tt> <i>realm</i>, return the corresponding
498      * credentials.
499      * If the <i>realm</i> exists with a <tt>null</tt> <i>host</i>, return the
500      * corresponding credentials.  If the <i>realm</i> does not exist, return
501      * the default Credentials.  If there are no default credentials, return
502      * <code>null</code>.
503      * 
504      * @param realm the authentication realm
505      * @param proxyHost the proxy host the realm is on
506      * @return the credentials 
507      * @see #setProxyCredentials(String, String, Credentials)
508      * 
509      * @deprecated use #getProxyCredentials(AuthScope)
510      */
511     public synchronized Credentials getProxyCredentials(String realm, String proxyHost) {
512        LOG.trace("enter HttpState.getCredentials(String, String");
513         return matchCredentials(this.proxyCred, 
514             new AuthScope(proxyHost, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME));
515     }
516     
517     /**
518      * Get the {@link Credentials proxy credentials} for the given authentication scope.
519      *
520      * @param authscope the {@link AuthScope authentication scope}
521      * @return the credentials 
522      * 
523      * @see #setProxyCredentials(AuthScope, Credentials)
524      * 
525      * @since 3.0
526      */
527     public synchronized Credentials getProxyCredentials(final AuthScope authscope) {
528         if (authscope == null) {
529             throw new IllegalArgumentException("Authentication scope may not be null");
530         }
531         LOG.trace("enter HttpState.getProxyCredentials(AuthScope)");
532         return matchCredentials(this.proxyCred, authscope);
533     }
534 
535     /**
536      * Returns a string representation of this HTTP state.
537      * 
538      * @return The string representation of the HTTP state.
539      * 
540      * @see java.lang.Object#toString()
541      */
542     public synchronized String toString() {
543         StringBuffer sbResult = new StringBuffer();
544 
545         sbResult.append("[");
546         sbResult.append(getCredentialsStringRepresentation(proxyCred));
547         sbResult.append(" | ");
548         sbResult.append(getCredentialsStringRepresentation(credMap));
549         sbResult.append(" | ");
550         sbResult.append(getCookiesStringRepresentation(cookies));
551         sbResult.append("]");
552 
553         String strResult = sbResult.toString();
554 
555         return strResult;
556     }
557     
558     /**
559      * Returns a string representation of the credentials.
560      * @param credMap The credentials.
561      * @return The string representation.
562      */
563     private static String getCredentialsStringRepresentation(final Map credMap) {
564         StringBuffer sbResult = new StringBuffer();
565         Iterator iter = credMap.keySet().iterator();
566         while (iter.hasNext()) {
567             Object key = iter.next();
568             Credentials cred = (Credentials) credMap.get(key);
569             if (sbResult.length() > 0) {
570                 sbResult.append(", ");
571             }
572             sbResult.append(key);
573             sbResult.append("#");
574             sbResult.append(cred.toString());
575         }
576         return sbResult.toString();
577     }
578     
579     /**
580      * Returns a string representation of the cookies.
581      * @param cookies The cookies
582      * @return The string representation.
583      */
584     private static String getCookiesStringRepresentation(final List cookies) {
585         StringBuffer sbResult = new StringBuffer();
586         Iterator iter = cookies.iterator();
587         while (iter.hasNext()) {
588             Cookie ck = (Cookie) iter.next();
589             if (sbResult.length() > 0) {
590                 sbResult.append("#");
591             }
592             sbResult.append(ck.toExternalForm());
593         }
594         return sbResult.toString();
595     }
596     
597     /**
598      * Clears all credentials.
599      */
600     public void clearCredentials() {
601         this.credMap.clear();
602     }
603     
604     /**
605      * Clears all proxy credentials.
606      */
607     public void clearProxyCredentials() {
608         this.proxyCred.clear();
609     }
610     
611     /**
612      * Clears all cookies.
613      */
614     public synchronized void clearCookies() {
615         this.cookies.clear();
616     }
617     
618     /**
619      * Clears the state information (all cookies, credentials and proxy credentials).
620      */
621     public void clear() {
622         clearCookies();
623         clearCredentials();
624         clearProxyCredentials();
625     }
626 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpStatus.html100644 0 0 101117 10661532627 25152 0ustar 0 0 HttpStatus xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpStatus.java,v 1.18 2004/05/02 11:21:13 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * Constants enumerating the HTTP status codes.
35   * All status codes defined in RFC1945 (HTTP/1.0, RFC2616 (HTTP/1.1), and
36   * RFC2518 (WebDAV) are supported.
37   * 
38   * @see StatusLine
39   * @author Unascribed
40   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
41   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
42   * 
43   * TODO: Internationalization of reason phrases 
44   * 
45   * @version $Id: HttpStatus.java 480424 2006-11-29 05:56:49Z bayard $
46   */
47  public class HttpStatus {
48  
49  
50      // -------------------------------------------------------- Class Variables
51  
52      /** Reason phrases lookup table. */
53      private static final String[][] REASON_PHRASES = new String[][]{
54          new String[0],
55          new String[3],
56          new String[8],
57          new String[8],
58          new String[25],
59          new String[8]
60      };
61  
62  
63      // --------------------------------------------------------- Public Methods
64  
65      /**
66       * Get the reason phrase for a particular status code.
67       * 
68       * This method always returns the English text as specified in the
69       * relevent RFCs and is not internationalized.
70       * 
71       * @param statusCode the numeric status code
72       * @return the reason phrase associated with the given status code
73       * or null if the status code is not recognized.
74       * 
75       * TODO: getStatusText should be called getReasonPhrase to match RFC
76       */
77      public static String getStatusText(int statusCode) {
78  
79          if (statusCode < 0) {
80              throw new IllegalArgumentException("status code may not be negative");
81          }
82          int classIndex = statusCode / 100;
83          int codeIndex = statusCode - classIndex * 100;
84          if (classIndex < 1 || classIndex > (REASON_PHRASES.length - 1) 
85              || codeIndex < 0 || codeIndex > (REASON_PHRASES[classIndex].length - 1)) {
86              return null;
87          }
88          return REASON_PHRASES[classIndex][codeIndex];
89      }
90  
91  
92      // -------------------------------------------------------- Private Methods
93  
94      /**
95       * Store the given reason phrase, by status code.
96       * @param statusCode The status code to lookup
97       * @param reasonPhrase The reason phrase for this status code
98       */
99      private static void addStatusCodeMap(int statusCode, String reasonPhrase) {
100         int classIndex = statusCode / 100;
101         REASON_PHRASES[classIndex][statusCode - classIndex * 100] = reasonPhrase;
102     }
103 
104 
105     // -------------------------------------------------------------- Constants
106 
107     // --- 1xx Informational ---
108 
109     /** <tt>100 Continue</tt> (HTTP/1.1 - RFC 2616) */
110     public static final int SC_CONTINUE = 100;
111     /** <tt>101 Switching Protocols</tt> (HTTP/1.1 - RFC 2616)*/
112     public static final int SC_SWITCHING_PROTOCOLS = 101;
113     /** <tt>102 Processing</tt> (WebDAV - RFC 2518) */
114     public static final int SC_PROCESSING = 102;
115 
116     // --- 2xx Success ---
117 
118     /** <tt>200 OK</tt> (HTTP/1.0 - RFC 1945) */
119     public static final int SC_OK = 200;
120     /** <tt>201 Created</tt> (HTTP/1.0 - RFC 1945) */
121     public static final int SC_CREATED = 201;
122     /** <tt>202 Accepted</tt> (HTTP/1.0 - RFC 1945) */
123     public static final int SC_ACCEPTED = 202;
124     /** <tt>203 Non Authoritative Information</tt> (HTTP/1.1 - RFC 2616) */
125     public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
126     /** <tt>204 No Content</tt> (HTTP/1.0 - RFC 1945) */
127     public static final int SC_NO_CONTENT = 204;
128     /** <tt>205 Reset Content</tt> (HTTP/1.1 - RFC 2616) */
129     public static final int SC_RESET_CONTENT = 205;
130     /** <tt>206 Partial Content</tt> (HTTP/1.1 - RFC 2616) */
131     public static final int SC_PARTIAL_CONTENT = 206;
132     /** 
133      * <tt>207 Multi-Status</tt> (WebDAV - RFC 2518) or <tt>207 Partial Update
134      * OK</tt> (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?)
135      */
136     public static final int SC_MULTI_STATUS = 207;
137 
138     // --- 3xx Redirection ---
139 
140     /** <tt>300 Mutliple Choices</tt> (HTTP/1.1 - RFC 2616) */
141     public static final int SC_MULTIPLE_CHOICES = 300;
142     /** <tt>301 Moved Permanently</tt> (HTTP/1.0 - RFC 1945) */
143     public static final int SC_MOVED_PERMANENTLY = 301;
144     /** <tt>302 Moved Temporarily</tt> (Sometimes <tt>Found</tt>) (HTTP/1.0 - RFC 1945) */
145     public static final int SC_MOVED_TEMPORARILY = 302;
146     /** <tt>303 See Other</tt> (HTTP/1.1 - RFC 2616) */
147     public static final int SC_SEE_OTHER = 303;
148     /** <tt>304 Not Modified</tt> (HTTP/1.0 - RFC 1945) */
149     public static final int SC_NOT_MODIFIED = 304;
150     /** <tt>305 Use Proxy</tt> (HTTP/1.1 - RFC 2616) */
151     public static final int SC_USE_PROXY = 305;
152     /** <tt>307 Temporary Redirect</tt> (HTTP/1.1 - RFC 2616) */
153     public static final int SC_TEMPORARY_REDIRECT = 307;
154 
155     // --- 4xx Client Error ---
156 
157     /** <tt>400 Bad Request</tt> (HTTP/1.1 - RFC 2616) */
158     public static final int SC_BAD_REQUEST = 400;
159     /** <tt>401 Unauthorized</tt> (HTTP/1.0 - RFC 1945) */
160     public static final int SC_UNAUTHORIZED = 401;
161     /** <tt>402 Payment Required</tt> (HTTP/1.1 - RFC 2616) */
162     public static final int SC_PAYMENT_REQUIRED = 402;
163     /** <tt>403 Forbidden</tt> (HTTP/1.0 - RFC 1945) */
164     public static final int SC_FORBIDDEN = 403;
165     /** <tt>404 Not Found</tt> (HTTP/1.0 - RFC 1945) */
166     public static final int SC_NOT_FOUND = 404;
167     /** <tt>405 Method Not Allowed</tt> (HTTP/1.1 - RFC 2616) */
168     public static final int SC_METHOD_NOT_ALLOWED = 405;
169     /** <tt>406 Not Acceptable</tt> (HTTP/1.1 - RFC 2616) */
170     public static final int SC_NOT_ACCEPTABLE = 406;
171     /** <tt>407 Proxy Authentication Required</tt> (HTTP/1.1 - RFC 2616)*/
172     public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
173     /** <tt>408 Request Timeout</tt> (HTTP/1.1 - RFC 2616) */
174     public static final int SC_REQUEST_TIMEOUT = 408;
175     /** <tt>409 Conflict</tt> (HTTP/1.1 - RFC 2616) */
176     public static final int SC_CONFLICT = 409;
177     /** <tt>410 Gone</tt> (HTTP/1.1 - RFC 2616) */
178     public static final int SC_GONE = 410;
179     /** <tt>411 Length Required</tt> (HTTP/1.1 - RFC 2616) */
180     public static final int SC_LENGTH_REQUIRED = 411;
181     /** <tt>412 Precondition Failed</tt> (HTTP/1.1 - RFC 2616) */
182     public static final int SC_PRECONDITION_FAILED = 412;
183     /** <tt>413 Request Entity Too Large</tt> (HTTP/1.1 - RFC 2616) */
184     public static final int SC_REQUEST_TOO_LONG = 413;
185     /** <tt>414 Request-URI Too Long</tt> (HTTP/1.1 - RFC 2616) */
186     public static final int SC_REQUEST_URI_TOO_LONG = 414;
187     /** <tt>415 Unsupported Media Type</tt> (HTTP/1.1 - RFC 2616) */
188     public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
189     /** <tt>416 Requested Range Not Satisfiable</tt> (HTTP/1.1 - RFC 2616) */
190     public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
191     /** <tt>417 Expectation Failed</tt> (HTTP/1.1 - RFC 2616) */
192     public static final int SC_EXPECTATION_FAILED = 417;
193 
194     /**
195      * Static constant for a 418 error.
196      * <tt>418 Unprocessable Entity</tt> (WebDAV drafts?)
197      * or <tt>418 Reauthentication Required</tt> (HTTP/1.1 drafts?)
198      */
199     // not used
200     // public static final int SC_UNPROCESSABLE_ENTITY = 418;
201 
202     /**
203      * Static constant for a 419 error.
204      * <tt>419 Insufficient Space on Resource</tt>
205      * (WebDAV - draft-ietf-webdav-protocol-05?)
206      * or <tt>419 Proxy Reauthentication Required</tt>
207      * (HTTP/1.1 drafts?)
208      */
209     public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419;
210     /**
211      * Static constant for a 420 error.
212      * <tt>420 Method Failure</tt>
213      * (WebDAV - draft-ietf-webdav-protocol-05?)
214      */
215     public static final int SC_METHOD_FAILURE = 420;
216     /** <tt>422 Unprocessable Entity</tt> (WebDAV - RFC 2518) */
217     public static final int SC_UNPROCESSABLE_ENTITY = 422;
218     /** <tt>423 Locked</tt> (WebDAV - RFC 2518) */
219     public static final int SC_LOCKED = 423;
220     /** <tt>424 Failed Dependency</tt> (WebDAV - RFC 2518) */
221     public static final int SC_FAILED_DEPENDENCY = 424;
222 
223     // --- 5xx Server Error ---
224 
225     /** <tt>500 Server Error</tt> (HTTP/1.0 - RFC 1945) */
226     public static final int SC_INTERNAL_SERVER_ERROR = 500;
227     /** <tt>501 Not Implemented</tt> (HTTP/1.0 - RFC 1945) */
228     public static final int SC_NOT_IMPLEMENTED = 501;
229     /** <tt>502 Bad Gateway</tt> (HTTP/1.0 - RFC 1945) */
230     public static final int SC_BAD_GATEWAY = 502;
231     /** <tt>503 Service Unavailable</tt> (HTTP/1.0 - RFC 1945) */
232     public static final int SC_SERVICE_UNAVAILABLE = 503;
233     /** <tt>504 Gateway Timeout</tt> (HTTP/1.1 - RFC 2616) */
234     public static final int SC_GATEWAY_TIMEOUT = 504;
235     /** <tt>505 HTTP Version Not Supported</tt> (HTTP/1.1 - RFC 2616) */
236     public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
237 
238     /** <tt>507 Insufficient Storage</tt> (WebDAV - RFC 2518) */
239     public static final int SC_INSUFFICIENT_STORAGE = 507;
240 
241 
242     // ----------------------------------------------------- Static Initializer
243 
244     /** Set up status code to "reason phrase" map. */
245     static {
246         // HTTP 1.0 Server status codes -- see RFC 1945
247         addStatusCodeMap(SC_OK, "OK");
248         addStatusCodeMap(SC_CREATED, "Created");
249         addStatusCodeMap(SC_ACCEPTED, "Accepted");
250         addStatusCodeMap(SC_NO_CONTENT, "No Content");
251         addStatusCodeMap(SC_MOVED_PERMANENTLY, "Moved Permanently");
252         addStatusCodeMap(SC_MOVED_TEMPORARILY, "Moved Temporarily");
253         addStatusCodeMap(SC_NOT_MODIFIED, "Not Modified");
254         addStatusCodeMap(SC_BAD_REQUEST, "Bad Request");
255         addStatusCodeMap(SC_UNAUTHORIZED, "Unauthorized");
256         addStatusCodeMap(SC_FORBIDDEN, "Forbidden");
257         addStatusCodeMap(SC_NOT_FOUND, "Not Found");
258         addStatusCodeMap(SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
259         addStatusCodeMap(SC_NOT_IMPLEMENTED, "Not Implemented");
260         addStatusCodeMap(SC_BAD_GATEWAY, "Bad Gateway");
261         addStatusCodeMap(SC_SERVICE_UNAVAILABLE, "Service Unavailable");
262 
263         // HTTP 1.1 Server status codes -- see RFC 2048
264         addStatusCodeMap(SC_CONTINUE, "Continue");
265         addStatusCodeMap(SC_TEMPORARY_REDIRECT, "Temporary Redirect");
266         addStatusCodeMap(SC_METHOD_NOT_ALLOWED, "Method Not Allowed");
267         addStatusCodeMap(SC_CONFLICT, "Conflict");
268         addStatusCodeMap(SC_PRECONDITION_FAILED, "Precondition Failed");
269         addStatusCodeMap(SC_REQUEST_TOO_LONG, "Request Too Long");
270         addStatusCodeMap(SC_REQUEST_URI_TOO_LONG, "Request-URI Too Long");
271         addStatusCodeMap(SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type");
272         addStatusCodeMap(SC_MULTIPLE_CHOICES, "Multiple Choices");
273         addStatusCodeMap(SC_SEE_OTHER, "See Other");
274         addStatusCodeMap(SC_USE_PROXY, "Use Proxy");
275         addStatusCodeMap(SC_PAYMENT_REQUIRED, "Payment Required");
276         addStatusCodeMap(SC_NOT_ACCEPTABLE, "Not Acceptable");
277         addStatusCodeMap(SC_PROXY_AUTHENTICATION_REQUIRED, 
278             "Proxy Authentication Required");
279         addStatusCodeMap(SC_REQUEST_TIMEOUT, 
280             "Request Timeout");
281 
282         addStatusCodeMap(SC_SWITCHING_PROTOCOLS, "Switching Protocols");
283         addStatusCodeMap(SC_NON_AUTHORITATIVE_INFORMATION,
284                          "Non Authoritative Information");
285         addStatusCodeMap(SC_RESET_CONTENT, "Reset Content");
286         addStatusCodeMap(SC_PARTIAL_CONTENT, "Partial Content");
287         addStatusCodeMap(SC_GATEWAY_TIMEOUT, "Gateway Timeout");
288         addStatusCodeMap(SC_HTTP_VERSION_NOT_SUPPORTED,
289                          "Http Version Not Supported");
290         addStatusCodeMap(SC_GONE,
291                          "Gone");
292         addStatusCodeMap(SC_LENGTH_REQUIRED,
293                          "Length Required");
294         addStatusCodeMap(SC_REQUESTED_RANGE_NOT_SATISFIABLE,
295                          "Requested Range Not Satisfiable");
296         addStatusCodeMap(SC_EXPECTATION_FAILED,
297                          "Expectation Failed");
298 
299         // WebDAV Server-specific status codes
300         addStatusCodeMap(SC_PROCESSING, "Processing");
301         addStatusCodeMap(SC_MULTI_STATUS, "Multi-Status");
302         addStatusCodeMap(SC_UNPROCESSABLE_ENTITY, "Unprocessable Entity");
303         addStatusCodeMap(SC_INSUFFICIENT_SPACE_ON_RESOURCE,
304                          "Insufficient Space On Resource");
305         addStatusCodeMap(SC_METHOD_FAILURE, "Method Failure");
306         addStatusCodeMap(SC_LOCKED, "Locked");
307         addStatusCodeMap(SC_INSUFFICIENT_STORAGE , "Insufficient Storage");
308         addStatusCodeMap(SC_FAILED_DEPENDENCY, "Failed Dependency");
309     }
310 
311 
312 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpURL.html100644 0 0 217523 10661532627 24342 0ustar 0 0 HttpURL xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpURL.java,v 1.18 2004/09/30 17:26:41 oglueck Exp $
3    * $Revision: 507324 $
4    * $Date: 2007-02-14 01:12:11 +0100 (Wed, 14 Feb 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import org.apache.commons.httpclient.util.URIUtil;
34  
35  /**
36   * The HTTP URL.
37   *
38   * @author <a href="mailto:jericho at apache.org">Sung-Gu</a>
39   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
40   */
41  public class HttpURL extends URI {
42  
43      // ----------------------------------------------------------- Constructors
44  
45      /** Create an instance as an internal use. */
46      protected HttpURL() {
47      }
48  
49  
50      /**
51       * Construct a HTTP URL as an escaped form of a character array with the
52       * given charset to do escape encoding.
53       *
54       * @param escaped the HTTP URL character sequence
55       * @param charset the charset string to do escape encoding
56       * @throws URIException If {@link #checkValid()} fails
57       * @throws NullPointerException if <code>escaped</code> is <code>null</code>
58       * @see #getProtocolCharset
59       */
60      public HttpURL(char[] escaped, String charset)
61          throws URIException, NullPointerException {
62          protocolCharset = charset;
63          parseUriReference(new String(escaped), true);
64          checkValid();
65      }
66  
67  
68      /**
69       * Construct a HTTP URL as an escaped form of a character array.
70       *
71       * @param escaped the HTTP URL character sequence
72       * @throws URIException If {@link #checkValid()} fails
73       * @throws NullPointerException if <code>escaped</code> is <code>null</code>
74       * @see #getDefaultProtocolCharset
75       */
76      public HttpURL(char[] escaped) throws URIException, NullPointerException {
77          parseUriReference(new String(escaped), true);
78          checkValid();
79      }
80  
81  
82      /**
83       * Construct a HTTP URL from a given string with the given charset to do
84       * escape encoding.
85       *
86       * @param original the HTTP URL string
87       * @param charset the charset string to do escape encoding
88       * @throws URIException If {@link #checkValid()} fails
89       * @see #getProtocolCharset
90       */
91      public HttpURL(String original, String charset) throws URIException {
92          protocolCharset = charset;
93          parseUriReference(original, false);
94          checkValid();
95      }
96  
97  
98      /**
99       * Construct a HTTP URL from a given string.
100      *
101      * @param original the HTTP URL string
102      * @throws URIException If {@link #checkValid()} fails
103      * @see #getDefaultProtocolCharset
104      */
105     public HttpURL(String original) throws URIException {
106         parseUriReference(original, false);
107         checkValid();
108     }
109 
110 
111     /**
112      * Construct a HTTP URL from given components.
113      *
114      * @param host the host string
115      * @param port the port number
116      * @param path the path string
117      * @throws URIException If {@link #checkValid()} fails
118      * @see #getDefaultProtocolCharset
119      */
120     public HttpURL(String host, int port, String path) throws URIException {
121         this(null, null, host, port, path, null, null);
122     }
123 
124 
125     /**
126      * Construct a HTTP URL from given components.
127      *
128      * @param host the host string
129      * @param port the port number
130      * @param path the path string
131      * @param query the query string
132      * @throws URIException If {@link #checkValid()} fails
133      * @see #getDefaultProtocolCharset
134      */
135     public HttpURL(String host, int port, String path, String query)
136         throws URIException {
137 
138         this(null, null, host, port, path, query, null);
139     }
140 
141 
142     /**
143      * Construct a HTTP URL from given components.
144      *
145      * @param user the user name
146      * @param password his or her password
147      * @param host the host string
148      * @throws URIException If {@link #checkValid()} fails
149      * @see #getDefaultProtocolCharset
150      */
151     public HttpURL(String user, String password, String host)
152         throws URIException {
153 
154         this(user, password, host, -1, null, null, null);
155     }
156 
157 
158     /**
159      * Construct a HTTP URL from given components.
160      *
161      * @param user the user name
162      * @param password his or her password
163      * @param host the host string
164      * @param port the port number
165      * @throws URIException If {@link #checkValid()} fails
166      * @see #getDefaultProtocolCharset
167      */
168     public HttpURL(String user, String password, String host, int port)
169         throws URIException {
170 
171         this(user, password, host, port, null, null, null);
172     }
173 
174 
175     /**
176      * Construct a HTTP URL from given components.
177      *
178      * @param user the user name
179      * @param password his or her password
180      * @param host the host string
181      * @param port the port number
182      * @param path the path string
183      * @throws URIException If {@link #checkValid()} fails
184      * @see #getDefaultProtocolCharset
185      */
186     public HttpURL(String user, String password, String host, int port,
187             String path) throws URIException {
188 
189         this(user, password, host, port, path, null, null);
190     }
191 
192 
193     /**
194      * Construct a HTTP URL from given components.
195      *
196      * @param user the user name
197      * @param password his or her password
198      * @param host the host string
199      * @param port the port number
200      * @param path the path string
201      * @param query The query string.
202      * @throws URIException If {@link #checkValid()} fails
203      * @see #getDefaultProtocolCharset
204      */
205     public HttpURL(String user, String password, String host, int port,
206             String path, String query) throws URIException {
207 
208         this(user, password, host, port, path, query, null);
209     }
210 
211 
212     /**
213      * Construct a HTTP URL from given components.
214      *
215      * @param host the host string
216      * @param path the path string
217      * @param query the query string
218      * @param fragment the fragment string
219      * @throws URIException If {@link #checkValid()} fails
220      * @see #getDefaultProtocolCharset
221      */
222     public HttpURL(String host, String path, String query, String fragment)
223         throws URIException {
224 
225         this(null, null, host, -1, path, query, fragment);
226     }
227 
228 
229     /**
230      * Construct a HTTP URL from given components.
231      * 
232      * Note: The <code>userinfo</code> format is normally
233      * <code>&lt;username&gt;:&lt;password&gt;</code> where
234      * username and password must both be URL escaped. 
235      *
236      * @param userinfo the userinfo string whose parts are URL escaped
237      * @param host the host string
238      * @param path the path string
239      * @param query the query string
240      * @param fragment the fragment string
241      * @throws URIException If {@link #checkValid()} fails
242      * @see #getDefaultProtocolCharset
243      */
244     public HttpURL(String userinfo, String host, String path, String query,
245             String fragment) throws URIException {
246 
247         this(userinfo, host, -1, path, query, fragment);
248     }
249 
250 
251     /**
252      * Construct a HTTP URL from given components.
253      *
254      * Note: The <code>userinfo</code> format is normally
255      * <code>&lt;username&gt;:&lt;password&gt;</code> where
256      * username and password must both be URL escaped.
257      *  
258      * @param userinfo the userinfo string whose parts are URL escaped
259      * @param host the host string
260      * @param port the port number
261      * @param path the path string
262      * @throws URIException If {@link #checkValid()} fails
263      * @see #getDefaultProtocolCharset
264      */
265     public HttpURL(String userinfo, String host, int port, String path)
266         throws URIException {
267 
268         this(userinfo, host, port, path, null, null);
269     }
270 
271 
272     /**
273      * Construct a HTTP URL from given components.
274      *
275      * Note: The <code>userinfo</code> format is normally
276      * <code>&lt;username&gt;:&lt;password&gt;</code> where
277      * username and password must both be URL escaped.
278      *  
279      * @param userinfo the userinfo string whose parts are URL escaped
280      * @param host the host string
281      * @param port the port number
282      * @param path the path string
283      * @param query the query string
284      * @throws URIException If {@link #checkValid()} fails
285      * @see #getDefaultProtocolCharset
286      */
287     public HttpURL(String userinfo, String host, int port, String path,
288             String query) throws URIException {
289 
290         this(userinfo, host, port, path, query, null);
291     }
292 
293 
294     /**
295      * Construct a HTTP URL from given components.
296      *
297      * Note: The <code>userinfo</code> format is normally
298      * <code>&lt;username&gt;:&lt;password&gt;</code> where
299      * username and password must both be URL escaped.
300      *  
301      * @param userinfo the userinfo string whose parts are URL escaped
302      * @param host the host string
303      * @param port the port number
304      * @param path the path string
305      * @param query the query string
306      * @param fragment the fragment string
307      * @throws URIException If {@link #checkValid()} fails
308      * @see #getDefaultProtocolCharset
309      */
310     public HttpURL(String userinfo, String host, int port, String path,
311             String query, String fragment) throws URIException {
312 
313         // validate and contruct the URI character sequence
314         StringBuffer buff = new StringBuffer();
315         if (userinfo != null || host != null || port != -1) {
316             _scheme = DEFAULT_SCHEME; // in order to verify the own protocol
317             buff.append(_default_scheme);
318             buff.append("://");
319             if (userinfo != null) {
320                 buff.append(userinfo);
321                 buff.append('@');
322             }
323             if (host != null) {
324                 buff.append(URIUtil.encode(host, URI.allowed_host));
325                 if (port != -1 || port != DEFAULT_PORT) {
326                     buff.append(':');
327                     buff.append(port);
328                 }
329             }
330         }
331         if (path != null) {  // accept empty path
332             if (scheme != null && !path.startsWith("/")) {
333                 throw new URIException(URIException.PARSING,
334                         "abs_path requested");
335             }
336             buff.append(URIUtil.encode(path, URI.allowed_abs_path));
337         }
338         if (query != null) {
339             buff.append('?');
340             buff.append(URIUtil.encode(query, URI.allowed_query));
341         }
342         if (fragment != null) {
343             buff.append('#');
344             buff.append(URIUtil.encode(fragment, URI.allowed_fragment));
345         }
346         parseUriReference(buff.toString(), true);
347         checkValid();
348     }
349 
350 
351     /**
352      * Construct a HTTP URL from given components.
353      *
354      * @param user the user name
355      * @param password his or her password
356      * @param host the host string
357      * @param port the port number
358      * @param path the path string
359      * @param query the query string
360      * @param fragment the fragment string
361      * @throws URIException If {@link #checkValid()} fails
362      * @see #getDefaultProtocolCharset
363      */
364     public HttpURL(String user, String password, String host, int port,
365             String path, String query, String fragment) throws URIException {
366         this(toUserinfo(user, password), host, port, path, query, fragment);
367     }
368     
369     protected static String toUserinfo(String user, String password) throws URIException {
370         if (user == null) return null;
371         StringBuffer usrinfo = new StringBuffer(20); //sufficient for real world
372         usrinfo.append(URIUtil.encode(user, URI.allowed_within_userinfo));
373         if (password == null) return usrinfo.toString();
374         usrinfo.append(':');
375         usrinfo.append(URIUtil.encode(password, URI.allowed_within_userinfo));
376         return usrinfo.toString();
377     }
378 
379 
380     /**
381      * Construct a HTTP URL with a given relative URL string.
382      *
383      * @param base the base HttpURL
384      * @param relative the relative HTTP URL string
385      * @throws URIException If {@link #checkValid()} fails
386      */
387     public HttpURL(HttpURL base, String relative) throws URIException {
388         this(base, new HttpURL(relative));
389     }
390 
391 
392     /**
393      * Construct a HTTP URL with a given relative URL.
394      *
395      * @param base the base HttpURL
396      * @param relative the relative HttpURL
397      * @throws URIException If {@link #checkValid()} fails
398      */
399     public HttpURL(HttpURL base, HttpURL relative) throws URIException {
400         super(base, relative);
401         checkValid();
402     }
403 
404     // -------------------------------------------------------------- Constants
405 
406     /**
407      * Default scheme for HTTP URL.
408      */
409     public static final char[] DEFAULT_SCHEME = { 'h', 't', 't', 'p' };
410 
411     /**
412      * Default scheme for HTTP URL.
413      * @deprecated Use {@link #DEFAULT_SCHEME} instead.  This one doesn't
414      * conform to the project naming conventions.
415      */
416     public static final char[] _default_scheme = DEFAULT_SCHEME;
417 
418     /**
419      * Default port for HTTP URL.
420      */
421     public static final int DEFAULT_PORT = 80;
422 
423     /**
424      * Default port for HTTP URL.
425      * @deprecated Use {@link #DEFAULT_PORT} instead.  This one doesn't conform
426      * to the project naming conventions.
427      */
428     public static final int _default_port = DEFAULT_PORT;
429 
430     /**
431      * The serialVersionUID.
432      */
433     static final long serialVersionUID = -7158031098595039459L;
434 
435     // ------------------------------------------------------------- The scheme
436 
437     /**
438      * Get the scheme.  You can get the scheme explicitly.
439      *
440      * @return the scheme
441      */
442     public char[] getRawScheme() {
443         return (_scheme == null) ? null : HttpURL.DEFAULT_SCHEME;
444     }
445 
446 
447     /**
448      * Get the scheme.  You can get the scheme explicitly.
449      *
450      * @return the scheme null if empty or undefined
451      */
452     public String getScheme() {
453         return (_scheme == null) ? null : new String(HttpURL.DEFAULT_SCHEME);
454     }
455 
456     // --------------------------------------------------------------- The port
457 
458     /**
459      * Get the port number.
460      * @return the port number
461      */
462     public int getPort() {
463         return (_port == -1) ? HttpURL.DEFAULT_PORT : _port;
464     }
465 
466     // ----------------------------------------------------------- The userinfo
467 
468     /**
469      * Set the raw-escaped user and password.
470      *
471      * @param escapedUser the raw-escaped user
472      * @param escapedPassword the raw-escaped password; could be null
473      * @throws URIException escaped user not valid or user required; escaped
474      * password not valid or username missed
475      */
476     public void setRawUserinfo(char[] escapedUser, char[] escapedPassword)
477         throws URIException {
478 
479         if (escapedUser == null || escapedUser.length == 0) {
480             throw new URIException(URIException.PARSING, "user required");
481         }
482         if (!validate(escapedUser, within_userinfo) 
483             || ((escapedPassword != null) 
484             && !validate(escapedPassword, within_userinfo))) {
485             throw new URIException(URIException.ESCAPING,
486                     "escaped userinfo not valid");
487         }
488         String username = new String(escapedUser);
489         String password = (escapedPassword == null) 
490             ? null : new String(escapedPassword);
491         String userinfo = username + ((password == null) ? "" : ":" + password);
492         String hostname = new String(getRawHost());
493         String hostport = (_port == -1) ? hostname : hostname + ":" + _port;
494         String authority = userinfo + "@" + hostport;
495         _userinfo = userinfo.toCharArray();
496         _authority = authority.toCharArray();
497         setURI();
498     }
499 
500 
501     /**
502      * Set the raw-escaped user and password.
503      *
504      * @param escapedUser the escaped user
505      * @param escapedPassword the escaped password; could be null
506      * @throws URIException escaped user not valid or user required; escaped
507      * password not valid or username missed
508      * @throws NullPointerException null user
509      */
510     public void setEscapedUserinfo(String escapedUser, String escapedPassword)
511         throws URIException, NullPointerException {
512 
513         setRawUserinfo(escapedUser.toCharArray(), (escapedPassword == null) 
514             ? null : escapedPassword.toCharArray());
515     }
516 
517 
518     /**
519      * Set the user and password.
520      *
521      * @param user the user
522      * @param password the password; could be null
523      * @throws URIException encoding error or username missed
524      * @throws NullPointerException null user
525      */
526     public void setUserinfo(String user, String password) 
527         throws URIException, NullPointerException {
528         // set the charset to do escape encoding
529         String charset = getProtocolCharset();
530         setRawUserinfo(encode(user, within_userinfo, charset),
531                 (password == null) 
532                 ? null 
533                 : encode(password, within_userinfo, charset));
534     }
535 
536 
537     /**
538      * Set the raw-escaped user.
539      *
540      * @param escapedUser the raw-escaped user
541      * @throws URIException escaped user not valid or user required
542      */
543     public void setRawUser(char[] escapedUser) throws URIException {
544         if (escapedUser == null || escapedUser.length == 0) {
545             throw new URIException(URIException.PARSING, "user required");
546         }
547         if (!validate(escapedUser, within_userinfo)) {
548             throw new URIException(URIException.ESCAPING,
549                     "escaped user not valid");
550         }
551         String username = new String(escapedUser);
552         char[] rawPassword = getRawPassword();
553 		String password = rawPassword == null ? null : new String(rawPassword);
554         String userinfo = username + ((password == null) ? "" : ":" + password);
555         String hostname = new String(getRawHost());
556         String hostport = (_port == -1) ? hostname : hostname + ":" + _port;
557         String authority = userinfo + "@" + hostport;
558         _userinfo = userinfo.toCharArray();
559         _authority = authority.toCharArray();
560         setURI();
561     }
562 
563 
564     /**
565      * Set the escaped user string.
566      *
567      * @param escapedUser the escaped user string
568      * @throws URIException escaped user not valid
569      * @throws NullPointerException null user
570      */
571     public void setEscapedUser(String escapedUser)
572         throws URIException, NullPointerException {
573         setRawUser(escapedUser.toCharArray());
574     }
575 
576 
577     /**
578      * Set the user string.
579      *
580      * @param user the user string
581      * @throws URIException user encoding error
582      * @throws NullPointerException null user
583      */
584     public void setUser(String user) throws URIException, NullPointerException {
585         setRawUser(encode(user, allowed_within_userinfo, getProtocolCharset()));
586     }
587 
588 
589     /**
590      * Get the raw-escaped user.
591      *
592      * @return the raw-escaped user
593      */
594     public char[] getRawUser() {
595         if (_userinfo == null || _userinfo.length == 0) {
596             return null;
597         }
598         int to = indexFirstOf(_userinfo, ':');
599         // String.indexOf(':', 0, _userinfo.length, _userinfo, 0, 1, 0);
600         if (to == -1) {
601             return _userinfo; // only user.
602         }
603         char[] result = new char[to];
604         System.arraycopy(_userinfo, 0, result, 0, to);
605         return result;
606     }
607 
608 
609     /**
610      * Get the escaped user
611      *
612      * @return the escaped user
613      */
614     public String getEscapedUser() {
615         char[] user = getRawUser();
616         return (user == null) ? null : new String(user);
617     }
618 
619 
620     /**
621      * Get the user.
622      *
623      * @return the user name
624      * @throws URIException If {@link #decode} fails
625      */
626     public String getUser() throws URIException {
627         char[] user = getRawUser();
628         return (user == null) ? null : decode(user, getProtocolCharset());
629     }
630 
631 
632     /**
633      * Set the raw-escaped password.
634      *
635      * @param escapedPassword the raw-escaped password; could be null
636      * @throws URIException escaped password not valid or username missed
637      */
638     public void setRawPassword(char[] escapedPassword) throws URIException {
639         if (escapedPassword != null 
640             && !validate(escapedPassword, within_userinfo)) {
641             throw new URIException(URIException.ESCAPING,
642                "escaped password not valid");
643         }
644         if (getRawUser() == null || getRawUser().length == 0) {
645             throw new URIException(URIException.PARSING, "username required");
646         }
647         String username = new String(getRawUser());
648         String password = escapedPassword == null ? null : new String(escapedPassword);
649         // an emtpy string is allowed as a password
650         String userinfo = username + ((password == null) ? "" : ":" + password);
651         String hostname = new String(getRawHost());
652         String hostport = (_port == -1) ? hostname : hostname + ":" + _port;
653         String authority = userinfo + "@" + hostport;
654         _userinfo = userinfo.toCharArray();
655         _authority = authority.toCharArray();
656         setURI();
657     }
658 
659 
660     /**
661      * Set the escaped password string.
662      *
663      * @param escapedPassword the escaped password string; could be null
664      * @throws URIException escaped password not valid or username missed
665      */
666     public void setEscapedPassword(String escapedPassword) throws URIException {
667         setRawPassword((escapedPassword == null) ? null 
668             : escapedPassword.toCharArray());
669     }
670 
671 
672     /**
673      * Set the password string.
674      *
675      * @param password the password string; could be null
676      * @throws URIException encoding error or username missed
677      */
678     public void setPassword(String password) throws URIException {
679         setRawPassword((password == null) ? null : encode(password,
680                     allowed_within_userinfo, getProtocolCharset()));
681     }
682 
683 
684     /**
685      * Get the raw-escaped password.
686      *
687      * @return the raw-escaped password
688      */
689     public char[] getRawPassword() {
690         int from = indexFirstOf(_userinfo, ':');
691         if (from == -1) {
692             return null; // null or only user.
693         }
694         int len = _userinfo.length - from - 1;
695         char[] result = new char[len];
696         System.arraycopy(_userinfo, from + 1, result, 0, len);
697         return result;
698     }
699 
700 
701     /**
702      * Get the escaped password.
703      *
704      * @return the escaped password
705      */
706     public String getEscapedPassword() {
707         char[] password = getRawPassword();
708         return (password == null) ? null : new String(password);
709     }
710 
711 
712     /**
713      * Get the password.
714      *
715      * @return the password
716      * @throws URIException If {@link #decode(char[],String)} fails.
717      */
718     public String getPassword() throws URIException {
719         char[] password = getRawPassword();
720         return (password == null) ? null : decode(password,
721                 getProtocolCharset());
722     }
723 
724     // --------------------------------------------------------------- The path
725 
726     /**
727      * Get the raw-escaped current hierarchy level.
728      *
729      * @return the raw-escaped current hierarchy level
730      * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails.
731      */
732     public char[] getRawCurrentHierPath() throws URIException {
733         return (_path == null || _path.length == 0) ? rootPath 
734             : super.getRawCurrentHierPath(_path);
735     }
736 
737 
738     /**
739      * Get the level above the this hierarchy level.
740      *
741      * @return the raw above hierarchy level
742      * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails.
743      */
744     public char[] getRawAboveHierPath() throws URIException {
745         char[] path = getRawCurrentHierPath();
746         return (path == null || path.length == 0) ? rootPath : getRawCurrentHierPath(path);
747     }
748 
749 
750     /**
751      * Get the raw escaped path.
752      *
753      * @return the path '/' if empty or undefined
754      */
755     public char[] getRawPath() {
756         char[] path =  super.getRawPath();
757         return (path == null || path.length == 0) ? rootPath : path;
758     }
759 
760     // -------------------------------------------------------------- The query
761 
762     /**
763      * Set the query as the name and value pair.
764      *
765      * @param queryName the query string.
766      * @param queryValue the query string.
767      * @throws URIException incomplete trailing escape pattern
768      * Or unsupported character encoding
769      * @throws NullPointerException null query
770      * @see #encode
771      */
772     public void setQuery(String queryName, String queryValue)
773         throws URIException, NullPointerException {
774 
775         StringBuffer buff = new StringBuffer();
776         // set the charset to do escape encoding
777         String charset = getProtocolCharset();
778         buff.append(encode(queryName, allowed_within_query, charset));
779         buff.append('=');
780         buff.append(encode(queryValue, allowed_within_query, charset));
781         _query = buff.toString().toCharArray();
782         setURI();
783     }
784 
785 
786     /**
787      * Set the query as the name and value pairs.
788      *
789      * @param queryName the array of the query string.
790      * @param queryValue the array of the query string.
791      * @throws URIException incomplete trailing escape pattern,
792      * unsupported character encoding or wrong array size
793      * @throws NullPointerException null query
794      * @see #encode
795      */
796     public void setQuery(String[] queryName, String[] queryValue)
797         throws URIException, NullPointerException {
798 
799         int length = queryName.length;
800         if (length != queryValue.length) {
801             throw new URIException("wrong array size of query");
802         }
803 
804         StringBuffer buff = new StringBuffer();
805         // set the charset to do escape encoding
806         String charset = getProtocolCharset();
807         for (int i = 0; i < length; i++) {
808             buff.append(encode(queryName[i], allowed_within_query, charset));
809             buff.append('=');
810             buff.append(encode(queryValue[i], allowed_within_query, charset));
811             if (i + 1 < length) { 
812                 buff.append('&');
813             }
814         }
815         _query = buff.toString().toCharArray();
816         setURI();
817     }
818 
819     // ---------------------------------------------------------------- Utility
820 
821     /**
822      * Verify the valid class use for construction.
823      *
824      * @throws URIException the wrong scheme use
825      */
826     protected void checkValid() throws URIException {
827         // could be explicit protocol or undefined.
828         if (!(equals(_scheme, DEFAULT_SCHEME) || _scheme == null)) {
829             throw new URIException(URIException.PARSING, "wrong class use");
830         }
831     }
832 
833     /**
834      * Once it's parsed successfully, set this URI.
835      *
836      * @see #getRawURI
837      */
838     protected void setURI() {
839         // set _uri
840         StringBuffer buf = new StringBuffer();
841         // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
842         if (_scheme != null) {
843             buf.append(_scheme);
844             buf.append(':');
845         }
846         if (_is_net_path) {
847             buf.append("//");
848             if (_authority != null) { // has_authority
849                 if (_userinfo != null) { // by default, remove userinfo part
850                     if (_host != null) {
851                         buf.append(_host);
852                         if (_port != -1) {
853                             buf.append(':');
854                             buf.append(_port);
855                         }
856                     }
857                 } else {
858                     buf.append(_authority);
859                 }
860             }
861         }
862         if (_opaque != null && _is_opaque_part) {
863             buf.append(_opaque);
864         } else if (_path != null) {
865             // _is_hier_part or _is_relativeURI
866             if (_path.length != 0) {
867                 buf.append(_path);
868             }
869         }
870         if (_query != null) { // has_query
871             buf.append('?');
872             buf.append(_query);
873         }
874         // ignore the fragment identifier
875         _uri = buf.toString().toCharArray();
876         hash = 0;
877     }
878     
879 }
880 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpVersion.html100644 0 0 55056 10661532627 25306 0ustar 0 0 HttpVersion xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpVersion.java,v 1.6 2004/12/20 19:52:50 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   *  <p>HTTP version, as specified in RFC 2616.</p>
35   *  <p>
36   *  HTTP uses a "&lt;major&gt;.&lt;minor&gt;" numbering scheme to indicate
37   *  versions of the protocol. The protocol versioning policy is intended to
38   *  allow the sender to indicate the format of a message and its capacity for
39   *  understanding further HTTP communication, rather than the features
40   *  obtained via that communication. No change is made to the version
41   *  number for the addition of message components which do not affect
42   *  communication behavior or which only add to extensible field values.
43   *  The &lt;minor&gt; number is incremented when the changes made to the
44   *  protocol add features which do not change the general message parsing
45   *  algorithm, but which may add to the message semantics and imply
46   *  additional capabilities of the sender. The &lt;major&gt; number is
47   *  incremented when the format of a message within the protocol is
48   *  changed. See RFC 2145 [36] for a fuller explanation.
49   *  </p>
50   *  <p>
51   *  The version of an HTTP message is indicated by an HTTP-Version field
52   *  in the first line of the message.
53   *  </p>
54   *  <pre>
55   *     HTTP-Version   = "HTTP" "/" 1*DIGIT "." 1*DIGIT
56   *  </pre>
57   *  <p>
58   *   Note that the major and minor numbers MUST be treated as separate
59   *   integers and that each MAY be incremented higher than a single digit.
60   *   Thus, HTTP/2.4 is a lower version than HTTP/2.13, which in turn is
61   *   lower than HTTP/12.3. Leading zeros MUST be ignored by recipients and
62   *   MUST NOT be sent.
63   *  </p>
64   * 
65   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
66   * 
67   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
68   *
69   * @since 3.0
70   */
71  public class HttpVersion implements Comparable {
72  
73      /** Major version number of the HTTP protocol */
74      private int major = 0;
75  
76      /** Minor version number of the HTTP protocol */
77      private int minor = 0;
78  
79      /** HTTP protocol version 0.9 */
80      public static final HttpVersion HTTP_0_9 = new HttpVersion(0, 9);  
81  
82      /** HTTP protocol version 1.0 */
83      public static final HttpVersion HTTP_1_0 = new HttpVersion(1, 0);  
84  
85      /** HTTP protocol version 1.1 */
86      public static final HttpVersion HTTP_1_1 = new HttpVersion(1, 1);  
87      
88      /**
89       * Create an HTTP protocol version designator.
90       *
91       * @param major   the major version number of the HTTP protocol
92       * @param minor   the minor version number of the HTTP protocol
93       * 
94       * @throws IllegalArgumentException if either major or minor version number is negative
95       */
96      public HttpVersion(int major, int minor) {
97          if (major < 0) {
98              throw new IllegalArgumentException("HTTP major version number may not be negative");
99          }
100         this.major = major;
101         if (minor < 0) {
102             throw new IllegalArgumentException("HTTP minor version number may not be negative");
103         }
104         this.minor = minor;
105     }
106     
107     /**
108      * Returns the major version number of the HTTP protocol.
109      * 
110      * @return the major version number.
111      */
112     public int getMajor() {
113         return major;
114     }
115 
116     /**
117      * Returns the minor version number of the HTTP protocol.
118      * 
119      * @return the minor version number.
120      */
121     public int getMinor() {
122         return minor;
123     }
124 
125     /**
126      * @see java.lang.Object#hashCode()
127      */
128     public int hashCode() {
129         return this.major * 100000 + this.minor;
130     }
131         
132     /**
133      * @see java.lang.Object#equals(java.lang.Object)
134      */
135     public boolean equals(Object obj) {
136         if (this == obj) {
137             return true;
138         }
139         if (!(obj instanceof HttpVersion)) {
140             return false;
141         }
142         return equals((HttpVersion)obj);  
143     }
144 
145     /**
146      * Compares this HTTP protocol version with another one.
147      * 
148      * @param anotherVer the version to be compared with.
149      *  
150      * @return a negative integer, zero, or a positive integer as this version is less than, 
151      *    equal to, or greater than the specified version.     
152      */
153     public int compareTo(HttpVersion anotherVer) {
154         if (anotherVer == null) {
155             throw new IllegalArgumentException("Version parameter may not be null"); 
156         }
157         int delta = getMajor() - anotherVer.getMajor();
158         if (delta == 0) {
159             delta = getMinor() - anotherVer.getMinor();
160         }
161         return delta;
162     }
163 
164     /**
165      * @see java.lang.Comparable#compareTo(java.lang.Object)
166      */
167     public int compareTo(Object o) {
168         return compareTo((HttpVersion)o);
169     }
170 
171     /**
172      * Test if the HTTP protocol version is equal to the given number.
173      * 
174      * @return <tt>true</tt> if HTTP protocol version is given to the given number, 
175      *         <tt>false</tt> otherwise.
176      */
177     public boolean equals(HttpVersion version) {
178         return compareTo(version) == 0;  
179     }
180 
181     /**
182      * Test if the HTTP protocol version is greater or equal to the given number.
183      * 
184      * @return <tt>true</tt> if HTTP protocol version is greater or equal given to the 
185      *         given number, <tt>false</tt> otherwise.
186      */
187     public boolean greaterEquals(HttpVersion version) {
188         return compareTo(version) >= 0;
189     }
190 
191     /**
192      * Test if the HTTP protocol version is less or equal to the given number.
193      * 
194      * @return <tt>true</tt> if HTTP protocol version is less or equal to given to the 
195      *         given number, <tt>false</tt> otherwise.
196      */
197     public boolean lessEquals(HttpVersion version) {
198         return compareTo(version) <= 0;
199     }
200 
201     /**
202      * @see java.lang.Object#toString()
203      */
204     public String toString() {
205         StringBuffer buffer = new StringBuffer();
206         buffer.append("HTTP/"); 
207         buffer.append(this.major); 
208         buffer.append('.'); 
209         buffer.append(this.minor); 
210         return buffer.toString();
211     }
212 
213     /**
214      * Parses the textual representation of the given HTTP protocol version.
215      * 
216      * @return HTTP protocol version.
217      * 
218      * @throws ProtocolException if the string is not a valid HTTP protocol version. 
219      */
220     public static HttpVersion parse(final String s) throws ProtocolException {
221         if (s == null) {
222             throw new IllegalArgumentException("String may not be null");
223         }
224         if (!s.startsWith("HTTP/")) {
225             throw new ProtocolException("Invalid HTTP version string: " + s);
226         }
227         int major, minor;
228         
229         int i1 = "HTTP/".length();
230         int i2 = s.indexOf(".", i1);
231         if (i2 == -1) {
232             throw new ProtocolException("Invalid HTTP version number: " + s);
233         }
234         try {
235             major = Integer.parseInt(s.substring(i1, i2)); 
236         } catch (NumberFormatException e) {
237             throw new ProtocolException("Invalid HTTP major version number: " + s);
238         }
239         i1 = i2 + 1;
240         i2 = s.length();
241         try {
242             minor = Integer.parseInt(s.substring(i1, i2)); 
243         } catch (NumberFormatException e) {
244             throw new ProtocolException("Invalid HTTP minor version number: " + s);
245         }
246         return new HttpVersion(major, minor);
247     }
248 
249 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/HttpsURL.html100644 0 0 116145 10661532627 24523 0ustar 0 0 HttpsURL xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpsURL.java,v 1.11 2004/09/30 17:26:41 oglueck Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import org.apache.commons.httpclient.util.URIUtil;
34  
35  /**
36   * The HTTPS URL.
37   *
38   * @author <a href="mailto:jericho at apache.org">Sung-Gu</a>
39   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
40   */
41  public class HttpsURL extends HttpURL {
42  
43      // ----------------------------------------------------------- Constructors
44  
45      /**
46       * Create an instance as an internal use.
47       */
48      protected HttpsURL() {
49      }
50  
51  
52      /**
53       * Construct a HTTPS URL as an escaped form of a character array with the
54       * given charset to do escape encoding.
55       *
56       * @param escaped the HTTPS URL character sequence
57       * @param charset the charset to do escape encoding
58       * @throws URIException If {@link #checkValid()} fails
59       * @throws NullPointerException if <code>escaped</code> is <code>null</code>
60       * @see #getProtocolCharset
61       */
62      public HttpsURL(char[] escaped, String charset)
63          throws URIException, NullPointerException {
64          protocolCharset = charset;
65          parseUriReference(new String(escaped), true);
66          checkValid();
67      }
68  
69  
70      /**
71       * Construct a HTTPS URL as an escaped form of a character array.
72       *
73       * @param escaped the HTTPS URL character sequence
74       * @throws URIException If {@link #checkValid()} fails
75       * @throws NullPointerException if <code>escaped</code> is <code>null</code>
76       * @see #getDefaultProtocolCharset
77       */
78      public HttpsURL(char[] escaped) throws URIException, NullPointerException {
79          parseUriReference(new String(escaped), true);
80          checkValid();
81      }
82  
83  
84      /**
85       * Construct a HTTPS URL from a given string with the given charset to do
86       * escape encoding.
87       *
88       * @param original the HTTPS URL string
89       * @param charset the charset to do escape encoding
90       * @throws URIException If {@link #checkValid()} fails
91       * @see #getProtocolCharset
92       */
93      public HttpsURL(String original, String charset) throws URIException {
94          protocolCharset = charset;
95          parseUriReference(original, false);
96          checkValid();
97      }
98  
99  
100     /**
101      * Construct a HTTPS URL from a given string.
102      *
103      * @param original the HTTPS URL string
104      * @throws URIException If {@link #checkValid()} fails
105      * @see #getDefaultProtocolCharset
106      */
107     public HttpsURL(String original) throws URIException {
108         parseUriReference(original, false);
109         checkValid();
110     }
111 
112 
113     /**
114      * Construct a HTTPS URL from given components.
115      *
116      * @param host the host string
117      * @param port the port number
118      * @param path the path string
119      * @throws URIException If {@link #checkValid()} fails
120      * @see #getDefaultProtocolCharset
121      */
122     public HttpsURL(String host, int port, String path) throws URIException {
123         this(null, host, port, path, null, null);
124     }
125 
126 
127     /**
128      * Construct a HTTPS URL from given components.
129      *
130      * @param host the host string
131      * @param port the port number
132      * @param path the path string
133      * @param query the query string
134      * @throws URIException If {@link #checkValid()} fails
135      * @see #getDefaultProtocolCharset
136      */
137     public HttpsURL(String host, int port, String path, String query)
138         throws URIException {
139 
140         this(null, host, port, path, query, null);
141     }
142 
143 
144     /**
145      * Construct a HTTPS URL from given components.
146      *
147      * @param user the user name
148      * @param password his or her password
149      * @param host the host string
150      * @throws URIException If {@link #checkValid()} fails
151      * @see #getDefaultProtocolCharset
152      */
153     public HttpsURL(String user, String password, String host)
154         throws URIException {
155 
156         this(user, password, host, -1, null, null, null);
157     }
158 
159 
160     /**
161      * Construct a HTTPS URL from given components.
162      *
163      * @param user the user name
164      * @param password his or her password
165      * @param host the host string
166      * @param port the port number
167      * @throws URIException If {@link #checkValid()} fails
168      * @see #getDefaultProtocolCharset
169      */
170     public HttpsURL(String user, String password, String host, int port)
171         throws URIException {
172 
173         this(user, password, host, port, null, null, null);
174     }
175 
176 
177     /**
178      * Construct a HTTPS URL from given components.
179      *
180      * @param user the user name
181      * @param password his or her password
182      * @param host the host string
183      * @param port the port number
184      * @param path the path string
185      * @throws URIException If {@link #checkValid()} fails
186      * @see #getDefaultProtocolCharset
187      */
188     public HttpsURL(String user, String password, String host, int port,
189             String path) throws URIException {
190 
191         this(user, password, host, port, path, null, null);
192     }
193 
194 
195     /**
196      * Construct a HTTPS URL from given components.
197      *
198      * @param user the user name
199      * @param password his or her password
200      * @param host the host string
201      * @param port the port number
202      * @param path the path string
203      * @param query The query string.
204      * @throws URIException If {@link #checkValid()} fails
205      * @see #getDefaultProtocolCharset
206      */
207     public HttpsURL(String user, String password, String host, int port,
208             String path, String query) throws URIException {
209 
210         this(user, password, host, port, path, query, null);
211     }
212 
213 
214     /**
215      * Construct a HTTPS URL from given components.
216      *
217      * @param host the host string
218      * @param path the path string
219      * @param query the query string
220      * @param fragment the fragment string
221      * @throws URIException If {@link #checkValid()} fails
222      * @see #getDefaultProtocolCharset
223      */
224     public HttpsURL(String host, String path, String query, String fragment)
225         throws URIException {
226 
227         this(null, host, -1, path, query, fragment);
228     }
229 
230 
231     /**
232      * Construct a HTTPS URL from given components.
233      *
234      * Note: The <code>userinfo</code> format is normally
235      * <code>&lt;username&gt;:&lt;password&gt;</code> where
236      * username and password must both be URL escaped.
237      *  
238      * @param userinfo the userinfo string whose parts are URL escaped
239      * @param host the host string
240      * @param path the path string
241      * @param query the query string
242      * @param fragment the fragment string
243      * @throws URIException If {@link #checkValid()} fails
244      * @see #getDefaultProtocolCharset
245      */
246     public HttpsURL(String userinfo, String host, String path, String query,
247             String fragment) throws URIException {
248 
249         this(userinfo, host, -1, path, query, fragment);
250     }
251 
252 
253     /**
254      * Construct a HTTPS URL from given components.
255      *
256      * Note: The <code>userinfo</code> format is normally
257      * <code>&lt;username&gt;:&lt;password&gt;</code> where
258      * username and password must both be URL escaped.
259      *  
260      * @param userinfo the userinfo string whose parts are URL escaped
261      * @param host the host string
262      * @param port the port number
263      * @param path the path string
264      * @throws URIException If {@link #checkValid()} fails
265      * @see #getDefaultProtocolCharset
266      */
267     public HttpsURL(String userinfo, String host, int port, String path)
268         throws URIException {
269 
270         this(userinfo, host, port, path, null, null);
271     }
272 
273 
274     /**
275      * Construct a HTTPS URL from given components.
276      *
277      * Note: The <code>userinfo</code> format is normally
278      * <code>&lt;username&gt;:&lt;password&gt;</code> where
279      * username and password must both be URL escaped.
280      *  
281      * @param userinfo the userinfo string whose parts are URL escaped
282      * @param host the host string
283      * @param port the port number
284      * @param path the path string
285      * @param query the query string
286      * @throws URIException If {@link #checkValid()} fails
287      * @see #getDefaultProtocolCharset
288      */
289     public HttpsURL(String userinfo, String host, int port, String path,
290             String query) throws URIException {
291 
292         this(userinfo, host, port, path, query, null);
293     }
294 
295 
296     /**
297      * Construct a HTTPS URL from given components.
298      *
299      * Note: The <code>userinfo</code> format is normally
300      * <code>&lt;username&gt;:&lt;password&gt;</code> where
301      * username and password must both be URL escaped.
302      *  
303      * @param userinfo the userinfo string whose parts are URL escaped
304      * @param host the host string
305      * @param port the port number
306      * @param path the path string
307      * @param query the query string
308      * @param fragment the fragment string
309      * @throws URIException If {@link #checkValid()} fails
310      * @see #getDefaultProtocolCharset
311      */
312     public HttpsURL(String userinfo, String host, int port, String path,
313             String query, String fragment) throws URIException {
314 
315         // validate and contruct the URI character sequence
316         StringBuffer buff = new StringBuffer();
317         if (userinfo != null || host != null || port != -1) {
318             _scheme = DEFAULT_SCHEME; // in order to verify the own protocol
319             buff.append(_default_scheme);
320             buff.append("://");
321             if (userinfo != null) {
322                 buff.append(userinfo);
323                 buff.append('@');
324             }
325             if (host != null) {
326                 buff.append(URIUtil.encode(host, URI.allowed_host));
327                 if (port != -1 || port != DEFAULT_PORT) {
328                     buff.append(':');
329                     buff.append(port);
330                 }
331             }
332         }
333         if (path != null) {  // accept empty path
334             if (scheme != null && !path.startsWith("/")) {
335                 throw new URIException(URIException.PARSING,
336                         "abs_path requested");
337             }
338             buff.append(URIUtil.encode(path, URI.allowed_abs_path));
339         }
340         if (query != null) {
341             buff.append('?');
342             buff.append(URIUtil.encode(query, URI.allowed_query));
343         }
344         if (fragment != null) {
345             buff.append('#');
346             buff.append(URIUtil.encode(fragment, URI.allowed_fragment));
347         }
348         parseUriReference(buff.toString(), true);
349         checkValid();
350     }
351 
352     /**
353      * Construct a HTTP URL from given components.
354      *
355      * @param user the user name
356      * @param password his or her password
357      * @param host the host string
358      * @param port the port number
359      * @param path the path string
360      * @param query the query string
361      * @param fragment the fragment string
362      * @throws URIException If {@link #checkValid()} fails
363      * @see #getDefaultProtocolCharset
364      */
365     public HttpsURL(String user, String password, String host, int port,
366             String path, String query, String fragment) throws URIException {
367         this(HttpURL.toUserinfo(user, password), host, port, path, query, fragment);
368     }    
369 
370     /**
371      * Construct a HTTPS URL with a given relative HTTPS URL string.
372      *
373      * @param base the base HttpsURL
374      * @param relative the relative HTTPS URL string
375      * @throws URIException If {@link #checkValid()} fails
376      */
377     public HttpsURL(HttpsURL base, String relative) throws URIException {
378         this(base, new HttpsURL(relative));
379     }
380 
381 
382     /**
383      * Construct a HTTPS URL with a given relative URL.
384      *
385      * @param base the base HttpsURL
386      * @param relative the relative HttpsURL
387      * @throws URIException If {@link #checkValid()} fails
388      */
389     public HttpsURL(HttpsURL base, HttpsURL relative) throws URIException {
390         super(base, relative);
391         checkValid();
392     }
393 
394     // -------------------------------------------------------------- Constants
395 
396     /**
397      * Default scheme for HTTPS URL.
398      */
399     public static final char[] DEFAULT_SCHEME = { 'h', 't', 't', 'p', 's' };
400     
401     /**
402      * Default scheme for HTTPS URL.
403      * @deprecated Use {@link #DEFAULT_SCHEME} instead.  This one doesn't
404      * conform to the project naming conventions.
405      */
406     public static final char[] _default_scheme = DEFAULT_SCHEME;
407 
408 
409     /**
410      * Default port for HTTPS URL.
411      */
412     public static final int DEFAULT_PORT = 443;
413 
414     /**
415      * Default port for HTTPS URL.
416      * @deprecated Use {@link #DEFAULT_PORT} instead.  This one doesn't conform
417      * to the project naming conventions.
418      */
419     public static final int _default_port = DEFAULT_PORT;
420 
421 
422     /**
423      * The serialVersionUID.
424      */
425     static final long serialVersionUID = 887844277028676648L;
426 
427     // ------------------------------------------------------------- The scheme
428 
429     /**
430      * Get the scheme.  You can get the scheme explicitly.
431      *
432      * @return the scheme
433      */
434     public char[] getRawScheme() {
435         return (_scheme == null) ? null : HttpsURL.DEFAULT_SCHEME;
436     }
437 
438 
439     /**
440      * Get the scheme.  You can get the scheme explicitly.
441      *
442      * @return the scheme null if empty or undefined
443      */
444     public String getScheme() {
445         return (_scheme == null) ? null : new String(HttpsURL.DEFAULT_SCHEME);
446     }
447 
448     // --------------------------------------------------------------- The port
449 
450     /**
451      * Get the port number.
452      * @return the port number
453      */
454     public int getPort() {
455         return (_port == -1) ? HttpsURL.DEFAULT_PORT : _port;
456     }    
457     
458     // ---------------------------------------------------------------- Utility
459 
460     /**
461      * Verify the valid class use for construction.
462      *
463      * @throws URIException the wrong scheme use
464      */
465     protected void checkValid() throws URIException {
466         // could be explicit protocol or undefined.
467         if (!(equals(_scheme, DEFAULT_SCHEME) || _scheme == null)) {
468             throw new URIException(URIException.PARSING, "wrong class use");
469         }
470     }
471 
472 }
473 

././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/InvalidRedirectLocationException.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/InvalidRedirectLocationException.html100644 0 0 16545 10661532627 31441 0ustar 0 0 InvalidRedirectLocationException xref

1   /*
2    * $HeadRL$
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * Signals violation of HTTP specification caused by an invalid redirect
35   * location
36   * 
37   * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
38   * 
39   * @since 3.1
40   */
41  public class InvalidRedirectLocationException extends RedirectException {
42  
43      private final String location;
44      
45      /**
46       * Creates a new InvalidRedirectLocationException with the specified detail message.
47       * 
48       * @param message the exception detail message
49       * @param location redirect location
50       */
51      public InvalidRedirectLocationException(final String message, final String location) {
52          super(message);
53          this.location = location;
54      }
55  
56      /**
57       * Creates a new RedirectException with the specified detail message and cause.
58       * 
59       * @param message the exception detail message
60       * @param location redirect location
61       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
62       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
63       */
64      public InvalidRedirectLocationException(final String message, final String location, 
65              final Throwable cause) {
66          super(message, cause);
67          this.location = location;
68      }
69      
70      public String getLocation() {
71          return this.location;
72      }
73      
74  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/MethodRetryHandler.html100644 0 0 15672 10661532627 26565 0ustar 0 0 MethodRetryHandler xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/MethodRetryHandler.java,v 1.5 2004/07/05 22:46:58 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * A handler for determining if an HttpMethod should be retried after a 
35   * recoverable exception during execution.
36   * 
37   * @see HttpMethod#execute(HttpState, HttpConnection)
38   * @see HttpRecoverableException
39   * 
40   * @deprecated use {@link HttpMethodRetryHandler}
41   * 
42   * @author Michael Becke
43   */
44  public interface MethodRetryHandler {
45  
46      /**
47       * Determines if a method should be retried after an HttpRecoverableException
48       * occurs during execution.
49       * 
50       * @param method the method being executed
51       * @param connection the connection the method is using
52       * @param recoverableException the exception that occurred
53       * @param executionCount the number of times this method has been 
54       * unsuccessfully executed
55       * @param requestSent this argument is unused and will be removed in the future. 
56       *   {@link HttpMethod#isRequestSent()} should be used instead
57       * 
58       * @return <code>true</code> if the method should be retried, <code>false</code>
59       * otherwise
60       */
61      boolean retryMethod(
62          HttpMethod method, 
63          HttpConnection connection,
64          HttpRecoverableException recoverableException,
65          int executionCount,
66          boolean requestSent);
67  
68  }

././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.ht100644 0 0 436462 10661532627 31422 0ustar 0 0 MultiThreadedHttpConnectionManager xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.java,v 1.47 2004/12/21 11:27:55 olegk Exp $
3    * $Revision: 564906 $
4    * $Date: 2007-08-11 14:27:18 +0200 (Sat, 11 Aug 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.io.OutputStream;
36  import java.lang.ref.Reference;
37  import java.lang.ref.ReferenceQueue;
38  import java.lang.ref.WeakReference;
39  import java.net.InetAddress;
40  import java.net.SocketException;
41  import java.util.ArrayList;
42  import java.util.HashMap;
43  import java.util.Iterator;
44  import java.util.LinkedList;
45  import java.util.Map;
46  import java.util.WeakHashMap;
47  
48  import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
49  import org.apache.commons.httpclient.params.HttpConnectionParams;
50  import org.apache.commons.httpclient.protocol.Protocol;
51  import org.apache.commons.httpclient.util.IdleConnectionHandler;
52  import org.apache.commons.logging.Log;
53  import org.apache.commons.logging.LogFactory;
54  
55  /**
56   * Manages a set of HttpConnections for various HostConfigurations.
57   *
58   * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
59   * @author Eric Johnson
60   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
61   * @author Carl A. Dunham
62   *
63   * @since 2.0
64   */
65  public class MultiThreadedHttpConnectionManager implements HttpConnectionManager {
66  
67      // -------------------------------------------------------- Class Variables
68  
69      /** Log object for this class. */
70      private static final Log LOG = LogFactory.getLog(MultiThreadedHttpConnectionManager.class);
71  
72      /** The default maximum number of connections allowed per host */
73      public static final int DEFAULT_MAX_HOST_CONNECTIONS = 2;   // Per RFC 2616 sec 8.1.4
74  
75      /** The default maximum number of connections allowed overall */
76      public static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 20;
77  
78      /**
79       * A mapping from Reference to ConnectionSource.  Used to reclaim resources when connections
80       * are lost to the garbage collector.
81       */
82      private static final Map REFERENCE_TO_CONNECTION_SOURCE = new HashMap();
83      
84      /**
85       * The reference queue used to track when HttpConnections are lost to the
86       * garbage collector
87       */
88      private static final ReferenceQueue REFERENCE_QUEUE = new ReferenceQueue();    
89  
90      /**
91       * The thread responsible for handling lost connections.
92       */
93      private static ReferenceQueueThread REFERENCE_QUEUE_THREAD;
94      
95      /**
96       * Holds references to all active instances of this class.
97       */    
98      private static WeakHashMap ALL_CONNECTION_MANAGERS = new WeakHashMap();
99      
100 
101     // ---------------------------------------------------------- Class Methods
102 
103     /**
104      * Shuts down and cleans up resources used by all instances of 
105      * MultiThreadedHttpConnectionManager. All static resources are released, all threads are 
106      * stopped, and {@link #shutdown()} is called on all live instances of 
107      * MultiThreadedHttpConnectionManager.
108      *
109      * @see #shutdown()
110      */
111     public static void shutdownAll() {
112 
113         synchronized (REFERENCE_TO_CONNECTION_SOURCE) {
114             // shutdown all connection managers
115             synchronized (ALL_CONNECTION_MANAGERS) {
116                 // Don't use an iterator here. Iterators on WeakHashMap can
117                 // get ConcurrentModificationException on garbage collection.
118                 MultiThreadedHttpConnectionManager[]
119                     connManagers = (MultiThreadedHttpConnectionManager[])
120                     ALL_CONNECTION_MANAGERS.keySet().toArray(
121                         new MultiThreadedHttpConnectionManager
122                             [ALL_CONNECTION_MANAGERS.size()]
123                         );
124 
125                 // The map may shrink after size() is called, or some entry
126                 // may get GCed while the array is built, so expect null.
127                 for (int i=0; i<connManagers.length; i++) {
128                     if (connManagers[i] != null)
129                         connManagers[i].shutdown();
130                 }
131             }
132             
133             // shutdown static resources
134             if (REFERENCE_QUEUE_THREAD != null) {
135                 REFERENCE_QUEUE_THREAD.shutdown();
136                 REFERENCE_QUEUE_THREAD = null;
137             }
138             REFERENCE_TO_CONNECTION_SOURCE.clear();
139         }        
140     }    
141     
142     /**
143      * Stores the reference to the given connection along with the host config and connection pool.  
144      * These values will be used to reclaim resources if the connection is lost to the garbage 
145      * collector.  This method should be called before a connection is released from the connection 
146      * manager.
147      * 
148      * <p>A static reference to the connection manager will also be stored.  To ensure that
149      * the connection manager can be GCed {@link #removeReferenceToConnection(HttpConnection)}
150      * should be called for all connections that the connection manager is storing a reference
151      * to.</p>
152      * 
153      * @param connection the connection to create a reference for
154      * @param hostConfiguration the connection's host config
155      * @param connectionPool the connection pool that created the connection
156      * 
157      * @see #removeReferenceToConnection(HttpConnection)
158      */
159     private static void storeReferenceToConnection(
160         HttpConnectionWithReference connection,
161         HostConfiguration hostConfiguration,
162         ConnectionPool connectionPool
163     ) {
164         
165         ConnectionSource source = new ConnectionSource();
166         source.connectionPool = connectionPool;
167         source.hostConfiguration = hostConfiguration;
168         
169         synchronized (REFERENCE_TO_CONNECTION_SOURCE) {
170             
171             // start the reference queue thread if needed
172             if (REFERENCE_QUEUE_THREAD == null) {
173                 REFERENCE_QUEUE_THREAD = new ReferenceQueueThread();
174                 REFERENCE_QUEUE_THREAD.start();
175             }
176             
177             REFERENCE_TO_CONNECTION_SOURCE.put(
178                 connection.reference,
179                 source
180             );
181         }
182     }
183     
184     /**
185      * Closes and releases all connections currently checked out of the given connection pool.
186      * @param connectionPool the connection pool to shutdown the connections for
187      */
188     private static void shutdownCheckedOutConnections(ConnectionPool connectionPool) {
189 
190         // keep a list of the connections to be closed
191         ArrayList connectionsToClose = new ArrayList(); 
192         
193         synchronized (REFERENCE_TO_CONNECTION_SOURCE) {
194             
195             Iterator referenceIter = REFERENCE_TO_CONNECTION_SOURCE.keySet().iterator();
196             while (referenceIter.hasNext()) {
197                 Reference ref = (Reference) referenceIter.next();
198                 ConnectionSource source = 
199                     (ConnectionSource) REFERENCE_TO_CONNECTION_SOURCE.get(ref);
200                 if (source.connectionPool == connectionPool) {
201                     referenceIter.remove();
202                     HttpConnection connection = (HttpConnection) ref.get();
203                     if (connection != null) {
204                         connectionsToClose.add(connection);
205                     }
206                 }
207             }
208         }
209 
210         // close and release the connections outside of the synchronized block to
211         // avoid holding the lock for too long
212         for (Iterator i = connectionsToClose.iterator(); i.hasNext();) {
213             HttpConnection connection = (HttpConnection) i.next();
214             connection.close();
215             // remove the reference to the connection manager. this ensures
216             // that the we don't accidentally end up here again
217             connection.setHttpConnectionManager(null);
218             connection.releaseConnection();
219         }
220     }
221     
222     /**
223      * Removes the reference being stored for the given connection.  This method should be called
224      * when the connection manager again has a direct reference to the connection.
225      * 
226      * @param connection the connection to remove the reference for
227      * 
228      * @see #storeReferenceToConnection(HttpConnection, HostConfiguration, ConnectionPool)
229      */
230     private static void removeReferenceToConnection(HttpConnectionWithReference connection) {
231         
232         synchronized (REFERENCE_TO_CONNECTION_SOURCE) {
233             REFERENCE_TO_CONNECTION_SOURCE.remove(connection.reference);
234         }
235     }    
236     
237 
238     // ----------------------------------------------------- Instance Variables
239 
240     /**
241      * Collection of parameters associated with this connection manager.
242      */
243     private HttpConnectionManagerParams params = new HttpConnectionManagerParams(); 
244 
245     /** Connection Pool */
246     private ConnectionPool connectionPool;
247 
248     private volatile boolean shutdown = false;
249     
250 
251     // ----------------------------------------------------------- Constructors
252 
253     /**
254      * No-args constructor
255      */
256     public MultiThreadedHttpConnectionManager() {
257         this.connectionPool = new ConnectionPool();
258         synchronized(ALL_CONNECTION_MANAGERS) {
259             ALL_CONNECTION_MANAGERS.put(this, null);
260         }
261     }
262 
263 
264     // ------------------------------------------------------- Instance Methods
265 
266     /**
267      * Shuts down the connection manager and releases all resources.  All connections associated 
268      * with this class will be closed and released. 
269      * 
270      * <p>The connection manager can no longer be used once shut down.  
271      * 
272      * <p>Calling this method more than once will have no effect.
273      */
274     public synchronized void shutdown() {
275         synchronized (connectionPool) {
276             if (!shutdown) {
277                 shutdown = true;
278                 connectionPool.shutdown();
279             }
280         }
281     }
282     
283     /**
284      * Gets the staleCheckingEnabled value to be set on HttpConnections that are created.
285      * 
286      * @return <code>true</code> if stale checking will be enabled on HttpConnections
287      * 
288      * @see HttpConnection#isStaleCheckingEnabled()
289      * 
290      * @deprecated Use {@link HttpConnectionManagerParams#isStaleCheckingEnabled()},
291      * {@link HttpConnectionManager#getParams()}.
292      */
293     public boolean isConnectionStaleCheckingEnabled() {
294         return this.params.isStaleCheckingEnabled();
295     }
296 
297     /**
298      * Sets the staleCheckingEnabled value to be set on HttpConnections that are created.
299      * 
300      * @param connectionStaleCheckingEnabled <code>true</code> if stale checking will be enabled 
301      * on HttpConnections
302      * 
303      * @see HttpConnection#setStaleCheckingEnabled(boolean)
304      * 
305      * @deprecated Use {@link HttpConnectionManagerParams#setStaleCheckingEnabled(boolean)},
306      * {@link HttpConnectionManager#getParams()}.
307      */
308     public void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled) {
309         this.params.setStaleCheckingEnabled(connectionStaleCheckingEnabled);
310     }
311 
312     /**
313      * Sets the maximum number of connections allowed for a given
314      * HostConfiguration. Per RFC 2616 section 8.1.4, this value defaults to 2.
315      *
316      * @param maxHostConnections the number of connections allowed for each
317      * hostConfiguration
318      * 
319      * @deprecated Use {@link HttpConnectionManagerParams#setDefaultMaxConnectionsPerHost(int)},
320      * {@link HttpConnectionManager#getParams()}.
321      */
322     public void setMaxConnectionsPerHost(int maxHostConnections) {
323         this.params.setDefaultMaxConnectionsPerHost(maxHostConnections);
324     }
325 
326     /**
327      * Gets the maximum number of connections allowed for a given
328      * hostConfiguration.
329      *
330      * @return The maximum number of connections allowed for a given
331      * hostConfiguration.
332      * 
333      * @deprecated Use {@link HttpConnectionManagerParams#getDefaultMaxConnectionsPerHost()},
334      * {@link HttpConnectionManager#getParams()}.
335      */
336     public int getMaxConnectionsPerHost() {
337         return this.params.getDefaultMaxConnectionsPerHost();
338     }
339 
340     /**
341      * Sets the maximum number of connections allowed for this connection manager.
342      *
343      * @param maxTotalConnections the maximum number of connections allowed
344      * 
345      * @deprecated Use {@link HttpConnectionManagerParams#setMaxTotalConnections(int)},
346      * {@link HttpConnectionManager#getParams()}.
347      */
348     public void setMaxTotalConnections(int maxTotalConnections) {
349         this.params.setMaxTotalConnections(maxTotalConnections);
350     }
351 
352     /**
353      * Gets the maximum number of connections allowed for this connection manager.
354      *
355      * @return The maximum number of connections allowed
356      * 
357      * @deprecated Use {@link HttpConnectionManagerParams#getMaxTotalConnections()},
358      * {@link HttpConnectionManager#getParams()}.
359      */
360     public int getMaxTotalConnections() {
361         return this.params.getMaxTotalConnections();
362     }
363 
364     /**
365      * @see HttpConnectionManager#getConnection(HostConfiguration)
366      */
367     public HttpConnection getConnection(HostConfiguration hostConfiguration) {
368 
369         while (true) {
370             try {
371                 return getConnectionWithTimeout(hostConfiguration, 0);
372             } catch (ConnectionPoolTimeoutException e) {
373                 // we'll go ahead and log this, but it should never happen. HttpExceptions
374                 // are only thrown when the timeout occurs and since we have no timeout
375                 // it should never happen.
376                 LOG.debug(
377                     "Unexpected exception while waiting for connection",
378                     e
379                 );
380             }
381         }
382     }
383 
384     /**
385      * Gets a connection or waits if one is not available.  A connection is
386      * available if one exists that is not being used or if fewer than
387      * maxHostConnections have been created in the connectionPool, and fewer
388      * than maxTotalConnections have been created in all connectionPools.
389      *
390      * @param hostConfiguration The host configuration specifying the connection
391      *        details.
392      * @param timeout the number of milliseconds to wait for a connection, 0 to
393      * wait indefinitely
394      *
395      * @return HttpConnection an available connection
396      *
397      * @throws HttpException if a connection does not become available in
398      * 'timeout' milliseconds
399      * 
400      * @since 3.0
401      */
402     public HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration, 
403         long timeout) throws ConnectionPoolTimeoutException {
404 
405         LOG.trace("enter HttpConnectionManager.getConnectionWithTimeout(HostConfiguration, long)");
406 
407         if (hostConfiguration == null) {
408             throw new IllegalArgumentException("hostConfiguration is null");
409         }
410 
411         if (LOG.isDebugEnabled()) {
412             LOG.debug("HttpConnectionManager.getConnection:  config = "
413                 + hostConfiguration + ", timeout = " + timeout);
414         }
415 
416         final HttpConnection conn = doGetConnection(hostConfiguration, timeout);
417 
418         // wrap the connection in an adapter so we can ensure it is used 
419         // only once
420         return new HttpConnectionAdapter(conn);
421     }
422 
423 	/**
424 	 * @see HttpConnectionManager#getConnection(HostConfiguration, long)
425 	 * 
426 	 * @deprecated Use #getConnectionWithTimeout(HostConfiguration, long)
427 	 */
428 	public HttpConnection getConnection(HostConfiguration hostConfiguration, 
429 		long timeout) throws HttpException {
430 
431 		LOG.trace("enter HttpConnectionManager.getConnection(HostConfiguration, long)");
432 		try {
433 			return getConnectionWithTimeout(hostConfiguration, timeout);
434 		} catch(ConnectionPoolTimeoutException e) {
435 			throw new HttpException(e.getMessage());
436 		}
437 	}
438 
439     private HttpConnection doGetConnection(HostConfiguration hostConfiguration, 
440         long timeout) throws ConnectionPoolTimeoutException {
441 
442         HttpConnection connection = null;
443 
444         int maxHostConnections = this.params.getMaxConnectionsPerHost(hostConfiguration);
445         int maxTotalConnections = this.params.getMaxTotalConnections();
446         
447         synchronized (connectionPool) {
448 
449             // we clone the hostConfiguration
450             // so that it cannot be changed once the connection has been retrieved
451             hostConfiguration = new HostConfiguration(hostConfiguration);
452             HostConnectionPool hostPool = connectionPool.getHostPool(hostConfiguration, true);
453             WaitingThread waitingThread = null;
454 
455             boolean useTimeout = (timeout > 0);
456             long timeToWait = timeout;
457             long startWait = 0;
458             long endWait = 0;
459 
460             while (connection == null) {
461 
462                 if (shutdown) {
463                     throw new IllegalStateException("Connection factory has been shutdown.");
464                 }
465                 
466                 // happen to have a free connection with the right specs
467                 //
468                 if (hostPool.freeConnections.size() > 0) {
469                     connection = connectionPool.getFreeConnection(hostConfiguration);
470 
471                 // have room to make more
472                 //
473                 } else if ((hostPool.numConnections < maxHostConnections) 
474                     && (connectionPool.numConnections < maxTotalConnections)) {
475 
476                     connection = connectionPool.createConnection(hostConfiguration);
477 
478                 // have room to add host connection, and there is at least one free
479                 // connection that can be liberated to make overall room
480                 //
481                 } else if ((hostPool.numConnections < maxHostConnections) 
482                     && (connectionPool.freeConnections.size() > 0)) {
483 
484                     connectionPool.deleteLeastUsedConnection();
485                     connection = connectionPool.createConnection(hostConfiguration);
486 
487                 // otherwise, we have to wait for one of the above conditions to
488                 // become true
489                 //
490                 } else {
491                     // TODO: keep track of which hostConfigurations have waiting
492                     // threads, so they avoid being sacrificed before necessary
493 
494                     try {
495                         
496                         if (useTimeout && timeToWait <= 0) {
497                             throw new ConnectionPoolTimeoutException("Timeout waiting for connection");
498                         }
499                         
500                         if (LOG.isDebugEnabled()) {
501                             LOG.debug("Unable to get a connection, waiting..., hostConfig=" + hostConfiguration);
502                         }
503                         
504                         if (waitingThread == null) {
505                             waitingThread = new WaitingThread();
506                             waitingThread.hostConnectionPool = hostPool;
507                             waitingThread.thread = Thread.currentThread();
508                         } else {
509                             waitingThread.interruptedByConnectionPool = false;
510                         }
511                                     
512                         if (useTimeout) {
513                             startWait = System.currentTimeMillis();
514                         }
515                         
516                         hostPool.waitingThreads.addLast(waitingThread);
517                         connectionPool.waitingThreads.addLast(waitingThread);
518                         connectionPool.wait(timeToWait);
519                     } catch (InterruptedException e) {
520                         if (!waitingThread.interruptedByConnectionPool) {
521                             LOG.debug("Interrupted while waiting for connection", e);
522                             throw new IllegalThreadStateException(
523                                 "Interrupted while waiting in MultiThreadedHttpConnectionManager");
524                         }
525                         // Else, do nothing, we were interrupted by the connection pool
526                         // and should now have a connection waiting for us, continue
527                         // in the loop and let's get it.
528                     } finally {
529                         if (!waitingThread.interruptedByConnectionPool) {
530                             // Either we timed out, experienced a "spurious wakeup", or were
531                             // interrupted by an external thread.  Regardless we need to 
532                             // cleanup for ourselves in the wait queue.
533                             hostPool.waitingThreads.remove(waitingThread);
534                             connectionPool.waitingThreads.remove(waitingThread);
535                         }
536                         
537                         if (useTimeout) {
538                             endWait = System.currentTimeMillis();
539                             timeToWait -= (endWait - startWait);
540                         }
541                     }
542                 }
543             }
544         }
545         return connection;
546     }
547 
548     /**
549      * Gets the total number of pooled connections for the given host configuration.  This 
550      * is the total number of connections that have been created and are still in use 
551      * by this connection manager for the host configuration.  This value will
552      * not exceed the {@link #getMaxConnectionsPerHost() maximum number of connections per
553      * host}.
554      * 
555      * @param hostConfiguration The host configuration
556      * @return The total number of pooled connections
557      */
558     public int getConnectionsInPool(HostConfiguration hostConfiguration) {
559         synchronized (connectionPool) {
560             HostConnectionPool hostPool = connectionPool.getHostPool(hostConfiguration, false);
561             return (hostPool != null) ? hostPool.numConnections : 0;
562         }
563     }
564 
565     /**
566      * Gets the total number of pooled connections.  This is the total number of 
567      * connections that have been created and are still in use by this connection 
568      * manager.  This value will not exceed the {@link #getMaxTotalConnections() 
569      * maximum number of connections}.
570      * 
571      * @return the total number of pooled connections
572      */
573     public int getConnectionsInPool() {
574         synchronized (connectionPool) {
575             return connectionPool.numConnections;
576         }
577     }
578     
579     /**
580      * Gets the number of connections in use for this configuration.
581      *
582      * @param hostConfiguration the key that connections are tracked on
583      * @return the number of connections in use
584      * 
585      * @deprecated Use {@link #getConnectionsInPool(HostConfiguration)}
586      */
587     public int getConnectionsInUse(HostConfiguration hostConfiguration) {
588         return getConnectionsInPool(hostConfiguration);
589     }
590 
591     /**
592      * Gets the total number of connections in use.
593      * 
594      * @return the total number of connections in use
595      * 
596      * @deprecated Use {@link #getConnectionsInPool()}
597      */
598     public int getConnectionsInUse() {
599         return getConnectionsInPool();
600     }
601 
602     /**
603      * Deletes all closed connections.  Only connections currently owned by the connection
604      * manager are processed.
605      * 
606      * @see HttpConnection#isOpen()
607      * 
608      * @since 3.0
609      */
610     public void deleteClosedConnections() {
611         connectionPool.deleteClosedConnections();
612     }
613     
614     /**
615      * @since 3.0
616      */
617     public void closeIdleConnections(long idleTimeout) {
618         connectionPool.closeIdleConnections(idleTimeout);
619         deleteClosedConnections();
620     }
621     
622     /**
623      * Make the given HttpConnection available for use by other requests.
624      * If another thread is blocked in getConnection() that could use this
625      * connection, it will be woken up.
626      *
627      * @param conn the HttpConnection to make available.
628      */
629     public void releaseConnection(HttpConnection conn) {
630         LOG.trace("enter HttpConnectionManager.releaseConnection(HttpConnection)");
631 
632         if (conn instanceof HttpConnectionAdapter) {
633             // connections given out are wrapped in an HttpConnectionAdapter
634             conn = ((HttpConnectionAdapter) conn).getWrappedConnection();
635         } else {
636             // this is okay, when an HttpConnectionAdapter is released
637             // is releases the real connection
638         }
639 
640         // make sure that the response has been read.
641         SimpleHttpConnectionManager.finishLastResponse(conn);
642 
643         connectionPool.freeConnection(conn);
644     }
645 
646     /**
647      * Gets the host configuration for a connection.
648      * @param conn the connection to get the configuration of
649      * @return a new HostConfiguration
650      */
651     private HostConfiguration configurationForConnection(HttpConnection conn) {
652 
653         HostConfiguration connectionConfiguration = new HostConfiguration();
654         
655         connectionConfiguration.setHost(
656             conn.getHost(), 
657             conn.getPort(), 
658             conn.getProtocol()
659         );
660         if (conn.getLocalAddress() != null) {
661             connectionConfiguration.setLocalAddress(conn.getLocalAddress());
662         }
663         if (conn.getProxyHost() != null) {
664             connectionConfiguration.setProxy(conn.getProxyHost(), conn.getProxyPort());
665         }
666 
667         return connectionConfiguration;
668     }
669 
670     /**
671      * Returns {@link HttpConnectionManagerParams parameters} associated 
672      * with this connection manager.
673      * 
674      * @since 3.0
675      * 
676      * @see HttpConnectionManagerParams
677      */
678     public HttpConnectionManagerParams getParams() {
679         return this.params;
680     }
681 
682     /**
683      * Assigns {@link HttpConnectionManagerParams parameters} for this 
684      * connection manager.
685      * 
686      * @since 3.0
687      * 
688      * @see HttpConnectionManagerParams
689      */
690     public void setParams(final HttpConnectionManagerParams params) {
691         if (params == null) {
692             throw new IllegalArgumentException("Parameters may not be null");
693         }
694         this.params = params;
695     }
696     
697     /**
698      * Global Connection Pool, including per-host pools
699      */
700     private class ConnectionPool {
701         
702         /** The list of free connections */
703         private LinkedList freeConnections = new LinkedList();
704 
705         /** The list of WaitingThreads waiting for a connection */
706         private LinkedList waitingThreads = new LinkedList();
707 
708         /**
709          * Map where keys are {@link HostConfiguration}s and values are {@link
710          * HostConnectionPool}s
711          */
712         private final Map mapHosts = new HashMap();
713 
714         private IdleConnectionHandler idleConnectionHandler = new IdleConnectionHandler();        
715         
716         /** The number of created connections */
717         private int numConnections = 0;
718 
719         /**
720          * Cleans up all connection pool resources.
721          */
722         public synchronized void shutdown() {
723             
724             // close all free connections
725             Iterator iter = freeConnections.iterator();
726             while (iter.hasNext()) {
727                 HttpConnection conn = (HttpConnection) iter.next();
728                 iter.remove();
729                 conn.close();
730             }
731             
732             // close all connections that have been checked out
733             shutdownCheckedOutConnections(this);
734             
735             // interrupt all waiting threads
736             iter = waitingThreads.iterator();
737             while (iter.hasNext()) {
738                 WaitingThread waiter = (WaitingThread) iter.next();
739                 iter.remove();
740                 waiter.interruptedByConnectionPool = true;
741                 waiter.thread.interrupt();
742             }
743             
744             // clear out map hosts
745             mapHosts.clear();
746             
747             // remove all references to connections
748             idleConnectionHandler.removeAll();
749         }
750         
751         /**
752          * Creates a new connection and returns it for use of the calling method.
753          *
754          * @param hostConfiguration the configuration for the connection
755          * @return a new connection or <code>null</code> if none are available
756          */
757         public synchronized HttpConnection createConnection(HostConfiguration hostConfiguration) {
758             HostConnectionPool hostPool = getHostPool(hostConfiguration, true);
759             if (LOG.isDebugEnabled()) {
760                 LOG.debug("Allocating new connection, hostConfig=" + hostConfiguration);
761             }
762             HttpConnectionWithReference connection = new HttpConnectionWithReference(
763                     hostConfiguration);
764             connection.getParams().setDefaults(MultiThreadedHttpConnectionManager.this.params);
765             connection.setHttpConnectionManager(MultiThreadedHttpConnectionManager.this);
766             numConnections++;
767             hostPool.numConnections++;
768     
769             // store a reference to this connection so that it can be cleaned up
770             // in the event it is not correctly released
771             storeReferenceToConnection(connection, hostConfiguration, this);
772             return connection;
773         }
774     
775         /**
776          * Handles cleaning up for a lost connection with the given config.  Decrements any 
777          * connection counts and notifies waiting threads, if appropriate.
778          * 
779          * @param config the host configuration of the connection that was lost
780          */
781         public synchronized void handleLostConnection(HostConfiguration config) {
782             HostConnectionPool hostPool = getHostPool(config, true);
783             hostPool.numConnections--;
784             if ((hostPool.numConnections == 0) &&
785                 hostPool.waitingThreads.isEmpty()) {
786 
787                 mapHosts.remove(config);
788             }
789             
790             numConnections--;
791             notifyWaitingThread(config);
792         }
793 
794         /**
795          * Get the pool (list) of connections available for the given hostConfig.
796          *
797          * @param hostConfiguration the configuraton for the connection pool
798          * @param create <code>true</code> to create a pool if not found,
799          *               <code>false</code> to return <code>null</code>
800          *
801          * @return a pool (list) of connections available for the given config,
802          *         or <code>null</code> if neither found nor created
803          */
804         public synchronized HostConnectionPool getHostPool(HostConfiguration hostConfiguration, boolean create) {
805             LOG.trace("enter HttpConnectionManager.ConnectionPool.getHostPool(HostConfiguration)");
806 
807             // Look for a list of connections for the given config
808             HostConnectionPool listConnections = (HostConnectionPool) 
809                 mapHosts.get(hostConfiguration);
810             if ((listConnections == null) && create) {
811                 // First time for this config
812                 listConnections = new HostConnectionPool();
813                 listConnections.hostConfiguration = hostConfiguration;
814                 mapHosts.put(hostConfiguration, listConnections);
815             }
816             
817             return listConnections;
818         }
819 
820         /**
821          * If available, get a free connection for this host
822          *
823          * @param hostConfiguration the configuraton for the connection pool
824          * @return an available connection for the given config
825          */
826         public synchronized HttpConnection getFreeConnection(HostConfiguration hostConfiguration) {
827 
828             HttpConnectionWithReference connection = null;
829             
830             HostConnectionPool hostPool = getHostPool(hostConfiguration, false);
831 
832             if ((hostPool != null) && (hostPool.freeConnections.size() > 0)) {
833                 connection = (HttpConnectionWithReference) hostPool.freeConnections.removeLast();
834                 freeConnections.remove(connection);
835                 // store a reference to this connection so that it can be cleaned up
836                 // in the event it is not correctly released
837                 storeReferenceToConnection(connection, hostConfiguration, this);
838                 if (LOG.isDebugEnabled()) {
839                     LOG.debug("Getting free connection, hostConfig=" + hostConfiguration);
840                 }
841 
842                 // remove the connection from the timeout handler
843                 idleConnectionHandler.remove(connection);
844             } else if (LOG.isDebugEnabled()) {
845                 LOG.debug("There were no free connections to get, hostConfig=" 
846                     + hostConfiguration);
847             }
848             return connection;
849         }
850         
851         /**
852          * Deletes all closed connections.
853          */        
854         public synchronized void deleteClosedConnections() {
855             
856             Iterator iter = freeConnections.iterator();
857             
858             while (iter.hasNext()) {
859                 HttpConnection conn = (HttpConnection) iter.next();
860                 if (!conn.isOpen()) {
861                     iter.remove();
862                     deleteConnection(conn);
863                 }
864             }
865         }
866 
867         /**
868          * Closes idle connections.
869          * @param idleTimeout
870          */
871         public synchronized void closeIdleConnections(long idleTimeout) {
872             idleConnectionHandler.closeIdleConnections(idleTimeout);
873         }
874         
875         /**
876          * Deletes the given connection.  This will remove all reference to the connection
877          * so that it can be GCed.
878          * 
879          * <p><b>Note:</b> Does not remove the connection from the freeConnections list.  It
880          * is assumed that the caller has already handled this case.</p>
881          * 
882          * @param connection The connection to delete
883          */
884         private synchronized void deleteConnection(HttpConnection connection) {
885             
886             HostConfiguration connectionConfiguration = configurationForConnection(connection);
887 
888             if (LOG.isDebugEnabled()) {
889                 LOG.debug("Reclaiming connection, hostConfig=" + connectionConfiguration);
890             }
891 
892             connection.close();
893 
894             HostConnectionPool hostPool = getHostPool(connectionConfiguration, true);
895             
896             hostPool.freeConnections.remove(connection);
897             hostPool.numConnections--;
898             numConnections--;
899             if ((hostPool.numConnections == 0) &&
900                 hostPool.waitingThreads.isEmpty()) {
901 
902                 mapHosts.remove(connectionConfiguration);
903             }
904             
905             // remove the connection from the timeout handler
906             idleConnectionHandler.remove(connection);            
907         }
908         
909         /**
910          * Close and delete an old, unused connection to make room for a new one.
911          */
912         public synchronized void deleteLeastUsedConnection() {
913 
914             HttpConnection connection = (HttpConnection) freeConnections.removeFirst();
915 
916             if (connection != null) {
917                 deleteConnection(connection);
918             } else if (LOG.isDebugEnabled()) {
919                 LOG.debug("Attempted to reclaim an unused connection but there were none.");
920             }
921         }
922 
923         /**
924          * Notifies a waiting thread that a connection for the given configuration is 
925          * available.
926          * @param configuration the host config to use for notifying
927          * @see #notifyWaitingThread(HostConnectionPool)
928          */
929         public synchronized void notifyWaitingThread(HostConfiguration configuration) {
930             notifyWaitingThread(getHostPool(configuration, true));
931         }
932 
933         /**
934          * Notifies a waiting thread that a connection for the given configuration is 
935          * available.  This will wake a thread waiting in this host pool or if there is not
936          * one a thread in the connection pool will be notified.
937          * 
938          * @param hostPool the host pool to use for notifying
939          */
940         public synchronized void notifyWaitingThread(HostConnectionPool hostPool) {
941 
942             // find the thread we are going to notify, we want to ensure that each
943             // waiting thread is only interrupted once so we will remove it from 
944             // all wait queues before interrupting it
945             WaitingThread waitingThread = null;
946                 
947             if (hostPool.waitingThreads.size() > 0) {
948                 if (LOG.isDebugEnabled()) {
949                     LOG.debug("Notifying thread waiting on host pool, hostConfig=" 
950                         + hostPool.hostConfiguration);
951                 }
952                 waitingThread = (WaitingThread) hostPool.waitingThreads.removeFirst();
953                 waitingThreads.remove(waitingThread);
954             } else if (waitingThreads.size() > 0) {
955                 if (LOG.isDebugEnabled()) {
956                     LOG.debug("No-one waiting on host pool, notifying next waiting thread.");
957                 }
958                 waitingThread = (WaitingThread) waitingThreads.removeFirst();
959                 waitingThread.hostConnectionPool.waitingThreads.remove(waitingThread);
960             } else if (LOG.isDebugEnabled()) {
961                 LOG.debug("Notifying no-one, there are no waiting threads");
962             }
963                 
964             if (waitingThread != null) {
965                 waitingThread.interruptedByConnectionPool = true;
966                 waitingThread.thread.interrupt();
967             }
968         }
969 
970         /**
971          * Marks the given connection as free.
972          * @param conn a connection that is no longer being used
973          */
974         public void freeConnection(HttpConnection conn) {
975 
976             HostConfiguration connectionConfiguration = configurationForConnection(conn);
977 
978             if (LOG.isDebugEnabled()) {
979                 LOG.debug("Freeing connection, hostConfig=" + connectionConfiguration);
980             }
981 
982             synchronized (this) {
983                 
984                 if (shutdown) {
985                     // the connection manager has been shutdown, release the connection's
986                     // resources and get out of here
987                     conn.close();
988                     return;
989                 }
990                 
991                 HostConnectionPool hostPool = getHostPool(connectionConfiguration, true);
992 
993                 // Put the connect back in the available list and notify a waiter
994                 hostPool.freeConnections.add(conn);
995                 if (hostPool.numConnections == 0) {
996                     // for some reason this connection pool didn't already exist
997                     LOG.error("Host connection pool not found, hostConfig=" 
998                               + connectionConfiguration);
999                     hostPool.numConnections = 1;
1000                 }
1001 
1002                 freeConnections.add(conn);
1003                 // we can remove the reference to this connection as we have control over
1004                 // it again.  this also ensures that the connection manager can be GCed
1005                 removeReferenceToConnection((HttpConnectionWithReference) conn);
1006                 if (numConnections == 0) {
1007                     // for some reason this connection pool didn't already exist
1008                     LOG.error("Host connection pool not found, hostConfig=" 
1009                               + connectionConfiguration);
1010                     numConnections = 1;
1011                 }
1012 
1013                 // register the connection with the timeout handler
1014                 idleConnectionHandler.add(conn);
1015 
1016                 notifyWaitingThread(hostPool);
1017             }
1018         }
1019     }
1020 
1021     /**
1022      * A simple struct-like class to combine the objects needed to release a connection's
1023      * resources when claimed by the garbage collector.
1024      */
1025     private static class ConnectionSource {
1026         
1027         /** The connection pool that created the connection */
1028         public ConnectionPool connectionPool;
1029 
1030         /** The connection's host configuration */
1031         public HostConfiguration hostConfiguration;
1032     }
1033     
1034     /**
1035      * A simple struct-like class to combine the connection list and the count
1036      * of created connections.
1037      */
1038     private static class HostConnectionPool {
1039         /** The hostConfig this pool is for */
1040         public HostConfiguration hostConfiguration;
1041         
1042         /** The list of free connections */
1043         public LinkedList freeConnections = new LinkedList();
1044         
1045         /** The list of WaitingThreads for this host */
1046         public LinkedList waitingThreads = new LinkedList();
1047 
1048         /** The number of created connections */
1049         public int numConnections = 0;
1050     }
1051     
1052     /**
1053      * A simple struct-like class to combine the waiting thread and the connection 
1054      * pool it is waiting on.
1055      */
1056     private static class WaitingThread {
1057         /** The thread that is waiting for a connection */
1058         public Thread thread;
1059         
1060         /** The connection pool the thread is waiting for */
1061         public HostConnectionPool hostConnectionPool;
1062         
1063         /** Flag to indicate if the thread was interrupted by the ConnectionPool. Set
1064          * to true inside {@link ConnectionPool#notifyWaitingThread(HostConnectionPool)} 
1065          * before the thread is interrupted. */
1066         public boolean interruptedByConnectionPool = false;
1067     }
1068 
1069     /**
1070      * A thread for listening for HttpConnections reclaimed by the garbage
1071      * collector.
1072      */
1073     private static class ReferenceQueueThread extends Thread {
1074 
1075         private volatile boolean shutdown = false;
1076         
1077         /**
1078          * Create an instance and make this a daemon thread.
1079          */
1080         public ReferenceQueueThread() {
1081             setDaemon(true);
1082             setName("MultiThreadedHttpConnectionManager cleanup");
1083         }
1084 
1085         public void shutdown() {
1086             this.shutdown = true;
1087             this.interrupt();
1088         }
1089         
1090         /**
1091          * Handles cleaning up for the given connection reference.
1092          * 
1093          * @param ref the reference to clean up
1094          */
1095         private void handleReference(Reference ref) {
1096             
1097             ConnectionSource source = null;
1098             
1099             synchronized (REFERENCE_TO_CONNECTION_SOURCE) {
1100                 source = (ConnectionSource) REFERENCE_TO_CONNECTION_SOURCE.remove(ref);
1101             }
1102             // only clean up for this reference if it is still associated with 
1103             // a ConnectionSource
1104             if (source != null) {
1105                 if (LOG.isDebugEnabled()) {
1106                     LOG.debug(
1107                         "Connection reclaimed by garbage collector, hostConfig=" 
1108                         + source.hostConfiguration);
1109                 }
1110                 
1111                 source.connectionPool.handleLostConnection(source.hostConfiguration);
1112             }
1113         }
1114 
1115         /**
1116          * Start execution.
1117          */
1118         public void run() {
1119             while (!shutdown) {
1120                 try {
1121                     // remove the next reference and process it
1122                     Reference ref = REFERENCE_QUEUE.remove();
1123                     if (ref != null) {
1124                         handleReference(ref);
1125                     }
1126                 } catch (InterruptedException e) {
1127                     LOG.debug("ReferenceQueueThread interrupted", e);
1128                 }
1129             }
1130         }
1131 
1132     }
1133     
1134     /**
1135      * A connection that keeps a reference to itself.
1136      */
1137     private static class HttpConnectionWithReference extends HttpConnection {
1138         
1139         public WeakReference reference = new WeakReference(this, REFERENCE_QUEUE);
1140         
1141         /**
1142          * @param hostConfiguration
1143          */
1144         public HttpConnectionWithReference(HostConfiguration hostConfiguration) {
1145             super(hostConfiguration);
1146         }
1147 
1148     }
1149     
1150     /**
1151      * An HttpConnection wrapper that ensures a connection cannot be used
1152      * once released.
1153      */
1154     private static class HttpConnectionAdapter extends HttpConnection {
1155 
1156         // the wrapped connection
1157         private HttpConnection wrappedConnection;
1158 
1159         /**
1160          * Creates a new HttpConnectionAdapter.
1161          * @param connection the connection to be wrapped
1162          */
1163         public HttpConnectionAdapter(HttpConnection connection) {
1164             super(connection.getHost(), connection.getPort(), connection.getProtocol());
1165             this.wrappedConnection = connection;
1166         }
1167 
1168         /**
1169          * Tests if the wrapped connection is still available.
1170          * @return boolean
1171          */
1172         protected boolean hasConnection() {
1173             return wrappedConnection != null;
1174         }
1175 
1176         /**
1177          * @return HttpConnection
1178          */
1179         HttpConnection getWrappedConnection() {
1180             return wrappedConnection;
1181         }
1182         
1183         public void close() {
1184             if (hasConnection()) {
1185                 wrappedConnection.close();
1186             } else {
1187                 // do nothing
1188             }
1189         }
1190 
1191         public InetAddress getLocalAddress() {
1192             if (hasConnection()) {
1193                 return wrappedConnection.getLocalAddress();
1194             } else {
1195                 return null;
1196             }
1197         }
1198 
1199         /**
1200          * @deprecated
1201          */
1202         public boolean isStaleCheckingEnabled() {
1203             if (hasConnection()) {
1204                 return wrappedConnection.isStaleCheckingEnabled();
1205             } else {
1206                 return false;
1207             }
1208         }
1209 
1210         public void setLocalAddress(InetAddress localAddress) {
1211             if (hasConnection()) {
1212                 wrappedConnection.setLocalAddress(localAddress);
1213             } else {
1214                 throw new IllegalStateException("Connection has been released");
1215             }
1216         }
1217     
1218         /**
1219          * @deprecated 
1220          */
1221         public void setStaleCheckingEnabled(boolean staleCheckEnabled) {
1222             if (hasConnection()) {
1223                 wrappedConnection.setStaleCheckingEnabled(staleCheckEnabled);
1224             } else {
1225                 throw new IllegalStateException("Connection has been released");
1226             }
1227         }
1228 
1229         public String getHost() {
1230             if (hasConnection()) {
1231                 return wrappedConnection.getHost();
1232             } else {
1233                 return null;
1234             }
1235         }
1236 
1237         public HttpConnectionManager getHttpConnectionManager() {
1238             if (hasConnection()) {
1239                 return wrappedConnection.getHttpConnectionManager();
1240             } else {
1241                 return null;
1242             }
1243         }
1244 
1245         public InputStream getLastResponseInputStream() {
1246             if (hasConnection()) {
1247                 return wrappedConnection.getLastResponseInputStream();
1248             } else {
1249                 return null;
1250             }
1251         }
1252 
1253         public int getPort() {
1254             if (hasConnection()) {
1255                 return wrappedConnection.getPort();
1256             } else {
1257                 return -1;
1258             }
1259         }
1260 
1261         public Protocol getProtocol() {
1262             if (hasConnection()) {
1263                 return wrappedConnection.getProtocol();
1264             } else {
1265                 return null;
1266             }
1267         }
1268 
1269         public String getProxyHost() {
1270             if (hasConnection()) {
1271                 return wrappedConnection.getProxyHost();
1272             } else {
1273                 return null;
1274             }
1275         }
1276 
1277         public int getProxyPort() {
1278             if (hasConnection()) {
1279                 return wrappedConnection.getProxyPort();
1280             } else {
1281                 return -1;
1282             }
1283         }
1284 
1285         public OutputStream getRequestOutputStream()
1286             throws IOException, IllegalStateException {
1287             if (hasConnection()) {
1288                 return wrappedConnection.getRequestOutputStream();
1289             } else {
1290                 return null;
1291             }
1292         }
1293 
1294         public InputStream getResponseInputStream()
1295             throws IOException, IllegalStateException {
1296             if (hasConnection()) {
1297                 return wrappedConnection.getResponseInputStream();
1298             } else {
1299                 return null;
1300             }
1301         }
1302 
1303         public boolean isOpen() {
1304             if (hasConnection()) {
1305                 return wrappedConnection.isOpen();
1306             } else {
1307                 return false;
1308             }
1309         }
1310 
1311         public boolean closeIfStale() throws IOException {
1312             if (hasConnection()) {
1313                 return wrappedConnection.closeIfStale();
1314             } else {
1315                 return false;
1316             }
1317         }
1318 
1319         public boolean isProxied() {
1320             if (hasConnection()) {
1321                 return wrappedConnection.isProxied();
1322             } else {
1323                 return false;
1324             }
1325         }
1326 
1327         public boolean isResponseAvailable() throws IOException {
1328             if (hasConnection()) {
1329                 return  wrappedConnection.isResponseAvailable();
1330             } else {
1331                 return false;
1332             }
1333         }
1334 
1335         public boolean isResponseAvailable(int timeout) throws IOException {
1336             if (hasConnection()) {
1337                 return  wrappedConnection.isResponseAvailable(timeout);
1338             } else {
1339                 return false;
1340             }
1341         }
1342 
1343         public boolean isSecure() {
1344             if (hasConnection()) {
1345                 return wrappedConnection.isSecure();
1346             } else {
1347                 return false;
1348             }
1349         }
1350 
1351         public boolean isTransparent() {
1352             if (hasConnection()) {
1353                 return wrappedConnection.isTransparent();
1354             } else {
1355                 return false;
1356             }
1357         }
1358 
1359         public void open() throws IOException {
1360             if (hasConnection()) {
1361                 wrappedConnection.open();
1362             } else {
1363                 throw new IllegalStateException("Connection has been released");
1364             }
1365         }
1366 
1367         /**
1368          * @deprecated
1369          */
1370         public void print(String data)
1371             throws IOException, IllegalStateException {
1372             if (hasConnection()) {
1373                 wrappedConnection.print(data);
1374             } else {
1375                 throw new IllegalStateException("Connection has been released");
1376             }
1377         }
1378 
1379         public void printLine()
1380             throws IOException, IllegalStateException {
1381             if (hasConnection()) {
1382                 wrappedConnection.printLine();
1383             } else {
1384                 throw new IllegalStateException("Connection has been released");
1385             }
1386         }
1387 
1388         /**
1389          * @deprecated
1390          */
1391         public void printLine(String data)
1392             throws IOException, IllegalStateException {
1393             if (hasConnection()) {
1394                 wrappedConnection.printLine(data);
1395             } else {
1396                 throw new IllegalStateException("Connection has been released");
1397             }
1398         }
1399 
1400         /**
1401          * @deprecated
1402          */
1403         public String readLine() throws IOException, IllegalStateException {
1404             if (hasConnection()) {
1405                 return wrappedConnection.readLine();
1406             } else {
1407                 throw new IllegalStateException("Connection has been released");
1408             }
1409         }
1410 
1411         public String readLine(String charset) throws IOException, IllegalStateException {
1412             if (hasConnection()) {
1413                 return wrappedConnection.readLine(charset);
1414             } else {
1415                 throw new IllegalStateException("Connection has been released");
1416             }
1417         }
1418 
1419         public void releaseConnection() {
1420             if (!isLocked() && hasConnection()) {
1421                 HttpConnection wrappedConnection = this.wrappedConnection;
1422                 this.wrappedConnection = null;
1423                 wrappedConnection.releaseConnection();
1424             } else {
1425                 // do nothing
1426             }
1427         }
1428 
1429         /**
1430          * @deprecated
1431          */
1432         public void setConnectionTimeout(int timeout) {
1433             if (hasConnection()) {
1434                 wrappedConnection.setConnectionTimeout(timeout);
1435             } else {
1436                 // do nothing
1437             }
1438         }
1439 
1440         public void setHost(String host) throws IllegalStateException {
1441             if (hasConnection()) {
1442                 wrappedConnection.setHost(host);
1443             } else {
1444                 // do nothing
1445             }
1446         }
1447 
1448         public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager) {
1449             if (hasConnection()) {
1450                 wrappedConnection.setHttpConnectionManager(httpConnectionManager);
1451             } else {
1452                 // do nothing
1453             }
1454         }
1455 
1456         public void setLastResponseInputStream(InputStream inStream) {
1457             if (hasConnection()) {
1458                 wrappedConnection.setLastResponseInputStream(inStream);
1459             } else {
1460                 // do nothing
1461             }
1462         }
1463 
1464         public void setPort(int port) throws IllegalStateException {
1465             if (hasConnection()) {
1466                 wrappedConnection.setPort(port);
1467             } else {
1468                 // do nothing
1469             }
1470         }
1471 
1472         public void setProtocol(Protocol protocol) {
1473             if (hasConnection()) {
1474                 wrappedConnection.setProtocol(protocol);
1475             } else {
1476                 // do nothing
1477             }
1478         }
1479 
1480         public void setProxyHost(String host) throws IllegalStateException {
1481             if (hasConnection()) {
1482                 wrappedConnection.setProxyHost(host);
1483             } else {
1484                 // do nothing
1485             }
1486         }
1487 
1488         public void setProxyPort(int port) throws IllegalStateException {
1489             if (hasConnection()) {
1490                 wrappedConnection.setProxyPort(port);
1491             } else {
1492                 // do nothing
1493             }
1494         }
1495 
1496         /**
1497          * @deprecated
1498          */
1499         public void setSoTimeout(int timeout)
1500             throws SocketException, IllegalStateException {
1501             if (hasConnection()) {
1502                 wrappedConnection.setSoTimeout(timeout);
1503             } else {
1504                 // do nothing
1505             }
1506         }
1507 
1508         /**
1509          * @deprecated
1510          */
1511         public void shutdownOutput() {
1512             if (hasConnection()) {
1513                 wrappedConnection.shutdownOutput();
1514             } else {
1515                 // do nothing
1516             }
1517         }
1518 
1519         public void tunnelCreated() throws IllegalStateException, IOException {
1520             if (hasConnection()) {
1521                 wrappedConnection.tunnelCreated();
1522             } else {
1523                 // do nothing
1524             }
1525         }
1526 
1527         public void write(byte[] data, int offset, int length)
1528             throws IOException, IllegalStateException {
1529             if (hasConnection()) {
1530                 wrappedConnection.write(data, offset, length);
1531             } else {
1532                 throw new IllegalStateException("Connection has been released");
1533             }
1534         }
1535 
1536         public void write(byte[] data)
1537             throws IOException, IllegalStateException {
1538             if (hasConnection()) {
1539                 wrappedConnection.write(data);
1540             } else {
1541                 throw new IllegalStateException("Connection has been released");
1542             }
1543         }
1544 
1545         public void writeLine()
1546             throws IOException, IllegalStateException {
1547             if (hasConnection()) {
1548                 wrappedConnection.writeLine();
1549             } else {
1550                 throw new IllegalStateException("Connection has been released");
1551             }
1552         }
1553 
1554         public void writeLine(byte[] data)
1555             throws IOException, IllegalStateException {
1556             if (hasConnection()) {
1557                 wrappedConnection.writeLine(data);
1558             } else {
1559                 throw new IllegalStateException("Connection has been released");
1560             }
1561         }
1562 
1563         public void flushRequestOutputStream() throws IOException {
1564             if (hasConnection()) {
1565                 wrappedConnection.flushRequestOutputStream();
1566             } else {
1567                 throw new IllegalStateException("Connection has been released");
1568             }
1569         }
1570 
1571         /**
1572          * @deprecated
1573          */
1574         public int getSoTimeout() throws SocketException {
1575             if (hasConnection()) {
1576                 return wrappedConnection.getSoTimeout();
1577             } else {
1578                 throw new IllegalStateException("Connection has been released");
1579             }
1580         }
1581 
1582         /**
1583          * @deprecated
1584          */
1585         public String getVirtualHost() {
1586             if (hasConnection()) {
1587                 return wrappedConnection.getVirtualHost();
1588             } else {
1589                 throw new IllegalStateException("Connection has been released");
1590             }
1591         }
1592 
1593         /**
1594          * @deprecated
1595          */
1596         public void setVirtualHost(String host) throws IllegalStateException {
1597             if (hasConnection()) {
1598                 wrappedConnection.setVirtualHost(host);
1599             } else {
1600                 throw new IllegalStateException("Connection has been released");
1601             }
1602         }
1603 
1604         public int getSendBufferSize() throws SocketException {
1605             if (hasConnection()) {
1606                 return wrappedConnection.getSendBufferSize();
1607             } else {
1608                 throw new IllegalStateException("Connection has been released");
1609             }
1610         }
1611 
1612         /**
1613          * @deprecated
1614          */
1615         public void setSendBufferSize(int sendBufferSize) throws SocketException {
1616             if (hasConnection()) {
1617                 wrappedConnection.setSendBufferSize(sendBufferSize);
1618             } else {
1619                 throw new IllegalStateException("Connection has been released");
1620             }
1621         }
1622 
1623         public HttpConnectionParams getParams() {
1624             if (hasConnection()) {
1625                 return wrappedConnection.getParams();
1626             } else {
1627                 throw new IllegalStateException("Connection has been released");
1628             }
1629         }
1630 
1631         public void setParams(final HttpConnectionParams params) {
1632             if (hasConnection()) {
1633                 wrappedConnection.setParams(params);
1634             } else {
1635                 throw new IllegalStateException("Connection has been released");
1636             }
1637         }
1638 
1639         /* (non-Javadoc)
1640          * @see org.apache.commons.httpclient.HttpConnection#print(java.lang.String, java.lang.String)
1641          */
1642         public void print(String data, String charset) throws IOException, IllegalStateException {
1643             if (hasConnection()) {
1644                 wrappedConnection.print(data, charset);
1645             } else {
1646                 throw new IllegalStateException("Connection has been released");
1647             }
1648         }
1649 
1650         /* (non-Javadoc)
1651          * @see org.apache.commons.httpclient.HttpConnection#printLine(java.lang.String, java.lang.String)
1652          */
1653         public void printLine(String data, String charset)
1654             throws IOException, IllegalStateException {
1655             if (hasConnection()) {
1656                 wrappedConnection.printLine(data, charset);
1657             } else {
1658                 throw new IllegalStateException("Connection has been released");
1659             }
1660         }
1661 
1662         /* (non-Javadoc)
1663          * @see org.apache.commons.httpclient.HttpConnection#setSocketTimeout(int)
1664          */
1665         public void setSocketTimeout(int timeout) throws SocketException, IllegalStateException {
1666             if (hasConnection()) {
1667                 wrappedConnection.setSocketTimeout(timeout);
1668             } else {
1669                 throw new IllegalStateException("Connection has been released");
1670             }
1671         }
1672 
1673     }
1674 
1675 }
1676 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/NTCredentials.html100644 0 0 40672 10661532627 25516 0ustar 0 0 NTCredentials xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/NTCredentials.java,v 1.10 2004/04/18 23:51:35 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import org.apache.commons.httpclient.util.LangUtils;
34  
35  /** {@link Credentials} for use with the NTLM authentication scheme which requires additional
36   * information.
37   *
38   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
39   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
40   * 
41   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
42   * 
43   * @since 2.0
44   */
45  public class NTCredentials extends UsernamePasswordCredentials {
46  
47      // ----------------------------------------------------- Instance Variables
48  
49      /** The Domain to authenticate with.  */
50      private String domain;
51  
52      /** The host the authentication request is originating from.  */
53      private String host;
54  
55  
56      // ----------------------------------------------------------- Constructors
57  
58      /**
59       * Default constructor.
60       * 
61       * @deprecated Do not use. Null user name, domain & host no longer allowed
62       */
63      public NTCredentials() {
64          super();
65      }
66  
67      /**
68       * Constructor.
69       * @param userName The user name.  This should not include the domain to authenticate with.
70       * For example: "user" is correct whereas "DOMAIN\\user" is not.
71       * @param password The password.
72       * @param host The host the authentication request is originating from.  Essentially, the
73       * computer name for this machine.
74       * @param domain The domain to authenticate within.
75       */
76      public NTCredentials(String userName, String password, String host,
77              String domain) {
78          super(userName, password);
79          if (domain == null) {
80              throw new IllegalArgumentException("Domain may not be null");
81          }
82          this.domain = domain;
83          if (host == null) {
84              throw new IllegalArgumentException("Host may not be null");
85          }
86          this.host = host;
87      }
88      // ------------------------------------------------------- Instance Methods
89  
90  
91      /**
92       * Sets the domain to authenticate with. The domain may not be null.
93       *
94       * @param domain the NT domain to authenticate in.
95       * 
96       * @see #getDomain()
97       * 
98       * @deprecated Do not use. The NTCredentials objects should be immutable
99       */
100     public void setDomain(String domain) {
101         if (domain == null) {
102             throw new IllegalArgumentException("Domain may not be null");
103         }
104         this.domain = domain;
105     }
106 
107     /**
108      * Retrieves the name to authenticate with.
109      *
110      * @return String the domain these credentials are intended to authenticate with.
111      * 
112      * @see #setDomain(String)
113      * 
114      */
115     public String getDomain() {
116         return domain;
117     }
118 
119     /** 
120      * Sets the host name of the computer originating the request. The host name may
121      * not be null.
122      *
123      * @param host the Host the user is logged into.
124      * 
125      * @deprecated Do not use. The NTCredentials objects should be immutable
126      */
127     public void setHost(String host) {
128         if (host == null) {
129             throw new IllegalArgumentException("Host may not be null");
130         }
131         this.host = host;
132     }
133 
134     /**
135      * Retrieves the host name of the computer originating the request.
136      *
137      * @return String the host the user is logged into.
138      */
139     public String getHost() {
140         return this.host;
141     }
142     
143     /**
144      * Return a string representation of this object.
145      * @return A string represenation of this object.
146      */
147     public String toString() {
148         final StringBuffer sbResult = new StringBuffer(super.toString());
149         
150         sbResult.append("@");
151         sbResult.append(this.host);
152         sbResult.append(".");
153         sbResult.append(this.domain);
154 
155         return sbResult.toString();
156     }
157 
158     /**
159      * Computes a hash code based on all the case-sensitive parts of the credentials object.
160      *
161      * @return  The hash code for the credentials.
162      */
163     public int hashCode() {
164         int hash = super.hashCode();
165         hash = LangUtils.hashCode(hash, this.host);
166         hash = LangUtils.hashCode(hash, this.domain);
167         return hash;
168     }
169 
170     /**
171      * Performs a case-sensitive check to see if the components of the credentials
172      * are the same.
173      *
174      * @param o  The object to match.
175      *
176      * @return <code>true</code> if all of the credentials match.
177      */
178     public boolean equals(Object o) {
179         if (o == null) return false;
180         if (this == o) return true;
181         if (super.equals(o) ) {
182             if (o instanceof NTCredentials) {
183                 NTCredentials that = (NTCredentials) o;
184 
185                 return LangUtils.equals(this.domain, that.domain)
186                     && LangUtils.equals(this.host, that.host);
187             }
188         }
189 
190         return false;
191     }
192 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/NameValuePair.html100644 0 0 30625 10661532627 25505 0ustar 0 0 NameValuePair xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/NameValuePair.java,v 1.17 2004/04/18 23:51:35 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.Serializable;
34  
35  import org.apache.commons.httpclient.util.LangUtils;
36  
37  /**
38   * <p>A simple class encapsulating a name/value pair.</p>
39   * 
40   * @author <a href="mailto:bcholmes@interlog.com">B.C. Holmes</a>
41   * @author Sean C. Sullivan
42   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
43   * 
44   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
45   * 
46   */
47  public class NameValuePair implements Serializable {
48  
49      // ----------------------------------------------------------- Constructors
50  
51      /**
52       * Default constructor.
53       * 
54       */
55      public NameValuePair() {
56          this (null, null);
57      }
58  
59      /**
60       * Constructor.
61       * @param name The name.
62       * @param value The value.
63       */
64      public NameValuePair(String name, String value) {
65          this.name = name;
66          this.value = value;
67      }
68  
69      // ----------------------------------------------------- Instance Variables
70  
71      /**
72       * Name.
73       */
74      private String name = null;
75  
76      /**
77       * Value.
78       */
79      private String value = null;
80  
81      // ------------------------------------------------------------- Properties
82  
83      /**
84       * Set the name.
85       *
86       * @param name The new name
87       * @see #getName()
88       */
89      public void setName(String name) {
90          this.name = name;
91      }
92  
93  
94      /**
95       * Return the name.
96       *
97       * @return String name The name
98       * @see #setName(String)
99       */
100     public String getName() {
101         return name;
102     }
103 
104 
105     /**
106      * Set the value.
107      *
108      * @param value The new value.
109      */
110     public void setValue(String value) {
111         this.value = value;
112     }
113 
114 
115     /**
116      * Return the current value.
117      *
118      * @return String value The current value.
119      */
120     public String getValue() {
121         return value;
122     }
123 
124     // --------------------------------------------------------- Public Methods
125 
126     /**
127      * Get a String representation of this pair.
128      * @return A string representation.
129      */
130     public String toString() {
131         return ("name=" + name + ", " + "value=" + value);
132     }
133 
134     public boolean equals(final Object object) {
135         if (object == null) return false;
136         if (this == object) return true;
137         if (object instanceof NameValuePair) {
138             NameValuePair that = (NameValuePair) object;
139             return LangUtils.equals(this.name, that.name)
140                   && LangUtils.equals(this.value, that.value);
141         } else {
142             return false;
143         }
144     }
145 
146     public int hashCode() {
147         int hash = LangUtils.HASH_SEED;
148         hash = LangUtils.hashCode(hash, this.name);
149         hash = LangUtils.hashCode(hash, this.value);
150         return hash;
151     }
152 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/NoHttpResponseException.html100644 0 0 17157 10661532627 27633 0ustar 0 0 NoHttpResponseException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/NoHttpResponseException.java,v 1.1 2004/07/05 22:46:58 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  
35  import org.apache.commons.httpclient.util.ExceptionUtil;
36  
37  /**
38   * <p>
39   * Signals that the target server failed to respond with a valid HTTP response.
40   * </p>
41   * 
42   * @author <a href="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a>
43   * 
44   * @version $Revision: 480424 $
45   */
46  public class NoHttpResponseException extends IOException {
47  
48      /**
49       * Creates a new NoHttpResponseException with a <tt>null</tt> detail message.
50       */
51      public NoHttpResponseException() {
52          super();
53      }
54  
55      /**
56       * Creates a new NoHttpResponseException with the specified detail message.
57       *
58       * @param message exception message
59       */
60      public NoHttpResponseException(String message) {
61          super(message);
62      }
63  
64      /**
65       * Creates a new NoHttpResponseException with the specified detail message and cause.
66       *
67       * @param message the exception detail message
68       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
69       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
70       * 
71       * @since 3.0
72       */
73      public NoHttpResponseException(String message, Throwable cause) {
74          super(message);
75          // If we're running on JDK 1.4 or later, tell Throwable what the cause was
76          ExceptionUtil.initCause(this, cause);
77      }
78  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/ProtocolException.html100644 0 0 16065 10661532627 26476 0ustar 0 0 ProtocolException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ProtocolException.java,v 1.4 2004/05/13 04:03:25 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * Signals that an HTTP protocol violation has occurred.  For example, HttpClient
35   * detected a malformed status line or headers, a missing message body, etc.
36   * 
37   * @author <a href="mailto:laura@lwerner.org">Laura Werner</a>
38   * 
39   * @since 3.0
40   */
41  public class ProtocolException extends HttpException {
42  
43      /**
44       * Creates a new ProtocolException with a <tt>null</tt> detail message. 
45       */
46      public ProtocolException() {
47          super();
48      }
49  
50      /**
51       * Creates a new ProtocolException with the specified detail message.
52       * 
53       * @param message The exception detail message
54       */
55      public ProtocolException(String message) {
56          super(message);
57      }
58  
59      /**
60       * Creates a new ProtocolException with the specified detail message and cause.
61       * 
62       * @param message the exception detail message
63       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
64       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
65       */
66      public ProtocolException(String message, Throwable cause) {
67          super(message, cause);
68      }
69  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/ProxyClient.html100644 0 0 70502 10661532627 25272 0ustar 0 0 ProxyClient xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ProxyClient.java,v 1.5 2004/12/20 11:39:04 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.net.Socket;
35  
36  import org.apache.commons.httpclient.params.HttpClientParams;
37  import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
38  import org.apache.commons.httpclient.params.HttpParams;
39  
40  /**
41   * A client that provides {@link java.net.Socket sockets} for communicating through HTTP proxies
42   * via the HTTP CONNECT method.  This is primarily needed for non-HTTP protocols that wish to 
43   * communicate via an HTTP proxy.
44   * 
45   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
46   * @author Michael Becke
47   * 
48   * @since 3.0
49   * 
50   * @version $Revision: 480424 $
51   */
52  public class ProxyClient {
53  
54      // ----------------------------------------------------- Instance Variables
55  
56      /**
57       * The {@link HttpState HTTP state} associated with this ProxyClient.
58       */
59      private HttpState state = new HttpState();
60      
61      /**
62       * The {@link HttpClientParams collection of parameters} associated with this ProxyClient.
63       */
64      private HttpClientParams params = null; 
65  
66      /** 
67       * The {@link HostConfiguration host configuration} associated with
68       * the ProxyClient
69       */
70      private HostConfiguration hostConfiguration = new HostConfiguration();
71      
72      /**
73       * Creates an instance of ProxyClient using default {@link HttpClientParams parameter set}.
74       * 
75       * @see HttpClientParams
76       */
77      public ProxyClient() {
78          this(new HttpClientParams());
79      }
80  
81      /**
82       * Creates an instance of ProxyClient using the given 
83       * {@link HttpClientParams parameter set}.
84       * 
85       * @param params The {@link HttpClientParams parameters} to use.
86       * 
87       * @see HttpClientParams
88       */
89      public ProxyClient(HttpClientParams params) {
90          super();
91          if (params == null) {
92              throw new IllegalArgumentException("Params may not be null");  
93          }
94          this.params = params;
95      }
96  
97      // ------------------------------------------------------------- Properties
98  
99      /**
100      * Returns {@link HttpState HTTP state} associated with the ProxyClient.
101      *
102      * @see #setState(HttpState)
103      * @return the shared client state
104      */
105     public synchronized HttpState getState() {
106         return state;
107     }
108 
109     /**
110      * Assigns {@link HttpState HTTP state} for the ProxyClient.
111      *
112      * @see #getState()
113      * @param state the new {@link HttpState HTTP state} for the client
114      */
115     public synchronized void setState(HttpState state) {
116         this.state = state;
117     }
118 
119     /**
120      * Returns the {@link HostConfiguration host configuration} associated with the 
121      * ProxyClient.
122      * 
123      * @return {@link HostConfiguration host configuration}
124      */
125     public synchronized HostConfiguration getHostConfiguration() {
126         return hostConfiguration;
127     }
128 
129     /**
130      * Assigns the {@link HostConfiguration host configuration} to use with the
131      * ProxyClient.
132      * 
133      * @param hostConfiguration The {@link HostConfiguration host configuration} to set
134      */
135     public synchronized void setHostConfiguration(HostConfiguration hostConfiguration) {
136         this.hostConfiguration = hostConfiguration;
137     }
138 
139     /**
140      * Returns {@link HttpClientParams HTTP protocol parameters} associated with this ProxyClient.
141      * 
142      * @see HttpClientParams
143      */
144     public synchronized HttpClientParams getParams() {
145         return this.params;
146     }
147 
148     /**
149      * Assigns {@link HttpClientParams HTTP protocol parameters} for this ProxyClient.
150      * 
151      * @see HttpClientParams
152      */
153     public synchronized void setParams(final HttpClientParams params) {
154         if (params == null) {
155             throw new IllegalArgumentException("Parameters may not be null");
156         }
157         this.params = params;
158     }
159 
160     /**
161      * Creates a socket that is connected, via the HTTP CONNECT method, to a proxy.
162      * 
163      * <p>
164      * Even though HTTP CONNECT proxying is generally used for HTTPS tunneling, the returned
165      * socket will not have been wrapped in an SSL socket.
166      * </p>
167      * 
168      * <p>
169      * Both the proxy and destination hosts must be set via the 
170      * {@link #getHostConfiguration() host configuration} prior to calling this method.
171      * </p>
172      * 
173      * @return the connect response
174      * 
175      * @throws IOException
176      * @throws HttpException
177      * 
178      * @see #getHostConfiguration()
179      */
180     public ConnectResponse connect() throws IOException, HttpException {
181         
182         HostConfiguration hostconf = getHostConfiguration();
183         if (hostconf.getProxyHost() == null) {
184             throw new IllegalStateException("proxy host must be configured");
185         }
186         if (hostconf.getHost() == null) {
187             throw new IllegalStateException("destination host must be configured");
188         }
189         if (hostconf.getProtocol().isSecure()) {
190             throw new IllegalStateException("secure protocol socket factory may not be used");
191         }
192         
193         ConnectMethod method = new ConnectMethod(getHostConfiguration());
194         method.getParams().setDefaults(getParams());
195         
196         DummyConnectionManager connectionManager = new DummyConnectionManager();
197         connectionManager.setConnectionParams(getParams());
198         
199         HttpMethodDirector director = new HttpMethodDirector(
200             connectionManager,
201             hostconf,
202             getParams(),
203             getState()
204         );
205         
206         director.executeMethod(method);
207         
208         ConnectResponse response = new ConnectResponse();
209         response.setConnectMethod(method);
210         
211         // only set the socket if the connect was successful
212         if (method.getStatusCode() == HttpStatus.SC_OK) {
213             response.setSocket(connectionManager.getConnection().getSocket());
214         } else {
215             connectionManager.getConnection().close();
216         }
217         
218         return response;
219     }
220 
221     /**
222      * Contains the method used to execute the connect along with the created socket.
223      */
224     public static class ConnectResponse {
225         
226         private ConnectMethod connectMethod;
227         
228         private Socket socket;
229         
230         private ConnectResponse() {}
231         
232         /**
233          * Gets the method that was used to execute the connect.  This method is useful for 
234          * analyzing the proxy's response when a connect fails.
235          * 
236          * @return the connectMethod.
237          */
238         public ConnectMethod getConnectMethod() {
239             return connectMethod;
240         }
241         /**
242          * @param connectMethod The connectMethod to set.
243          */
244         private void setConnectMethod(ConnectMethod connectMethod) {
245             this.connectMethod = connectMethod;
246         }
247         /**
248          * Gets the socket connected and authenticated (if appropriate) to the configured
249          * HTTP proxy, or <code>null</code> if a connection could not be made.  It is the
250          * responsibility of the user to close this socket when it is no longer needed.
251          * 
252          * @return the socket.
253          */
254         public Socket getSocket() {
255             return socket;
256         }
257         /**
258          * @param socket The socket to set.
259          */
260         private void setSocket(Socket socket) {
261             this.socket = socket;
262         }
263     }
264     
265     /**
266      * A connection manager that creates a single connection.  Meant to be used only once.
267      */
268     static class DummyConnectionManager implements HttpConnectionManager {
269 
270         private HttpConnection httpConnection;
271         
272         private HttpParams connectionParams;
273         
274         public void closeIdleConnections(long idleTimeout) {
275         }
276 
277         public HttpConnection getConnection() {
278             return httpConnection;
279         }
280 
281         public void setConnectionParams(HttpParams httpParams) {
282             this.connectionParams = httpParams;
283         }
284 
285         public HttpConnection getConnectionWithTimeout(
286             HostConfiguration hostConfiguration, long timeout) {
287 
288             httpConnection = new HttpConnection(hostConfiguration);
289             httpConnection.setHttpConnectionManager(this);
290             httpConnection.getParams().setDefaults(connectionParams);
291             return httpConnection;
292         }        
293         
294         /**
295          * @deprecated
296          */
297         public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout)
298             throws HttpException {
299             return getConnectionWithTimeout(hostConfiguration, timeout);
300         }
301         
302         public HttpConnection getConnection(HostConfiguration hostConfiguration) {
303             return getConnectionWithTimeout(hostConfiguration, -1);
304         }
305     
306         public void releaseConnection(HttpConnection conn) {
307         }
308 
309         public HttpConnectionManagerParams getParams() {
310             return null;
311         }
312 
313         public void setParams(HttpConnectionManagerParams params) {
314         }
315     }
316 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/ProxyHost.html100644 0 0 20460 10661532627 24767 0ustar 0 0 ProxyHost xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ProxyHost.java,v 1.2 2005/01/14 21:16:40 olegk Exp $
3    * $Revision: 510587 $
4    * $Date: 2007-02-22 17:56:08 +0100 (Thu, 22 Feb 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import org.apache.commons.httpclient.protocol.Protocol;
34  
35  /**
36   * Holds all of the variables needed to describe an HTTP connection to a proxy. Proxy hosts
37   * always use plain HTTP connection when communicating with clients.
38   * 
39   * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
40   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
41   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
42   * @author Laura Werner
43   * 
44   * @since 3.0 
45   */
46  public class ProxyHost extends HttpHost {
47  
48      /**
49       * Copy constructor for HttpHost
50       * 
51       * @param httpproxy the HTTP host to copy details from
52       */
53      public ProxyHost (final ProxyHost httpproxy) {
54          super(httpproxy);
55      }
56  
57      /**
58       * Constructor for ProxyHost.
59       *   
60       * @param hostname the hostname (IP or DNS name). Can be <code>null</code>.
61       * @param port the port. Value <code>-1</code> can be used to set default protocol port
62       */
63      public ProxyHost(final String hostname, int port) {
64          super(hostname, port, Protocol.getProtocol("http"));
65      }
66      
67      /**
68       * Constructor for HttpHost.
69       *   
70       * @param hostname the hostname (IP or DNS name). Can be <code>null</code>.
71       */
72      public ProxyHost(final String hostname) {
73          this(hostname, -1);
74      }
75      
76      /**
77       * @throws CloneNotSupportedException 
78       * @see java.lang.Object#clone()
79       */
80      public Object clone() throws CloneNotSupportedException {
81      	ProxyHost copy = (ProxyHost) super.clone();
82          return copy;
83      }    
84      
85  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/RedirectException.html100644 0 0 15672 10661532627 26441 0ustar 0 0 RedirectException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/RedirectException.java,v 1.2 2004/04/18 23:51:35 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * Signals violation of HTTP specification caused by an invalid redirect
35   * 
36   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
37   * 
38   * @since 3.0
39   */
40  public class RedirectException extends ProtocolException {
41  
42      /**
43       * Creates a new RedirectException with a <tt>null</tt> detail message. 
44       */
45      public RedirectException() {
46          super();
47      }
48  
49      /**
50       * Creates a new RedirectException with the specified detail message.
51       * 
52       * @param message The exception detail message
53       */
54      public RedirectException(String message) {
55          super(message);
56      }
57  
58      /**
59       * Creates a new RedirectException with the specified detail message and cause.
60       * 
61       * @param message the exception detail message
62       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
63       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
64       */
65      public RedirectException(String message, Throwable cause) {
66          super(message, cause);
67      }
68  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/ResponseConsumedWatcher.html100644 0 0 13167 10661532627 27630 0ustar 0 0 ResponseConsumedWatcher xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ResponseConsumedWatcher.java,v 1.5 2004/04/18 23:51:35 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * When a response stream has been consumed, various parts of the HttpClient
35   * implementation need to respond appropriately.
36   *
37   * <p>When one of the three types of {@link java.io.InputStream}, one of
38   * AutoCloseInputStream (package), {@link ContentLengthInputStream}, or
39   * {@link ChunkedInputStream} finishes with its content, either because
40   * all content has been consumed, or because it was explicitly closed,
41   * it notifies its corresponding method via this interface.</p>
42   *
43   * @see ContentLengthInputStream
44   * @see ChunkedInputStream
45   * @author Eric Johnson
46   */
47  interface ResponseConsumedWatcher {
48  
49      /**
50       * A response has been consumed.
51       */
52      void responseConsumed();
53  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/SimpleHttpConnectionManager.html100644 0 0 62050 10661532627 30415 0ustar 0 0 SimpleHttpConnectionManager xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/SimpleHttpConnectionManager.java,v 1.23 2004/10/16 22:40:08 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  
36  import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  
40  /**
41   * A connection manager that provides access to a single HttpConnection.  This
42   * manager makes no attempt to provide exclusive access to the contained
43   * HttpConnection.
44   *
45   * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
46   * @author Eric Johnson
47   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
48   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
49   * @author Laura Werner
50   * 
51   * @since 2.0
52   */
53  public class SimpleHttpConnectionManager implements HttpConnectionManager {
54  
55      private static final Log LOG = LogFactory.getLog(SimpleHttpConnectionManager.class);
56  
57      private static final String MISUSE_MESSAGE = 
58          "SimpleHttpConnectionManager being used incorrectly.  Be sure that"
59          + " HttpMethod.releaseConnection() is always called and that only one thread"
60          + " and/or method is using this connection manager at a time.";
61      
62      /**
63       * Since the same connection is about to be reused, make sure the
64       * previous request was completely processed, and if not
65       * consume it now.
66       * @param conn The connection
67       */
68      static void finishLastResponse(HttpConnection conn) {
69          InputStream lastResponse = conn.getLastResponseInputStream();
70          if (lastResponse != null) {
71              conn.setLastResponseInputStream(null);
72              try {
73                  lastResponse.close();
74              } catch (IOException ioe) {
75                  conn.close();
76              }
77          }
78      }
79      
80      /** The http connection */
81      protected HttpConnection httpConnection;
82  
83      /**
84       * Collection of parameters associated with this connection manager.
85       */
86      private HttpConnectionManagerParams params = new HttpConnectionManagerParams(); 
87  
88      /**
89       * The time the connection was made idle.
90       */
91      private long idleStartTime = Long.MAX_VALUE;
92      
93      /**
94       * Used to test if {@link #httpConnection} is currently in use 
95       * (i.e. checked out).  This is only used as a sanity check to help
96       * debug cases where this connection manager is being used incorrectly.
97       * It will not be used to enforce thread safety.
98       */
99      private volatile boolean inUse = false;
100 
101     private boolean alwaysClose = false;
102 
103     /**
104      * The connection manager created with this constructor will try to keep the 
105      * connection open (alive) between consecutive requests if the alwaysClose 
106      * parameter is set to <tt>false</tt>. Otherwise the connection manager will 
107      * always close connections upon release.
108      * 
109      * @param alwaysClose if set <tt>true</tt>, the connection manager will always
110      *    close connections upon release.
111      */
112     public SimpleHttpConnectionManager(boolean alwaysClose) {
113         super();
114         this.alwaysClose = alwaysClose;
115     }
116     
117     /**
118      * The connection manager created with this constructor will always try to keep 
119      * the connection open (alive) between consecutive requests.
120      */
121     public SimpleHttpConnectionManager() {
122         super();
123     }
124     
125     /**
126      * @see HttpConnectionManager#getConnection(HostConfiguration)
127      */
128     public HttpConnection getConnection(HostConfiguration hostConfiguration) {
129         return getConnection(hostConfiguration, 0);
130     }
131 
132     /**
133      * Gets the staleCheckingEnabled value to be set on HttpConnections that are created.
134      * 
135      * @return <code>true</code> if stale checking will be enabled on HttpConections
136      * 
137      * @see HttpConnection#isStaleCheckingEnabled()
138      * 
139      * @deprecated Use {@link HttpConnectionManagerParams#isStaleCheckingEnabled()},
140      * {@link HttpConnectionManager#getParams()}.
141      */
142     public boolean isConnectionStaleCheckingEnabled() {
143         return this.params.isStaleCheckingEnabled();
144     }
145 
146     /**
147      * Sets the staleCheckingEnabled value to be set on HttpConnections that are created.
148      * 
149      * @param connectionStaleCheckingEnabled <code>true</code> if stale checking will be enabled 
150      * on HttpConections
151      * 
152      * @see HttpConnection#setStaleCheckingEnabled(boolean)
153      * 
154      * @deprecated Use {@link HttpConnectionManagerParams#setStaleCheckingEnabled(boolean)},
155      * {@link HttpConnectionManager#getParams()}.
156      */
157     public void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled) {
158         this.params.setStaleCheckingEnabled(connectionStaleCheckingEnabled);
159     }
160     
161     /**
162      * This method always returns the same connection object. If the connection is already
163      * open, it will be closed and the new host configuration will be applied.
164      * 
165      * @param hostConfiguration The host configuration specifying the connection
166      *        details.
167      * @param timeout this parameter has no effect. The connection is always returned
168      *        immediately.
169      * @since 3.0
170      */
171     public HttpConnection getConnectionWithTimeout(
172         HostConfiguration hostConfiguration, long timeout) {
173 
174         if (httpConnection == null) {
175             httpConnection = new HttpConnection(hostConfiguration);
176             httpConnection.setHttpConnectionManager(this);
177             httpConnection.getParams().setDefaults(this.params);
178         } else {
179 
180             // make sure the host and proxy are correct for this connection
181             // close it and set the values if they are not
182             if (!hostConfiguration.hostEquals(httpConnection)
183                 || !hostConfiguration.proxyEquals(httpConnection)) {
184                     
185                 if (httpConnection.isOpen()) {
186                     httpConnection.close();
187                 }
188 
189                 httpConnection.setHost(hostConfiguration.getHost());
190                 httpConnection.setPort(hostConfiguration.getPort());
191                 httpConnection.setProtocol(hostConfiguration.getProtocol());
192                 httpConnection.setLocalAddress(hostConfiguration.getLocalAddress());
193 
194                 httpConnection.setProxyHost(hostConfiguration.getProxyHost());
195                 httpConnection.setProxyPort(hostConfiguration.getProxyPort());
196             } else {
197                 finishLastResponse(httpConnection);
198             }
199         }
200 
201         // remove the connection from the timeout handler
202         idleStartTime = Long.MAX_VALUE;
203 
204         if (inUse) LOG.warn(MISUSE_MESSAGE);
205         inUse = true;
206         
207         return httpConnection;
208     }
209 
210 	/**
211 	 * @see HttpConnectionManager#getConnection(HostConfiguration, long)
212 	 * 
213 	 * @deprecated Use #getConnectionWithTimeout(HostConfiguration, long)
214 	 */
215 	public HttpConnection getConnection(
216 		HostConfiguration hostConfiguration, long timeout) {
217         return getConnectionWithTimeout(hostConfiguration, timeout);
218 	}
219 
220     /**
221      * @see HttpConnectionManager#releaseConnection(org.apache.commons.httpclient.HttpConnection)
222      */
223     public void releaseConnection(HttpConnection conn) {
224         if (conn != httpConnection) {
225             throw new IllegalStateException("Unexpected release of an unknown connection.");
226         }
227         if (this.alwaysClose) {
228             httpConnection.close();
229         } else {
230             // make sure the connection is reuseable
231             finishLastResponse(httpConnection);
232         }
233         
234         inUse = false;
235 
236         // track the time the connection was made idle
237         idleStartTime = System.currentTimeMillis();
238     }
239 
240     /**
241      * Returns {@link HttpConnectionManagerParams parameters} associated 
242      * with this connection manager.
243      * 
244      * @since 2.1
245      * 
246      * @see HttpConnectionManagerParams
247      */
248     public HttpConnectionManagerParams getParams() {
249         return this.params;
250     }
251 
252     /**
253      * Assigns {@link HttpConnectionManagerParams parameters} for this 
254      * connection manager.
255      * 
256      * @since 2.1
257      * 
258      * @see HttpConnectionManagerParams
259      */
260     public void setParams(final HttpConnectionManagerParams params) {
261         if (params == null) {
262             throw new IllegalArgumentException("Parameters may not be null");
263         }
264         this.params = params;
265     }
266     
267     /**
268      * @since 3.0
269      */
270     public void closeIdleConnections(long idleTimeout) {
271         long maxIdleTime = System.currentTimeMillis() - idleTimeout;
272         if (idleStartTime <= maxIdleTime) {
273             httpConnection.close();
274         }
275     }
276     
277     /**
278      * since 3.1
279      */
280     public void shutdown() {
281         httpConnection.close();
282     }
283     
284 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/StatusLine.html100644 0 0 40507 10661532627 25107 0ustar 0 0 StatusLine xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/StatusLine.java,v 1.14 2004/07/19 20:24:21 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * Represents a Status-Line as returned from a HTTP server.
35   *
36   * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a> states
37   * the following regarding the Status-Line:
38   * <pre>
39   * 6.1 Status-Line
40   *
41   *  The first line of a Response message is the Status-Line, consisting
42   *  of the protocol version followed by a numeric status code and its
43   *  associated textual phrase, with each element separated by SP
44   *  characters. No CR or LF is allowed except in the final CRLF sequence.
45   *
46   *      Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
47   * </pre>
48   * <p>
49   * This class is immutable and is inherently thread safe.
50   *
51   * @see HttpStatus
52   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
53   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
54   * @version $Id: StatusLine.java 480424 2006-11-29 05:56:49Z bayard $
55   * @since 2.0
56   */
57  public class StatusLine {
58  
59      // ----------------------------------------------------- Instance Variables
60  
61      /** The original Status-Line. */
62      private final String statusLine;
63  
64      /** The HTTP-Version. */
65      private final String httpVersion;
66  
67      /** The Status-Code. */
68      private final int statusCode;
69  
70      /** The Reason-Phrase. */
71      private final String reasonPhrase;
72  
73  
74      // ----------------------------------------------------------- Constructors
75  
76      /**
77       * Default constructor.
78       *
79       * @param statusLine the status line returned from the HTTP server
80       * @throws HttpException if the status line is invalid
81       */
82      public StatusLine(final String statusLine) throws HttpException {
83  
84          int length = statusLine.length();
85          int at = 0;
86          int start = 0;
87          try {
88              while (Character.isWhitespace(statusLine.charAt(at))) {
89                  ++at;
90                  ++start;
91              }
92              if (!"HTTP".equals(statusLine.substring(at, at += 4))) {
93                  throw new HttpException("Status-Line '" + statusLine 
94                      + "' does not start with HTTP");
95              }
96              //handle the HTTP-Version
97              at = statusLine.indexOf(" ", at);
98              if (at <= 0) {
99                  throw new ProtocolException(
100                         "Unable to parse HTTP-Version from the status line: '"
101                         + statusLine + "'");
102             }
103             this.httpVersion = (statusLine.substring(start, at)).toUpperCase();
104 
105             //advance through spaces
106             while (statusLine.charAt(at) == ' ') {
107                 at++;
108             }
109 
110             //handle the Status-Code
111             int to = statusLine.indexOf(" ", at);
112             if (to < 0) {
113                 to = length;
114             }
115             try {
116                 this.statusCode = Integer.parseInt(statusLine.substring(at, to));
117             } catch (NumberFormatException e) {
118                 throw new ProtocolException(
119                     "Unable to parse status code from status line: '" 
120                     + statusLine + "'");
121             }
122             //handle the Reason-Phrase
123             at = to + 1;
124             if (at < length) {
125                 this.reasonPhrase = statusLine.substring(at).trim();
126             } else {
127                 this.reasonPhrase = "";
128             }
129         } catch (StringIndexOutOfBoundsException e) {
130             throw new HttpException("Status-Line '" + statusLine + "' is not valid"); 
131         }
132         //save the original Status-Line
133         this.statusLine = statusLine;
134     }
135 
136 
137     // --------------------------------------------------------- Public Methods
138 
139     /**
140      * @return the Status-Code
141      */
142     public final int getStatusCode() {
143         return statusCode;
144     }
145 
146     /**
147      * @return the HTTP-Version
148      */
149     public final String getHttpVersion() {
150         return httpVersion;
151     }
152 
153     /**
154      * @return the Reason-Phrase
155      */
156     public final String getReasonPhrase() {
157         return reasonPhrase;
158     }
159 
160     /**
161      * Return a string representation of this object.
162      * @return a string represenation of this object.
163      */
164     public final String toString() {
165         return statusLine;
166     }
167 
168     /**
169      * Tests if the string starts with 'HTTP' signature.
170      * @param s string to test
171      * @return <tt>true</tt> if the line starts with 'HTTP' 
172      *   signature, <tt>false</tt> otherwise.
173      */
174     public static boolean startsWithHTTP(final String s) {
175         try {
176             int at = 0;
177             while (Character.isWhitespace(s.charAt(at))) {
178                 ++at;
179             }
180             return ("HTTP".equals(s.substring(at, at + 4)));
181         } catch (StringIndexOutOfBoundsException e) {
182             return false;
183         }
184     }
185 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/URI.html100644 0 0 1176413 10661532627 23522 0ustar 0 0 URI xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/URI.java $
3    * $Revision: 564973 $
4    * $Date: 2007-08-11 22:51:47 +0200 (Sat, 11 Aug 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.io.ObjectInputStream;
35  import java.io.ObjectOutputStream;
36  import java.io.Serializable;
37  import java.util.Arrays;
38  import java.util.Locale;
39  import java.util.BitSet;
40  import java.util.Hashtable;
41  
42  import org.apache.commons.codec.DecoderException;
43  import org.apache.commons.codec.net.URLCodec;
44  import org.apache.commons.httpclient.util.EncodingUtil;
45  
46  /**
47   * The interface for the URI(Uniform Resource Identifiers) version of RFC 2396.
48   * This class has the purpose of supportting of parsing a URI reference to
49   * extend any specific protocols, the character encoding of the protocol to 
50   * be transported and the charset of the document.
51   * <p>
52   * A URI is always in an "escaped" form, since escaping or unescaping a
53   * completed URI might change its semantics.  
54   * <p>
55   * Implementers should be careful not to escape or unescape the same string
56   * more than once, since unescaping an already unescaped string might lead to
57   * misinterpreting a percent data character as another escaped character,
58   * or vice versa in the case of escaping an already escaped string.
59   * <p>
60   * In order to avoid these problems, data types used as follows:
61   * <p><blockquote><pre>
62   *   URI character sequence: char
63   *   octet sequence: byte
64   *   original character sequence: String
65   * </pre></blockquote><p>
66   *
67   * So, a URI is a sequence of characters as an array of a char type, which
68   * is not always represented as a sequence of octets as an array of byte.
69   * <p>
70   * 
71   * URI Syntactic Components
72   * <p><blockquote><pre>
73   * - In general, written as follows:
74   *   Absolute URI = &lt;scheme&gt:&lt;scheme-specific-part&gt;
75   *   Generic URI = &lt;scheme&gt;://&lt;authority&gt;&lt;path&gt;?&lt;query&gt;
76   *
77   * - Syntax
78   *   absoluteURI   = scheme ":" ( hier_part | opaque_part )
79   *   hier_part     = ( net_path | abs_path ) [ "?" query ]
80   *   net_path      = "//" authority [ abs_path ]
81   *   abs_path      = "/"  path_segments
82   * </pre></blockquote><p>
83   *
84   * The following examples illustrate URI that are in common use.
85   * <pre>
86   * ftp://ftp.is.co.za/rfc/rfc1808.txt
87   *    -- ftp scheme for File Transfer Protocol services
88   * gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles
89   *    -- gopher scheme for Gopher and Gopher+ Protocol services
90   * http://www.math.uio.no/faq/compression-faq/part1.html
91   *    -- http scheme for Hypertext Transfer Protocol services
92   * mailto:mduerst@ifi.unizh.ch
93   *    -- mailto scheme for electronic mail addresses
94   * news:comp.infosystems.www.servers.unix
95   *    -- news scheme for USENET news groups and articles
96   * telnet://melvyl.ucop.edu/
97   *    -- telnet scheme for interactive services via the TELNET Protocol
98   * </pre>
99   * Please, notice that there are many modifications from URL(RFC 1738) and
100  * relative URL(RFC 1808).
101  * <p>
102  * <b>The expressions for a URI</b>
103  * <p><pre>
104  * For escaped URI forms
105  *  - URI(char[]) // constructor
106  *  - char[] getRawXxx() // method
107  *  - String getEscapedXxx() // method
108  *  - String toString() // method
109  * <p>
110  * For unescaped URI forms
111  *  - URI(String) // constructor
112  *  - String getXXX() // method
113  * </pre><p>
114  *
115  * @author <a href="mailto:jericho@apache.org">Sung-Gu</a>
116  * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
117  * @version $Revision: 564973 $ $Date: 2002/03/14 15:14:01 
118  */
119 public class URI implements Cloneable, Comparable, Serializable {
120 
121 
122     // ----------------------------------------------------------- Constructors
123 
124     /** Create an instance as an internal use */
125     protected URI() {
126     }
127 
128     /**
129      * Construct a URI from a string with the given charset. The input string can 
130      * be either in escaped or unescaped form. 
131      *
132      * @param s URI character sequence
133      * @param escaped <tt>true</tt> if URI character sequence is in escaped form. 
134      *                <tt>false</tt> otherwise. 
135      * @param charset the charset string to do escape encoding, if required
136      * 
137      * @throws URIException If the URI cannot be created.
138      * @throws NullPointerException if input string is <code>null</code>
139      * 
140      * @see #getProtocolCharset
141      * 
142      * @since 3.0
143      */
144     public URI(String s, boolean escaped, String charset)
145         throws URIException, NullPointerException {
146         protocolCharset = charset;
147         parseUriReference(s, escaped);
148     }
149 
150     /**
151      * Construct a URI from a string with the given charset. The input string can 
152      * be either in escaped or unescaped form. 
153      *
154      * @param s URI character sequence
155      * @param escaped <tt>true</tt> if URI character sequence is in escaped form. 
156      *                <tt>false</tt> otherwise. 
157      * 
158      * @throws URIException If the URI cannot be created.
159      * @throws NullPointerException if input string is <code>null</code>
160      * 
161      * @see #getProtocolCharset
162      * 
163      * @since 3.0
164      */
165     public URI(String s, boolean escaped)
166         throws URIException, NullPointerException {
167         parseUriReference(s, escaped);
168     }
169 
170     /**
171      * Construct a URI as an escaped form of a character array with the given
172      * charset.
173      *
174      * @param escaped the URI character sequence
175      * @param charset the charset string to do escape encoding
176      * @throws URIException If the URI cannot be created.
177      * @throws NullPointerException if <code>escaped</code> is <code>null</code>
178      * @see #getProtocolCharset
179      * 
180      * @deprecated Use #URI(String, boolean, String)
181      */
182     public URI(char[] escaped, String charset) 
183         throws URIException, NullPointerException {
184         protocolCharset = charset;
185         parseUriReference(new String(escaped), true);
186     }
187 
188 
189     /**
190      * Construct a URI as an escaped form of a character array.
191      * An URI can be placed within double-quotes or angle brackets like 
192      * "http://test.com/" and &lt;http://test.com/&gt;
193      * 
194      * @param escaped the URI character sequence
195      * @throws URIException If the URI cannot be created.
196      * @throws NullPointerException if <code>escaped</code> is <code>null</code>
197      * @see #getDefaultProtocolCharset
198      * 
199      * @deprecated Use #URI(String, boolean)
200      */
201     public URI(char[] escaped) 
202         throws URIException, NullPointerException {
203         parseUriReference(new String(escaped), true);
204     }
205 
206 
207     /**
208      * Construct a URI from the given string with the given charset.
209      *
210      * @param original the string to be represented to URI character sequence
211      * It is one of absoluteURI and relativeURI.
212      * @param charset the charset string to do escape encoding
213      * @throws URIException If the URI cannot be created.
214      * @see #getProtocolCharset
215      * 
216      * @deprecated Use #URI(String, boolean, String)
217      */
218     public URI(String original, String charset) throws URIException {
219         protocolCharset = charset;
220         parseUriReference(original, false);
221     }
222 
223 
224     /**
225      * Construct a URI from the given string.
226      * <p><blockquote><pre>
227      *   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
228      * </pre></blockquote><p>
229      * An URI can be placed within double-quotes or angle brackets like 
230      * "http://test.com/" and &lt;http://test.com/&gt;
231      *
232      * @param original the string to be represented to URI character sequence
233      * It is one of absoluteURI and relativeURI.
234      * @throws URIException If the URI cannot be created.
235      * @see #getDefaultProtocolCharset
236      * 
237      * @deprecated Use #URI(String, boolean)
238      */
239     public URI(String original) throws URIException {
240         parseUriReference(original, false);
241     }
242 
243 
244     /**
245      * Construct a general URI from the given components.
246      * <p><blockquote><pre>
247      *   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
248      *   absoluteURI   = scheme ":" ( hier_part | opaque_part )
249      *   opaque_part   = uric_no_slash *uric
250      * </pre></blockquote><p>
251      * It's for absolute URI = &lt;scheme&gt;:&lt;scheme-specific-part&gt;#
252      * &lt;fragment&gt;.
253      *
254      * @param scheme the scheme string
255      * @param schemeSpecificPart scheme_specific_part
256      * @param fragment the fragment string
257      * @throws URIException If the URI cannot be created.
258      * @see #getDefaultProtocolCharset
259      */
260     public URI(String scheme, String schemeSpecificPart, String fragment)
261         throws URIException {
262 
263         // validate and contruct the URI character sequence
264         if (scheme == null) {
265            throw new URIException(URIException.PARSING, "scheme required");
266         }
267         char[] s = scheme.toLowerCase().toCharArray();
268         if (validate(s, URI.scheme)) {
269             _scheme = s; // is_absoluteURI
270         } else {
271             throw new URIException(URIException.PARSING, "incorrect scheme");
272         }
273         _opaque = encode(schemeSpecificPart, allowed_opaque_part,
274                 getProtocolCharset());
275         // Set flag
276         _is_opaque_part = true;
277         _fragment = fragment == null ? null : fragment.toCharArray(); 
278         setURI();
279     }
280 
281 
282     /**
283      * Construct a general URI from the given components.
284      * <p><blockquote><pre>
285      *   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
286      *   absoluteURI   = scheme ":" ( hier_part | opaque_part )
287      *   relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
288      *   hier_part     = ( net_path | abs_path ) [ "?" query ]
289      * </pre></blockquote><p>
290      * It's for absolute URI = &lt;scheme&gt;:&lt;path&gt;?&lt;query&gt;#&lt;
291      * fragment&gt; and relative URI = &lt;path&gt;?&lt;query&gt;#&lt;fragment
292      * &gt;.
293      *
294      * @param scheme the scheme string
295      * @param authority the authority string
296      * @param path the path string
297      * @param query the query string
298      * @param fragment the fragment string
299      * @throws URIException If the new URI cannot be created.
300      * @see #getDefaultProtocolCharset
301      */
302     public URI(String scheme, String authority, String path, String query,
303                String fragment) throws URIException {
304 
305         // validate and contruct the URI character sequence
306         StringBuffer buff = new StringBuffer();
307         if (scheme != null) {
308             buff.append(scheme);
309             buff.append(':');
310         }
311         if (authority != null) {
312             buff.append("//");
313             buff.append(authority);
314         }
315         if (path != null) {  // accept empty path
316             if ((scheme != null || authority != null)
317                     && !path.startsWith("/")) {
318                 throw new URIException(URIException.PARSING,
319                         "abs_path requested");
320             }
321             buff.append(path);
322         }
323         if (query != null) {
324             buff.append('?');
325             buff.append(query);
326         }
327         if (fragment != null) {
328             buff.append('#');
329             buff.append(fragment);
330         }
331         parseUriReference(buff.toString(), false);
332     }
333 
334 
335     /**
336      * Construct a general URI from the given components.
337      *
338      * @param scheme the scheme string
339      * @param userinfo the userinfo string
340      * @param host the host string
341      * @param port the port number
342      * @throws URIException If the new URI cannot be created.
343      * @see #getDefaultProtocolCharset
344      */
345     public URI(String scheme, String userinfo, String host, int port)
346         throws URIException {
347 
348         this(scheme, userinfo, host, port, null, null, null);
349     }
350 
351 
352     /**
353      * Construct a general URI from the given components.
354      *
355      * @param scheme the scheme string
356      * @param userinfo the userinfo string
357      * @param host the host string
358      * @param port the port number
359      * @param path the path string
360      * @throws URIException If the new URI cannot be created.
361      * @see #getDefaultProtocolCharset
362      */
363     public URI(String scheme, String userinfo, String host, int port,
364             String path) throws URIException {
365 
366         this(scheme, userinfo, host, port, path, null, null);
367     }
368 
369 
370     /**
371      * Construct a general URI from the given components.
372      *
373      * @param scheme the scheme string
374      * @param userinfo the userinfo string
375      * @param host the host string
376      * @param port the port number
377      * @param path the path string
378      * @param query the query string
379      * @throws URIException If the new URI cannot be created.
380      * @see #getDefaultProtocolCharset
381      */
382     public URI(String scheme, String userinfo, String host, int port,
383             String path, String query) throws URIException {
384 
385         this(scheme, userinfo, host, port, path, query, null);
386     }
387 
388 
389     /**
390      * Construct a general URI from the given components.
391      *
392      * @param scheme the scheme string
393      * @param userinfo the userinfo string
394      * @param host the host string
395      * @param port the port number
396      * @param path the path string
397      * @param query the query string
398      * @param fragment the fragment string
399      * @throws URIException If the new URI cannot be created.
400      * @see #getDefaultProtocolCharset
401      */
402     public URI(String scheme, String userinfo, String host, int port,
403             String path, String query, String fragment) throws URIException {
404 
405         this(scheme, (host == null) ? null 
406             : ((userinfo != null) ? userinfo + '@' : "") + host 
407                 + ((port != -1) ? ":" + port : ""), path, query, fragment);
408     }
409 
410 
411     /**
412      * Construct a general URI from the given components.
413      *
414      * @param scheme the scheme string
415      * @param host the host string
416      * @param path the path string
417      * @param fragment the fragment string
418      * @throws URIException If the new URI cannot be created.
419      * @see #getDefaultProtocolCharset
420      */
421     public URI(String scheme, String host, String path, String fragment)
422         throws URIException {
423 
424         this(scheme, host, path, null, fragment);
425     }
426 
427 
428     /**
429      * Construct a general URI with the given relative URI string.
430      *
431      * @param base the base URI
432      * @param relative the relative URI string
433      * @throws URIException If the new URI cannot be created.
434      * 
435      * @deprecated Use #URI(URI, String, boolean)
436      */
437     public URI(URI base, String relative) throws URIException {
438         this(base, new URI(relative));
439     }
440 
441 
442     /**
443      * Construct a general URI with the given relative URI string.
444      *
445      * @param base the base URI
446      * @param relative the relative URI string
447      * @param escaped <tt>true</tt> if URI character sequence is in escaped form. 
448      *                <tt>false</tt> otherwise.
449      *  
450      * @throws URIException If the new URI cannot be created.
451      * 
452      * @since 3.0
453      */
454     public URI(URI base, String relative, boolean escaped) throws URIException {
455         this(base, new URI(relative, escaped));
456     }
457 
458 
459     /**
460      * Construct a general URI with the given relative URI.
461      * <p><blockquote><pre>
462      *   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
463      *   relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
464      * </pre></blockquote><p>
465      * Resolving Relative References to Absolute Form.
466      *
467      * <strong>Examples of Resolving Relative URI References</strong>
468      *
469      * Within an object with a well-defined base URI of
470      * <p><blockquote><pre>
471      *   http://a/b/c/d;p?q
472      * </pre></blockquote><p>
473      * the relative URI would be resolved as follows:
474      *
475      * Normal Examples
476      *
477      * <p><blockquote><pre>
478      *   g:h           =  g:h
479      *   g             =  http://a/b/c/g
480      *   ./g           =  http://a/b/c/g
481      *   g/            =  http://a/b/c/g/
482      *   /g            =  http://a/g
483      *   //g           =  http://g
484      *   ?y            =  http://a/b/c/?y
485      *   g?y           =  http://a/b/c/g?y
486      *   #s            =  (current document)#s
487      *   g#s           =  http://a/b/c/g#s
488      *   g?y#s         =  http://a/b/c/g?y#s
489      *   ;x            =  http://a/b/c/;x
490      *   g;x           =  http://a/b/c/g;x
491      *   g;x?y#s       =  http://a/b/c/g;x?y#s
492      *   .             =  http://a/b/c/
493      *   ./            =  http://a/b/c/
494      *   ..            =  http://a/b/
495      *   ../           =  http://a/b/
496      *   ../g          =  http://a/b/g
497      *   ../..         =  http://a/
498      *   ../../        =  http://a/ 
499      *   ../../g       =  http://a/g
500      * </pre></blockquote><p>
501      *
502      * Some URI schemes do not allow a hierarchical syntax matching the
503      * <hier_part> syntax, and thus cannot use relative references.
504      *
505      * @param base the base URI
506      * @param relative the relative URI
507      * @throws URIException If the new URI cannot be created.
508      */
509     public URI(URI base, URI relative) throws URIException {
510 
511         if (base._scheme == null) {
512             throw new URIException(URIException.PARSING, "base URI required");
513         }
514         if (base._scheme != null) {
515             this._scheme = base._scheme;
516             this._authority = base._authority;
517             this._is_net_path = base._is_net_path; 
518         }
519         if (base._is_opaque_part || relative._is_opaque_part) {
520             this._scheme = base._scheme;
521             this._is_opaque_part = base._is_opaque_part 
522                 || relative._is_opaque_part;
523             this._opaque = relative._opaque;
524             this._fragment = relative._fragment;
525             this.setURI();
526             return;
527         }
528         boolean schemesEqual = Arrays.equals(base._scheme,relative._scheme);
529         if (relative._scheme != null 
530                 && (!schemesEqual  || relative._authority != null)) {
531             this._scheme = relative._scheme;
532             this._is_net_path = relative._is_net_path;
533             this._authority = relative._authority;
534             if (relative._is_server) {
535                 this._is_server = relative._is_server;
536                 this._userinfo = relative._userinfo;
537                 this._host = relative._host;
538                 this._port = relative._port;
539             } else if (relative._is_reg_name) {
540                 this._is_reg_name = relative._is_reg_name;
541             }
542             this._is_abs_path = relative._is_abs_path;
543             this._is_rel_path = relative._is_rel_path;
544             this._path = relative._path;
545         } else if (base._authority != null && relative._scheme == null) {
546             this._is_net_path = base._is_net_path;
547             this._authority = base._authority;
548             if (base._is_server) {
549                 this._is_server = base._is_server;
550                 this._userinfo = base._userinfo;
551                 this._host = base._host;
552                 this._port = base._port;
553             } else if (base._is_reg_name) {
554                 this._is_reg_name = base._is_reg_name;
555             }
556         }
557         if (relative._authority != null) {
558             this._is_net_path = relative._is_net_path;
559             this._authority = relative._authority;
560             if (relative._is_server) {
561                 this._is_server = relative._is_server;
562                 this._userinfo = relative._userinfo;
563                 this._host = relative._host;
564                 this._port = relative._port;
565             } else if (relative._is_reg_name) {
566                 this._is_reg_name = relative._is_reg_name;
567             }
568             this._is_abs_path = relative._is_abs_path;
569             this._is_rel_path = relative._is_rel_path;
570             this._path = relative._path;
571         }
572         // resolve the path and query if necessary
573         if (relative._authority == null 
574             && (relative._scheme == null || schemesEqual)) {
575             if ((relative._path == null || relative._path.length == 0)
576                 && relative._query == null) {
577                 // handle a reference to the current document, see RFC 2396 
578                 // section 5.2 step 2
579                 this._path = base._path;
580                 this._query = base._query;
581             } else {
582                 this._path = resolvePath(base._path, relative._path);
583             }
584         }
585         // base._query removed
586         if (relative._query != null) {
587             this._query = relative._query;
588         }
589         // base._fragment removed
590         if (relative._fragment != null) {
591             this._fragment = relative._fragment;
592         }
593         this.setURI();
594         // reparse the newly built URI, this will ensure that all flags are set correctly.
595         // TODO there must be a better way to do this
596         parseUriReference(new String(_uri), true);
597     }
598 
599     // --------------------------------------------------- Instance Variables
600 
601     /** Version ID for serialization */
602     static final long serialVersionUID = 604752400577948726L;
603 
604 
605     /**
606      * Cache the hash code for this URI.
607      */
608     protected int hash = 0;
609 
610 
611     /**
612      * This Uniform Resource Identifier (URI).
613      * The URI is always in an "escaped" form, since escaping or unescaping
614      * a completed URI might change its semantics.  
615      */
616     protected char[] _uri = null;
617 
618 
619     /**
620      * The charset of the protocol used by this URI instance.
621      */
622     protected String protocolCharset = null;
623 
624 
625     /**
626      * The default charset of the protocol.  RFC 2277, 2396
627      */
628     protected static String defaultProtocolCharset = "UTF-8";
629 
630 
631     /**
632      * The default charset of the document.  RFC 2277, 2396
633      * The platform's charset is used for the document by default.
634      */
635     protected static String defaultDocumentCharset = null;
636     protected static String defaultDocumentCharsetByLocale = null;
637     protected static String defaultDocumentCharsetByPlatform = null;
638     // Static initializer for defaultDocumentCharset
639     static {
640         Locale locale = Locale.getDefault();
641         // in order to support backward compatiblity
642         if (locale != null) {
643             defaultDocumentCharsetByLocale =
644                 LocaleToCharsetMap.getCharset(locale);
645             // set the default document charset
646             defaultDocumentCharset = defaultDocumentCharsetByLocale;
647         }
648         // in order to support platform encoding
649         try {
650             defaultDocumentCharsetByPlatform = System.getProperty("file.encoding");
651         } catch (SecurityException ignore) {
652         }
653         if (defaultDocumentCharset == null) {
654             // set the default document charset
655             defaultDocumentCharset = defaultDocumentCharsetByPlatform;
656         }
657     }
658 
659 
660     /**
661      * The scheme.
662      */
663     protected char[] _scheme = null;
664 
665 
666     /**
667      * The opaque.
668      */
669     protected char[] _opaque = null;
670 
671 
672     /**
673      * The authority.
674      */
675     protected char[] _authority = null;
676 
677 
678     /**
679      * The userinfo.
680      */
681     protected char[] _userinfo = null;
682 
683 
684     /**
685      * The host.
686      */
687     protected char[] _host = null;
688 
689 
690     /**
691      * The port.
692      */
693     protected int _port = -1;
694 
695 
696     /**
697      * The path.
698      */
699     protected char[] _path = null;
700 
701 
702     /**
703      * The query.
704      */
705     protected char[] _query = null;
706 
707 
708     /**
709      * The fragment.
710      */
711     protected char[] _fragment = null;
712 
713 
714     /**
715      * The root path.
716      */
717     protected static final char[] rootPath = { '/' };
718 
719     // ---------------------- Generous characters for each component validation
720 
721     /**
722      * The percent "%" character always has the reserved purpose of being the
723      * escape indicator, it must be escaped as "%25" in order to be used as
724      * data within a URI.
725      */
726     protected static final BitSet percent = new BitSet(256);
727     // Static initializer for percent
728     static {
729         percent.set('%');
730     }
731 
732 
733     /**
734      * BitSet for digit.
735      * <p><blockquote><pre>
736      * digit    = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
737      *            "8" | "9"
738      * </pre></blockquote><p>
739      */
740     protected static final BitSet digit = new BitSet(256);
741     // Static initializer for digit
742     static {
743         for (int i = '0'; i <= '9'; i++) {
744             digit.set(i);
745         }
746     }
747 
748 
749     /**
750      * BitSet for alpha.
751      * <p><blockquote><pre>
752      * alpha         = lowalpha | upalpha
753      * </pre></blockquote><p>
754      */
755     protected static final BitSet alpha = new BitSet(256);
756     // Static initializer for alpha
757     static {
758         for (int i = 'a'; i <= 'z'; i++) {
759             alpha.set(i);
760         }
761         for (int i = 'A'; i <= 'Z'; i++) {
762             alpha.set(i);
763         }
764     }
765 
766 
767     /**
768      * BitSet for alphanum (join of alpha &amp; digit).
769      * <p><blockquote><pre>
770      *  alphanum      = alpha | digit
771      * </pre></blockquote><p>
772      */
773     protected static final BitSet alphanum = new BitSet(256);
774     // Static initializer for alphanum
775     static {
776         alphanum.or(alpha);
777         alphanum.or(digit);
778     }
779 
780 
781     /**
782      * BitSet for hex.
783      * <p><blockquote><pre>
784      * hex           = digit | "A" | "B" | "C" | "D" | "E" | "F" |
785      *                         "a" | "b" | "c" | "d" | "e" | "f"
786      * </pre></blockquote><p>
787      */
788     protected static final BitSet hex = new BitSet(256);
789     // Static initializer for hex
790     static {
791         hex.or(digit);
792         for (int i = 'a'; i <= 'f'; i++) {
793             hex.set(i);
794         }
795         for (int i = 'A'; i <= 'F'; i++) {
796             hex.set(i);
797         }
798     }
799 
800 
801     /**
802      * BitSet for escaped.
803      * <p><blockquote><pre>
804      * escaped       = "%" hex hex
805      * </pre></blockquote><p>
806      */
807     protected static final BitSet escaped = new BitSet(256);
808     // Static initializer for escaped
809     static {
810         escaped.or(percent);
811         escaped.or(hex);
812     }
813 
814 
815     /**
816      * BitSet for mark.
817      * <p><blockquote><pre>
818      * mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
819      *                 "(" | ")"
820      * </pre></blockquote><p>
821      */
822     protected static final BitSet mark = new BitSet(256);
823     // Static initializer for mark
824     static {
825         mark.set('-');
826         mark.set('_');
827         mark.set('.');
828         mark.set('!');
829         mark.set('~');
830         mark.set('*');
831         mark.set('\'');
832         mark.set('(');
833         mark.set(')');
834     }
835 
836 
837     /**
838      * Data characters that are allowed in a URI but do not have a reserved
839      * purpose are called unreserved.
840      * <p><blockquote><pre>
841      * unreserved    = alphanum | mark
842      * </pre></blockquote><p>
843      */
844     protected static final BitSet unreserved = new BitSet(256);
845     // Static initializer for unreserved
846     static {
847         unreserved.or(alphanum);
848         unreserved.or(mark);
849     }
850 
851 
852     /**
853      * BitSet for reserved.
854      * <p><blockquote><pre>
855      * reserved      = ";" | "/" | "?" | ":" | "@" | "&amp;" | "=" | "+" |
856      *                 "$" | ","
857      * </pre></blockquote><p>
858      */
859     protected static final BitSet reserved = new BitSet(256);
860     // Static initializer for reserved
861     static {
862         reserved.set(';');
863         reserved.set('/');
864         reserved.set('?');
865         reserved.set(':');
866         reserved.set('@');
867         reserved.set('&');
868         reserved.set('=');
869         reserved.set('+');
870         reserved.set('$');
871         reserved.set(',');
872     }
873 
874 
875     /**
876      * BitSet for uric.
877      * <p><blockquote><pre>
878      * uric          = reserved | unreserved | escaped
879      * </pre></blockquote><p>
880      */
881     protected static final BitSet uric = new BitSet(256);
882     // Static initializer for uric
883     static {
884         uric.or(reserved);
885         uric.or(unreserved);
886         uric.or(escaped);
887     }
888 
889 
890     /**
891      * BitSet for fragment (alias for uric).
892      * <p><blockquote><pre>
893      * fragment      = *uric
894      * </pre></blockquote><p>
895      */
896     protected static final BitSet fragment = uric;
897 
898 
899     /**
900      * BitSet for query (alias for uric).
901      * <p><blockquote><pre>
902      * query         = *uric
903      * </pre></blockquote><p>
904      */
905     protected static final BitSet query = uric;
906 
907 
908     /**
909      * BitSet for pchar.
910      * <p><blockquote><pre>
911      * pchar         = unreserved | escaped |
912      *                 ":" | "@" | "&amp;" | "=" | "+" | "$" | ","
913      * </pre></blockquote><p>
914      */
915     protected static final BitSet pchar = new BitSet(256);
916     // Static initializer for pchar
917     static {
918         pchar.or(unreserved);
919         pchar.or(escaped);
920         pchar.set(':');
921         pchar.set('@');
922         pchar.set('&');
923         pchar.set('=');
924         pchar.set('+');
925         pchar.set('$');
926         pchar.set(',');
927     }
928 
929 
930     /**
931      * BitSet for param (alias for pchar).
932      * <p><blockquote><pre>
933      * param         = *pchar
934      * </pre></blockquote><p>
935      */
936     protected static final BitSet param = pchar;
937 
938 
939     /**
940      * BitSet for segment.
941      * <p><blockquote><pre>
942      * segment       = *pchar *( ";" param )
943      * </pre></blockquote><p>
944      */
945     protected static final BitSet segment = new BitSet(256);
946     // Static initializer for segment
947     static {
948         segment.or(pchar);
949         segment.set(';');
950         segment.or(param);
951     }
952 
953 
954     /**
955      * BitSet for path segments.
956      * <p><blockquote><pre>
957      * path_segments = segment *( "/" segment )
958      * </pre></blockquote><p>
959      */
960     protected static final BitSet path_segments = new BitSet(256);
961     // Static initializer for path_segments
962     static {
963         path_segments.set('/');
964         path_segments.or(segment);
965     }
966 
967 
968     /**
969      * URI absolute path.
970      * <p><blockquote><pre>
971      * abs_path      = "/"  path_segments
972      * </pre></blockquote><p>
973      */
974     protected static final BitSet abs_path = new BitSet(256);
975     // Static initializer for abs_path
976     static {
977         abs_path.set('/');
978         abs_path.or(path_segments);
979     }
980 
981 
982     /**
983      * URI bitset for encoding typical non-slash characters.
984      * <p><blockquote><pre>
985      * uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
986      *                 "&amp;" | "=" | "+" | "$" | ","
987      * </pre></blockquote><p>
988      */
989     protected static final BitSet uric_no_slash = new BitSet(256);
990     // Static initializer for uric_no_slash
991     static {
992         uric_no_slash.or(unreserved);
993         uric_no_slash.or(escaped);
994         uric_no_slash.set(';');
995         uric_no_slash.set('?');
996         uric_no_slash.set(';');
997         uric_no_slash.set('@');
998         uric_no_slash.set('&');
999         uric_no_slash.set('=');
1000         uric_no_slash.set('+');
1001         uric_no_slash.set('$');
1002         uric_no_slash.set(',');
1003     }
1004     
1005 
1006     /**
1007      * URI bitset that combines uric_no_slash and uric.
1008      * <p><blockquote><pre>
1009      * opaque_part   = uric_no_slash *uric
1010      * </pre></blockquote><p>
1011      */
1012     protected static final BitSet opaque_part = new BitSet(256);
1013     // Static initializer for opaque_part
1014     static {
1015         // it's generous. because first character must not include a slash
1016         opaque_part.or(uric_no_slash);
1017         opaque_part.or(uric);
1018     }
1019     
1020 
1021     /**
1022      * URI bitset that combines absolute path and opaque part.
1023      * <p><blockquote><pre>
1024      * path          = [ abs_path | opaque_part ]
1025      * </pre></blockquote><p>
1026      */
1027     protected static final BitSet path = new BitSet(256);
1028     // Static initializer for path
1029     static {
1030         path.or(abs_path);
1031         path.or(opaque_part);
1032     }
1033 
1034 
1035     /**
1036      * Port, a logical alias for digit.
1037      */
1038     protected static final BitSet port = digit;
1039 
1040 
1041     /**
1042      * Bitset that combines digit and dot fo IPv$address.
1043      * <p><blockquote><pre>
1044      * IPv4address   = 1*digit "." 1*digit "." 1*digit "." 1*digit
1045      * </pre></blockquote><p>
1046      */
1047     protected static final BitSet IPv4address = new BitSet(256);
1048     // Static initializer for IPv4address
1049     static {
1050         IPv4address.or(digit);
1051         IPv4address.set('.');
1052     }
1053 
1054 
1055     /**
1056      * RFC 2373.
1057      * <p><blockquote><pre>
1058      * IPv6address = hexpart [ ":" IPv4address ]
1059      * </pre></blockquote><p>
1060      */
1061     protected static final BitSet IPv6address = new BitSet(256);
1062     // Static initializer for IPv6address reference
1063     static {
1064         IPv6address.or(hex); // hexpart
1065         IPv6address.set(':');
1066         IPv6address.or(IPv4address);
1067     }
1068 
1069 
1070     /**
1071      * RFC 2732, 2373.
1072      * <p><blockquote><pre>
1073      * IPv6reference   = "[" IPv6address "]"
1074      * </pre></blockquote><p>
1075      */
1076     protected static final BitSet IPv6reference = new BitSet(256);
1077     // Static initializer for IPv6reference
1078     static {
1079         IPv6reference.set('[');
1080         IPv6reference.or(IPv6address);
1081         IPv6reference.set(']');
1082     }
1083 
1084 
1085     /**
1086      * BitSet for toplabel.
1087      * <p><blockquote><pre>
1088      * toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
1089      * </pre></blockquote><p>
1090      */
1091     protected static final BitSet toplabel = new BitSet(256);
1092     // Static initializer for toplabel
1093     static {
1094         toplabel.or(alphanum);
1095         toplabel.set('-');
1096     }
1097 
1098 
1099     /**
1100      * BitSet for domainlabel.
1101      * <p><blockquote><pre>
1102      * domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
1103      * </pre></blockquote><p>
1104      */
1105     protected static final BitSet domainlabel = toplabel;
1106 
1107 
1108     /**
1109      * BitSet for hostname.
1110      * <p><blockquote><pre>
1111      * hostname      = *( domainlabel "." ) toplabel [ "." ]
1112      * </pre></blockquote><p>
1113      */
1114     protected static final BitSet hostname = new BitSet(256);
1115     // Static initializer for hostname
1116     static {
1117         hostname.or(toplabel);
1118         // hostname.or(domainlabel);
1119         hostname.set('.');
1120     }
1121 
1122 
1123     /**
1124      * BitSet for host.
1125      * <p><blockquote><pre>
1126      * host          = hostname | IPv4address | IPv6reference
1127      * </pre></blockquote><p>
1128      */
1129     protected static final BitSet host = new BitSet(256);
1130     // Static initializer for host
1131     static {
1132         host.or(hostname);
1133         // host.or(IPv4address);
1134         host.or(IPv6reference); // IPv4address
1135     }
1136 
1137 
1138     /**
1139      * BitSet for hostport.
1140      * <p><blockquote><pre>
1141      * hostport      = host [ ":" port ]
1142      * </pre></blockquote><p>
1143      */
1144     protected static final BitSet hostport = new BitSet(256);
1145     // Static initializer for hostport
1146     static {
1147         hostport.or(host);
1148         hostport.set(':');
1149         hostport.or(port);
1150     }
1151 
1152 
1153     /**
1154      * Bitset for userinfo.
1155      * <p><blockquote><pre>
1156      * userinfo      = *( unreserved | escaped |
1157      *                    ";" | ":" | "&amp;" | "=" | "+" | "$" | "," )
1158      * </pre></blockquote><p>
1159      */
1160     protected static final BitSet userinfo = new BitSet(256);
1161     // Static initializer for userinfo
1162     static {
1163         userinfo.or(unreserved);
1164         userinfo.or(escaped);
1165         userinfo.set(';');
1166         userinfo.set(':');
1167         userinfo.set('&');
1168         userinfo.set('=');
1169         userinfo.set('+');
1170         userinfo.set('$');
1171         userinfo.set(',');
1172     }
1173 
1174 
1175     /**
1176      * BitSet for within the userinfo component like user and password.
1177      */
1178     public static final BitSet within_userinfo = new BitSet(256);
1179     // Static initializer for within_userinfo
1180     static {
1181         within_userinfo.or(userinfo);
1182         within_userinfo.clear(';'); // reserved within authority
1183         within_userinfo.clear(':');
1184         within_userinfo.clear('@');
1185         within_userinfo.clear('?');
1186         within_userinfo.clear('/');
1187     }
1188 
1189 
1190     /**
1191      * Bitset for server.
1192      * <p><blockquote><pre>
1193      * server        = [ [ userinfo "@" ] hostport ]
1194      * </pre></blockquote><p>
1195      */
1196     protected static final BitSet server = new BitSet(256);
1197     // Static initializer for server
1198     static {
1199         server.or(userinfo);
1200         server.set('@');
1201         server.or(hostport);
1202     }
1203 
1204 
1205     /**
1206      * BitSet for reg_name.
1207      * <p><blockquote><pre>
1208      * reg_name      = 1*( unreserved | escaped | "$" | "," |
1209      *                     ";" | ":" | "@" | "&amp;" | "=" | "+" )
1210      * </pre></blockquote><p>
1211      */
1212     protected static final BitSet reg_name = new BitSet(256);
1213     // Static initializer for reg_name
1214     static {
1215         reg_name.or(unreserved);
1216         reg_name.or(escaped);
1217         reg_name.set('$');
1218         reg_name.set(',');
1219         reg_name.set(';');
1220         reg_name.set(':');
1221         reg_name.set('@');
1222         reg_name.set('&');
1223         reg_name.set('=');
1224         reg_name.set('+');
1225     }
1226 
1227 
1228     /**
1229      * BitSet for authority.
1230      * <p><blockquote><pre>
1231      * authority     = server | reg_name
1232      * </pre></blockquote><p>
1233      */
1234     protected static final BitSet authority = new BitSet(256);
1235     // Static initializer for authority
1236     static {
1237         authority.or(server);
1238         authority.or(reg_name);
1239     }
1240 
1241 
1242     /**
1243      * BitSet for scheme.
1244      * <p><blockquote><pre>
1245      * scheme        = alpha *( alpha | digit | "+" | "-" | "." )
1246      * </pre></blockquote><p>
1247      */
1248     protected static final BitSet scheme = new BitSet(256);
1249     // Static initializer for scheme
1250     static {
1251         scheme.or(alpha);
1252         scheme.or(digit);
1253         scheme.set('+');
1254         scheme.set('-');
1255         scheme.set('.');
1256     }
1257 
1258 
1259     /**
1260      * BitSet for rel_segment.
1261      * <p><blockquote><pre>
1262      * rel_segment   = 1*( unreserved | escaped |
1263      *                     ";" | "@" | "&amp;" | "=" | "+" | "$" | "," )
1264      * </pre></blockquote><p>
1265      */
1266     protected static final BitSet rel_segment = new BitSet(256);
1267     // Static initializer for rel_segment
1268     static {
1269         rel_segment.or(unreserved);
1270         rel_segment.or(escaped);
1271         rel_segment.set(';');
1272         rel_segment.set('@');
1273         rel_segment.set('&');
1274         rel_segment.set('=');
1275         rel_segment.set('+');
1276         rel_segment.set('$');
1277         rel_segment.set(',');
1278     }
1279 
1280 
1281     /**
1282      * BitSet for rel_path.
1283      * <p><blockquote><pre>
1284      * rel_path      = rel_segment [ abs_path ]
1285      * </pre></blockquote><p>
1286      */
1287     protected static final BitSet rel_path = new BitSet(256);
1288     // Static initializer for rel_path
1289     static {
1290         rel_path.or(rel_segment);
1291         rel_path.or(abs_path);
1292     }
1293 
1294 
1295     /**
1296      * BitSet for net_path.
1297      * <p><blockquote><pre>
1298      * net_path      = "//" authority [ abs_path ]
1299      * </pre></blockquote><p>
1300      */
1301     protected static final BitSet net_path = new BitSet(256);
1302     // Static initializer for net_path
1303     static {
1304         net_path.set('/');
1305         net_path.or(authority);
1306         net_path.or(abs_path);
1307     }
1308     
1309 
1310     /**
1311      * BitSet for hier_part.
1312      * <p><blockquote><pre>
1313      * hier_part     = ( net_path | abs_path ) [ "?" query ]
1314      * </pre></blockquote><p>
1315      */
1316     protected static final BitSet hier_part = new BitSet(256);
1317     // Static initializer for hier_part
1318     static {
1319         hier_part.or(net_path);
1320         hier_part.or(abs_path);
1321         // hier_part.set('?'); aleady included
1322         hier_part.or(query);
1323     }
1324 
1325 
1326     /**
1327      * BitSet for relativeURI.
1328      * <p><blockquote><pre>
1329      * relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
1330      * </pre></blockquote><p>
1331      */
1332     protected static final BitSet relativeURI = new BitSet(256);
1333     // Static initializer for relativeURI
1334     static {
1335         relativeURI.or(net_path);
1336         relativeURI.or(abs_path);
1337         relativeURI.or(rel_path);
1338         // relativeURI.set('?'); aleady included
1339         relativeURI.or(query);
1340     }
1341 
1342 
1343     /**
1344      * BitSet for absoluteURI.
1345      * <p><blockquote><pre>
1346      * absoluteURI   = scheme ":" ( hier_part | opaque_part )
1347      * </pre></blockquote><p>
1348      */
1349     protected static final BitSet absoluteURI = new BitSet(256);
1350     // Static initializer for absoluteURI
1351     static {
1352         absoluteURI.or(scheme);
1353         absoluteURI.set(':');
1354         absoluteURI.or(hier_part);
1355         absoluteURI.or(opaque_part);
1356     }
1357 
1358 
1359     /**
1360      * BitSet for URI-reference.
1361      * <p><blockquote><pre>
1362      * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
1363      * </pre></blockquote><p>
1364      */
1365     protected static final BitSet URI_reference = new BitSet(256);
1366     // Static initializer for URI_reference
1367     static {
1368         URI_reference.or(absoluteURI);
1369         URI_reference.or(relativeURI);
1370         URI_reference.set('#');
1371         URI_reference.or(fragment);
1372     }
1373 
1374     // ---------------------------- Characters disallowed within the URI syntax
1375     // Excluded US-ASCII Characters are like control, space, delims and unwise
1376 
1377     /**
1378      * BitSet for control.
1379      */
1380     public static final BitSet control = new BitSet(256);
1381     // Static initializer for control
1382     static {
1383         for (int i = 0; i <= 0x1F; i++) {
1384             control.set(i);
1385         }
1386         control.set(0x7F);
1387     }
1388 
1389     /**
1390      * BitSet for space.
1391      */
1392     public static final BitSet space = new BitSet(256);
1393     // Static initializer for space
1394     static {
1395         space.set(0x20);
1396     }
1397 
1398 
1399     /**
1400      * BitSet for delims.
1401      */
1402     public static final BitSet delims = new BitSet(256);
1403     // Static initializer for delims
1404     static {
1405         delims.set('<');
1406         delims.set('>');
1407         delims.set('#');
1408         delims.set('%');
1409         delims.set('"');
1410     }
1411 
1412 
1413     /**
1414      * BitSet for unwise.
1415      */
1416     public static final BitSet unwise = new BitSet(256);
1417     // Static initializer for unwise
1418     static {
1419         unwise.set('{');
1420         unwise.set('}');
1421         unwise.set('|');
1422         unwise.set('\\');
1423         unwise.set('^');
1424         unwise.set('[');
1425         unwise.set(']');
1426         unwise.set('`');
1427     }
1428 
1429 
1430     /**
1431      * Disallowed rel_path before escaping.
1432      */
1433     public static final BitSet disallowed_rel_path = new BitSet(256);
1434     // Static initializer for disallowed_rel_path
1435     static {
1436         disallowed_rel_path.or(uric);
1437         disallowed_rel_path.andNot(rel_path);
1438     }
1439 
1440 
1441     /**
1442      * Disallowed opaque_part before escaping.
1443      */
1444     public static final BitSet disallowed_opaque_part = new BitSet(256);
1445     // Static initializer for disallowed_opaque_part
1446     static {
1447         disallowed_opaque_part.or(uric);
1448         disallowed_opaque_part.andNot(opaque_part);
1449     }
1450 
1451     // ----------------------- Characters allowed within and for each component
1452 
1453     /**
1454      * Those characters that are allowed for the authority component.
1455      */
1456     public static final BitSet allowed_authority = new BitSet(256);
1457     // Static initializer for allowed_authority
1458     static {
1459         allowed_authority.or(authority);
1460         allowed_authority.clear('%');
1461     }
1462 
1463 
1464     /**
1465      * Those characters that are allowed for the opaque_part.
1466      */
1467     public static final BitSet allowed_opaque_part = new BitSet(256);
1468     // Static initializer for allowed_opaque_part 
1469     static {
1470         allowed_opaque_part.or(opaque_part);
1471         allowed_opaque_part.clear('%');
1472     }
1473 
1474 
1475     /**
1476      * Those characters that are allowed for the reg_name.
1477      */
1478     public static final BitSet allowed_reg_name = new BitSet(256);
1479     // Static initializer for allowed_reg_name 
1480     static {
1481         allowed_reg_name.or(reg_name);
1482         // allowed_reg_name.andNot(percent);
1483         allowed_reg_name.clear('%');
1484     }
1485 
1486 
1487     /**
1488      * Those characters that are allowed for the userinfo component.
1489      */
1490     public static final BitSet allowed_userinfo = new BitSet(256);
1491     // Static initializer for allowed_userinfo
1492     static {
1493         allowed_userinfo.or(userinfo);
1494         // allowed_userinfo.andNot(percent);
1495         allowed_userinfo.clear('%');
1496     }
1497 
1498 
1499     /**
1500      * Those characters that are allowed for within the userinfo component.
1501      */
1502     public static final BitSet allowed_within_userinfo = new BitSet(256);
1503     // Static initializer for allowed_within_userinfo
1504     static {
1505         allowed_within_userinfo.or(within_userinfo);
1506         allowed_within_userinfo.clear('%');
1507     }
1508 
1509 
1510     /**
1511      * Those characters that are allowed for the IPv6reference component.
1512      * The characters '[', ']' in IPv6reference should be excluded.
1513      */
1514     public static final BitSet allowed_IPv6reference = new BitSet(256);
1515     // Static initializer for allowed_IPv6reference
1516     static {
1517         allowed_IPv6reference.or(IPv6reference);
1518         // allowed_IPv6reference.andNot(unwise);
1519         allowed_IPv6reference.clear('[');
1520         allowed_IPv6reference.clear(']');
1521     }
1522 
1523 
1524     /**
1525      * Those characters that are allowed for the host component.
1526      * The characters '[', ']' in IPv6reference should be excluded.
1527      */
1528     public static final BitSet allowed_host = new BitSet(256);
1529     // Static initializer for allowed_host
1530     static {
1531         allowed_host.or(hostname);
1532         allowed_host.or(allowed_IPv6reference);
1533     }
1534 
1535 
1536     /**
1537      * Those characters that are allowed for the authority component.
1538      */
1539     public static final BitSet allowed_within_authority = new BitSet(256);
1540     // Static initializer for allowed_within_authority
1541     static {
1542         allowed_within_authority.or(server);
1543         allowed_within_authority.or(reg_name);
1544         allowed_within_authority.clear(';');
1545         allowed_within_authority.clear(':');
1546         allowed_within_authority.clear('@');
1547         allowed_within_authority.clear('?');
1548         allowed_within_authority.clear('/');
1549     }
1550 
1551 
1552     /**
1553      * Those characters that are allowed for the abs_path.
1554      */
1555     public static final BitSet allowed_abs_path = new BitSet(256);
1556     // Static initializer for allowed_abs_path
1557     static {
1558         allowed_abs_path.or(abs_path);
1559         // allowed_abs_path.set('/');  // aleady included
1560         allowed_abs_path.andNot(percent);
1561         allowed_abs_path.clear('+');
1562     }
1563 
1564 
1565     /**
1566      * Those characters that are allowed for the rel_path.
1567      */
1568     public static final BitSet allowed_rel_path = new BitSet(256);
1569     // Static initializer for allowed_rel_path
1570     static {
1571         allowed_rel_path.or(rel_path);
1572         allowed_rel_path.clear('%');
1573         allowed_rel_path.clear('+');
1574     }
1575 
1576 
1577     /**
1578      * Those characters that are allowed within the path.
1579      */
1580     public static final BitSet allowed_within_path = new BitSet(256);
1581     // Static initializer for allowed_within_path
1582     static {
1583         allowed_within_path.or(abs_path);
1584         allowed_within_path.clear('/');
1585         allowed_within_path.clear(';');
1586         allowed_within_path.clear('=');
1587         allowed_within_path.clear('?');
1588     }
1589 
1590 
1591     /**
1592      * Those characters that are allowed for the query component.
1593      */
1594     public static final BitSet allowed_query = new BitSet(256);
1595     // Static initializer for allowed_query
1596     static {
1597         allowed_query.or(uric);
1598         allowed_query.clear('%');
1599     }
1600 
1601 
1602     /**
1603      * Those characters that are allowed within the query component.
1604      */
1605     public static final BitSet allowed_within_query = new BitSet(256);
1606     // Static initializer for allowed_within_query
1607     static {
1608         allowed_within_query.or(allowed_query);
1609         allowed_within_query.andNot(reserved); // excluded 'reserved'
1610     }
1611 
1612 
1613     /**
1614      * Those characters that are allowed for the fragment component.
1615      */
1616     public static final BitSet allowed_fragment = new BitSet(256);
1617     // Static initializer for allowed_fragment
1618     static {
1619         allowed_fragment.or(uric);
1620         allowed_fragment.clear('%');
1621     }
1622 
1623     // ------------------------------------------- Flags for this URI-reference
1624 
1625     // TODO: Figure out what all these variables are for and provide javadoc
1626 
1627     // URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
1628     // absoluteURI   = scheme ":" ( hier_part | opaque_part )
1629     protected boolean _is_hier_part;
1630     protected boolean _is_opaque_part;
1631     // relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ] 
1632     // hier_part     = ( net_path | abs_path ) [ "?" query ]
1633     protected boolean _is_net_path;
1634     protected boolean _is_abs_path;
1635     protected boolean _is_rel_path;
1636     // net_path      = "//" authority [ abs_path ] 
1637     // authority     = server | reg_name
1638     protected boolean _is_reg_name;
1639     protected boolean _is_server;  // = _has_server
1640     // server        = [ [ userinfo "@" ] hostport ]
1641     // host          = hostname | IPv4address | IPv6reference
1642     protected boolean _is_hostname;
1643     protected boolean _is_IPv4address;
1644     protected boolean _is_IPv6reference;
1645 
1646     // ------------------------------------------ Character and escape encoding
1647     
1648     /**
1649      * Encodes URI string.
1650      *
1651      * This is a two mapping, one from original characters to octets, and
1652      * subsequently a second from octets to URI characters:
1653      * <p><blockquote><pre>
1654      *   original character sequence->octet sequence->URI character sequence
1655      * </pre></blockquote><p>
1656      *
1657      * An escaped octet is encoded as a character triplet, consisting of the
1658      * percent character "%" followed by the two hexadecimal digits
1659      * representing the octet code. For example, "%20" is the escaped
1660      * encoding for the US-ASCII space character.
1661      * <p>
1662      * Conversion from the local filesystem character set to UTF-8 will
1663      * normally involve a two step process. First convert the local character
1664      * set to the UCS; then convert the UCS to UTF-8.
1665      * The first step in the process can be performed by maintaining a mapping
1666      * table that includes the local character set code and the corresponding
1667      * UCS code.
1668      * The next step is to convert the UCS character code to the UTF-8 encoding.
1669      * <p>
1670      * Mapping between vendor codepages can be done in a very similar manner
1671      * as described above.
1672      * <p>
1673      * The only time escape encodings can allowedly be made is when a URI is
1674      * being created from its component parts.  The escape and validate methods
1675      * are internally performed within this method.
1676      *
1677      * @param original the original character sequence
1678      * @param allowed those characters that are allowed within a component
1679      * @param charset the protocol charset
1680      * @return URI character sequence
1681      * @throws URIException null component or unsupported character encoding
1682      */
1683         
1684     protected static char[] encode(String original, BitSet allowed,
1685             String charset) throws URIException {
1686         if (original == null) {
1687             throw new IllegalArgumentException("Original string may not be null");
1688         }
1689         if (allowed == null) {
1690             throw new IllegalArgumentException("Allowed bitset may not be null");
1691         }
1692         byte[] rawdata = URLCodec.encodeUrl(allowed, EncodingUtil.getBytes(original, charset));
1693         return EncodingUtil.getAsciiString(rawdata).toCharArray();
1694     }
1695 
1696     /**
1697      * Decodes URI encoded string.
1698      *
1699      * This is a two mapping, one from URI characters to octets, and
1700      * subsequently a second from octets to original characters:
1701      * <p><blockquote><pre>
1702      *   URI character sequence->octet sequence->original character sequence
1703      * </pre></blockquote><p>
1704      *
1705      * A URI must be separated into its components before the escaped
1706      * characters within those components can be allowedly decoded.
1707      * <p>
1708      * Notice that there is a chance that URI characters that are non UTF-8
1709      * may be parsed as valid UTF-8.  A recent non-scientific analysis found
1710      * that EUC encoded Japanese words had a 2.7% false reading; SJIS had a
1711      * 0.0005% false reading; other encoding such as ASCII or KOI-8 have a 0%
1712      * false reading.
1713      * <p>
1714      * The percent "%" character always has the reserved purpose of being
1715      * the escape indicator, it must be escaped as "%25" in order to be used
1716      * as data within a URI.
1717      * <p>
1718      * The unescape method is internally performed within this method.
1719      *
1720      * @param component the URI character sequence
1721      * @param charset the protocol charset
1722      * @return original character sequence
1723      * @throws URIException incomplete trailing escape pattern or unsupported
1724      * character encoding
1725      */
1726     protected static String decode(char[] component, String charset) 
1727         throws URIException {
1728         if (component == null) {
1729             throw new IllegalArgumentException("Component array of chars may not be null");
1730         }
1731         return decode(new String(component), charset);
1732     }
1733 
1734     /**
1735      * Decodes URI encoded string.
1736      *
1737      * This is a two mapping, one from URI characters to octets, and
1738      * subsequently a second from octets to original characters:
1739      * <p><blockquote><pre>
1740      *   URI character sequence->octet sequence->original character sequence
1741      * </pre></blockquote><p>
1742      *
1743      * A URI must be separated into its components before the escaped
1744      * characters within those components can be allowedly decoded.
1745      * <p>
1746      * Notice that there is a chance that URI characters that are non UTF-8
1747      * may be parsed as valid UTF-8.  A recent non-scientific analysis found
1748      * that EUC encoded Japanese words had a 2.7% false reading; SJIS had a
1749      * 0.0005% false reading; other encoding such as ASCII or KOI-8 have a 0%
1750      * false reading.
1751      * <p>
1752      * The percent "%" character always has the reserved purpose of being
1753      * the escape indicator, it must be escaped as "%25" in order to be used
1754      * as data within a URI.
1755      * <p>
1756      * The unescape method is internally performed within this method.
1757      *
1758      * @param component the URI character sequence
1759      * @param charset the protocol charset
1760      * @return original character sequence
1761      * @throws URIException incomplete trailing escape pattern or unsupported
1762      * character encoding
1763      * 
1764      * @since 3.0
1765      */
1766     protected static String decode(String component, String charset) 
1767         throws URIException {
1768         if (component == null) {
1769             throw new IllegalArgumentException("Component array of chars may not be null");
1770         }
1771         byte[] rawdata = null;
1772         try { 
1773             rawdata = URLCodec.decodeUrl(EncodingUtil.getAsciiBytes(component));
1774         } catch (DecoderException e) {
1775             throw new URIException(e.getMessage());
1776         }
1777         return EncodingUtil.getString(rawdata, charset);
1778     }
1779     /**
1780      * Pre-validate the unescaped URI string within a specific component.
1781      *
1782      * @param component the component string within the component
1783      * @param disallowed those characters disallowed within the component
1784      * @return if true, it doesn't have the disallowed characters
1785      * if false, the component is undefined or an incorrect one
1786      */
1787     protected boolean prevalidate(String component, BitSet disallowed) {
1788         // prevalidate the given component by disallowed characters
1789         if (component == null) {
1790             return false; // undefined
1791         }
1792         char[] target = component.toCharArray();
1793         for (int i = 0; i < target.length; i++) {
1794             if (disallowed.get(target[i])) {
1795                 return false;
1796             }
1797         }
1798         return true;
1799     }
1800 
1801 
1802     /**
1803      * Validate the URI characters within a specific component.
1804      * The component must be performed after escape encoding. Or it doesn't
1805      * include escaped characters.
1806      *
1807      * @param component the characters sequence within the component
1808      * @param generous those characters that are allowed within a component
1809      * @return if true, it's the correct URI character sequence
1810      */
1811     protected boolean validate(char[] component, BitSet generous) {
1812         // validate each component by generous characters
1813         return validate(component, 0, -1, generous);
1814     }
1815 
1816 
1817     /**
1818      * Validate the URI characters within a specific component.
1819      * The component must be performed after escape encoding. Or it doesn't
1820      * include escaped characters.
1821      * <p>
1822      * It's not that much strict, generous.  The strict validation might be 
1823      * performed before being called this method.
1824      *
1825      * @param component the characters sequence within the component
1826      * @param soffset the starting offset of the given component
1827      * @param eoffset the ending offset of the given component
1828      * if -1, it means the length of the component
1829      * @param generous those characters that are allowed within a component
1830      * @return if true, it's the correct URI character sequence
1831      */
1832     protected boolean validate(char[] component, int soffset, int eoffset,
1833             BitSet generous) {
1834         // validate each component by generous characters
1835         if (eoffset == -1) {
1836             eoffset = component.length - 1;
1837         }
1838         for (int i = soffset; i <= eoffset; i++) {
1839             if (!generous.get(component[i])) { 
1840                 return false;
1841             }
1842         }
1843         return true;
1844     }
1845 
1846 
1847     /**
1848      * In order to avoid any possilbity of conflict with non-ASCII characters,
1849      * Parse a URI reference as a <code>String</code> with the character
1850      * encoding of the local system or the document.
1851      * <p>
1852      * The following line is the regular expression for breaking-down a URI
1853      * reference into its components.
1854      * <p><blockquote><pre>
1855      *   ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
1856      *    12            3  4          5       6  7        8 9
1857      * </pre></blockquote><p>
1858      * For example, matching the above expression to
1859      *   http://jakarta.apache.org/ietf/uri/#Related
1860      * results in the following subexpression matches:
1861      * <p><blockquote><pre>
1862      *               $1 = http:
1863      *  scheme    =  $2 = http
1864      *               $3 = //jakarta.apache.org
1865      *  authority =  $4 = jakarta.apache.org
1866      *  path      =  $5 = /ietf/uri/
1867      *               $6 = <undefined>
1868      *  query     =  $7 = <undefined>
1869      *               $8 = #Related
1870      *  fragment  =  $9 = Related
1871      * </pre></blockquote><p>
1872      *
1873      * @param original the original character sequence
1874      * @param escaped <code>true</code> if <code>original</code> is escaped
1875      * @throws URIException If an error occurs.
1876      */
1877     protected void parseUriReference(String original, boolean escaped)
1878         throws URIException {
1879 
1880         // validate and contruct the URI character sequence
1881         if (original == null) {
1882             throw new URIException("URI-Reference required");
1883         }
1884 
1885         /* @
1886          *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
1887          */
1888         String tmp = original.trim();
1889         
1890         /*
1891          * The length of the string sequence of characters.
1892          * It may not be equal to the length of the byte array.
1893          */
1894         int length = tmp.length();
1895 
1896         /*
1897          * Remove the delimiters like angle brackets around an URI.
1898          */
1899         if (length > 0) {
1900             char[] firstDelimiter = { tmp.charAt(0) };
1901             if (validate(firstDelimiter, delims)) {
1902                 if (length >= 2) {
1903                     char[] lastDelimiter = { tmp.charAt(length - 1) };
1904                     if (validate(lastDelimiter, delims)) {
1905                         tmp = tmp.substring(1, length - 1);
1906                         length = length - 2;
1907                     }
1908                 }
1909             }
1910         }
1911 
1912         /*
1913          * The starting index
1914          */
1915         int from = 0;
1916 
1917         /*
1918          * The test flag whether the URI is started from the path component.
1919          */
1920         boolean isStartedFromPath = false;
1921         int atColon = tmp.indexOf(':');
1922         int atSlash = tmp.indexOf('/');
1923         if ((atColon <= 0 && !tmp.startsWith("//"))
1924             || (atSlash >= 0 && atSlash < atColon)) {
1925             isStartedFromPath = true;
1926         }
1927 
1928         /*
1929          * <p><blockquote><pre>
1930          *     @@@@@@@@
1931          *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
1932          * </pre></blockquote><p>
1933          */
1934         int at = indexFirstOf(tmp, isStartedFromPath ? "/?#" : ":/?#", from);
1935         if (at == -1) { 
1936             at = 0;
1937         }
1938 
1939         /*
1940          * Parse the scheme.
1941          * <p><blockquote><pre>
1942          *  scheme    =  $2 = http
1943          *              @
1944          *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
1945          * </pre></blockquote><p>
1946          */
1947         if (at > 0 && at < length && tmp.charAt(at) == ':') {
1948             char[] target = tmp.substring(0, at).toLowerCase().toCharArray();
1949             if (validate(target, scheme)) {
1950                 _scheme = target;
1951             } else {
1952                 throw new URIException("incorrect scheme");
1953             }
1954             from = ++at;
1955         }
1956 
1957         /*
1958          * Parse the authority component.
1959          * <p><blockquote><pre>
1960          *  authority =  $4 = jakarta.apache.org
1961          *                  @@
1962          *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
1963          * </pre></blockquote><p>
1964          */
1965         // Reset flags
1966         _is_net_path = _is_abs_path = _is_rel_path = _is_hier_part = false;
1967         if (0 <= at && at < length && tmp.charAt(at) == '/') {
1968             // Set flag
1969             _is_hier_part = true;
1970             if (at + 2 < length && tmp.charAt(at + 1) == '/' 
1971                 && !isStartedFromPath) {
1972                 // the temporary index to start the search from
1973                 int next = indexFirstOf(tmp, "/?#", at + 2);
1974                 if (next == -1) {
1975                     next = (tmp.substring(at + 2).length() == 0) ? at + 2 
1976                         : tmp.length();
1977                 }
1978                 parseAuthority(tmp.substring(at + 2, next), escaped);
1979                 from = at = next;
1980                 // Set flag
1981                 _is_net_path = true;
1982             }
1983             if (from == at) {
1984                 // Set flag
1985                 _is_abs_path = true;
1986             }
1987         }
1988 
1989         /*
1990          * Parse the path component.
1991          * <p><blockquote><pre>
1992          *  path      =  $5 = /ietf/uri/
1993          *                                @@@@@@
1994          *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
1995          * </pre></blockquote><p>
1996          */
1997         if (from < length) {
1998             // rel_path = rel_segment [ abs_path ]
1999             int next = indexFirstOf(tmp, "?#", from);
2000             if (next == -1) {
2001                 next = tmp.length();
2002             }
2003             if (!_is_abs_path) {
2004                 if (!escaped 
2005                     && prevalidate(tmp.substring(from, next), disallowed_rel_path) 
2006                     || escaped 
2007                     && validate(tmp.substring(from, next).toCharArray(), rel_path)) {
2008                     // Set flag
2009                     _is_rel_path = true;
2010                 } else if (!escaped 
2011                     && prevalidate(tmp.substring(from, next), disallowed_opaque_part) 
2012                     || escaped 
2013                     && validate(tmp.substring(from, next).toCharArray(), opaque_part)) {
2014                     // Set flag
2015                     _is_opaque_part = true;
2016                 } else {
2017                     // the path component may be empty
2018                     _path = null;
2019                 }
2020             }
2021             String s = tmp.substring(from, next);
2022             if (escaped) {
2023                 setRawPath(s.toCharArray());
2024             } else {
2025                 setPath(s);
2026             }
2027             at = next;
2028         }
2029 
2030         // set the charset to do escape encoding
2031         String charset = getProtocolCharset();
2032 
2033         /*
2034          * Parse the query component.
2035          * <p><blockquote><pre>
2036          *  query     =  $7 = <undefined>
2037          *                                        @@@@@@@@@
2038          *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
2039          * </pre></blockquote><p>
2040          */
2041         if (0 <= at && at + 1 < length && tmp.charAt(at) == '?') {
2042             int next = tmp.indexOf('#', at + 1);
2043             if (next == -1) {
2044                 next = tmp.length();
2045             }
2046             if (escaped) {
2047                 _query = tmp.substring(at + 1, next).toCharArray();
2048                 if (!validate(_query, uric)) {
2049                     throw new URIException("Invalid query");
2050                 }
2051             } else {
2052                 _query = encode(tmp.substring(at + 1, next), allowed_query, charset);
2053             }
2054             at = next;
2055         }
2056 
2057         /*
2058          * Parse the fragment component.
2059          * <p><blockquote><pre>
2060          *  fragment  =  $9 = Related
2061          *                                                   @@@@@@@@
2062          *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
2063          * </pre></blockquote><p>
2064          */
2065         if (0 <= at && at + 1 <= length && tmp.charAt(at) == '#') {
2066             if (at + 1 == length) { // empty fragment
2067                 _fragment = "".toCharArray();
2068             } else {
2069                 _fragment = (escaped) ? tmp.substring(at + 1).toCharArray() 
2070                     : encode(tmp.substring(at + 1), allowed_fragment, charset);
2071             }
2072         }
2073 
2074         // set this URI.
2075         setURI();
2076     }
2077 
2078 
2079     /**
2080      * Get the earlier index that to be searched for the first occurrance in
2081      * one of any of the given string.
2082      *
2083      * @param s the string to be indexed
2084      * @param delims the delimiters used to index
2085      * @return the earlier index if there are delimiters
2086      */
2087     protected int indexFirstOf(String s, String delims) {
2088         return indexFirstOf(s, delims, -1);
2089     }
2090 
2091 
2092     /**
2093      * Get the earlier index that to be searched for the first occurrance in
2094      * one of any of the given string.
2095      *
2096      * @param s the string to be indexed
2097      * @param delims the delimiters used to index
2098      * @param offset the from index
2099      * @return the earlier index if there are delimiters
2100      */
2101     protected int indexFirstOf(String s, String delims, int offset) {
2102         if (s == null || s.length() == 0) {
2103             return -1;
2104         }
2105         if (delims == null || delims.length() == 0) {
2106             return -1;
2107         }
2108         // check boundaries
2109         if (offset < 0) {
2110             offset = 0;
2111         } else if (offset > s.length()) {
2112             return -1;
2113         }
2114         // s is never null
2115         int min = s.length();
2116         char[] delim = delims.toCharArray();
2117         for (int i = 0; i < delim.length; i++) {
2118             int at = s.indexOf(delim[i], offset);
2119             if (at >= 0 && at < min) {
2120                 min = at;
2121             }
2122         }
2123         return (min == s.length()) ? -1 : min;
2124     }
2125 
2126 
2127     /**
2128      * Get the earlier index that to be searched for the first occurrance in
2129      * one of any of the given array.
2130      *
2131      * @param s the character array to be indexed
2132      * @param delim the delimiter used to index
2133      * @return the ealier index if there are a delimiter
2134      */
2135     protected int indexFirstOf(char[] s, char delim) {
2136         return indexFirstOf(s, delim, 0);
2137     }
2138 
2139 
2140     /**
2141      * Get the earlier index that to be searched for the first occurrance in
2142      * one of any of the given array.
2143      *
2144      * @param s the character array to be indexed
2145      * @param delim the delimiter used to index
2146      * @param offset The offset.
2147      * @return the ealier index if there is a delimiter
2148      */
2149     protected int indexFirstOf(char[] s, char delim, int offset) {
2150         if (s == null || s.length == 0) {
2151             return -1;
2152         }
2153         // check boundaries
2154         if (offset < 0) {
2155             offset = 0;
2156         } else if (offset > s.length) {
2157             return -1;
2158         }
2159         for (int i = offset; i < s.length; i++) {
2160             if (s[i] == delim) {
2161                 return i;
2162             }
2163         }
2164         return -1;
2165     }
2166 
2167 
2168     /**
2169      * Parse the authority component.
2170      *
2171      * @param original the original character sequence of authority component
2172      * @param escaped <code>true</code> if <code>original</code> is escaped
2173      * @throws URIException If an error occurs.
2174      */
2175     protected void parseAuthority(String original, boolean escaped)
2176         throws URIException {
2177 
2178         // Reset flags
2179         _is_reg_name = _is_server =
2180         _is_hostname = _is_IPv4address = _is_IPv6reference = false;
2181 
2182         // set the charset to do escape encoding
2183         String charset = getProtocolCharset();
2184 
2185         boolean hasPort = true;
2186         int from = 0;
2187         int next = original.indexOf('@');
2188         if (next != -1) { // neither -1 and 0
2189             // each protocol extented from URI supports the specific userinfo
2190             _userinfo = (escaped) ? original.substring(0, next).toCharArray() 
2191                 : encode(original.substring(0, next), allowed_userinfo,
2192                         charset);
2193             from = next + 1;
2194         }
2195         next = original.indexOf('[', from);
2196         if (next >= from) {
2197             next = original.indexOf(']', from);
2198             if (next == -1) {
2199                 throw new URIException(URIException.PARSING, "IPv6reference");
2200             } else {
2201                 next++;
2202             }
2203             // In IPv6reference, '[', ']' should be excluded
2204             _host = (escaped) ? original.substring(from, next).toCharArray() 
2205                 : encode(original.substring(from, next), allowed_IPv6reference,
2206                         charset);
2207             // Set flag
2208             _is_IPv6reference = true;
2209         } else { // only for !_is_IPv6reference
2210             next = original.indexOf(':', from);
2211             if (next == -1) {
2212                 next = original.length();
2213                 hasPort = false;
2214             }
2215             // REMINDME: it doesn't need the pre-validation
2216             _host = original.substring(from, next).toCharArray();
2217             if (validate(_host, IPv4address)) {
2218                 // Set flag
2219                 _is_IPv4address = true;
2220             } else if (validate(_host, hostname)) {
2221                 // Set flag
2222                 _is_hostname = true;
2223             } else {
2224                 // Set flag
2225                 _is_reg_name = true;
2226             }
2227         }
2228         if (_is_reg_name) {
2229             // Reset flags for a server-based naming authority
2230             _is_server = _is_hostname = _is_IPv4address =
2231             _is_IPv6reference = false;
2232             // set a registry-based naming authority
2233             if (escaped) {
2234                 _authority = original.toCharArray();
2235                 if (!validate(_authority, reg_name)) {
2236                     throw new URIException("Invalid authority");
2237                 }
2238             } else {
2239                 _authority = encode(original, allowed_reg_name, charset);
2240             }
2241         } else {
2242             if (original.length() - 1 > next && hasPort 
2243                 && original.charAt(next) == ':') { // not empty
2244                 from = next + 1;
2245                 try {
2246                     _port = Integer.parseInt(original.substring(from));
2247                 } catch (NumberFormatException error) {
2248                     throw new URIException(URIException.PARSING,
2249                             "invalid port number");
2250                 }
2251             }
2252             // set a server-based naming authority
2253             StringBuffer buf = new StringBuffer();
2254             if (_userinfo != null) { // has_userinfo
2255                 buf.append(_userinfo);
2256                 buf.append('@');
2257             }
2258             if (_host != null) {
2259                 buf.append(_host);
2260                 if (_port != -1) {
2261                     buf.append(':');
2262                     buf.append(_port);
2263                 }
2264             }
2265             _authority = buf.toString().toCharArray();
2266             // Set flag
2267             _is_server = true;
2268         }
2269     }
2270 
2271 
2272     /**
2273      * Once it's parsed successfully, set this URI.
2274      *
2275      * @see #getRawURI
2276      */
2277     protected void setURI() {
2278         // set _uri
2279         StringBuffer buf = new StringBuffer();
2280         // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
2281         if (_scheme != null) {
2282             buf.append(_scheme);
2283             buf.append(':');
2284         }
2285         if (_is_net_path) {
2286             buf.append("//");
2287             if (_authority != null) { // has_authority
2288                 buf.append(_authority);
2289             }
2290         }
2291         if (_opaque != null && _is_opaque_part) {
2292             buf.append(_opaque);
2293         } else if (_path != null) {
2294             // _is_hier_part or _is_relativeURI
2295             if (_path.length != 0) {
2296                 buf.append(_path);
2297             }
2298         }
2299         if (_query != null) { // has_query
2300             buf.append('?');
2301             buf.append(_query);
2302         }
2303         // ignore the fragment identifier
2304         _uri = buf.toString().toCharArray();
2305         hash = 0;
2306     }
2307 
2308     // ----------------------------------------------------------- Test methods
2309   
2310 
2311     /**
2312      * Tell whether or not this URI is absolute.
2313      *
2314      * @return true iif this URI is absoluteURI
2315      */
2316     public boolean isAbsoluteURI() {
2317         return (_scheme != null);
2318     }
2319   
2320 
2321     /**
2322      * Tell whether or not this URI is relative.
2323      *
2324      * @return true iif this URI is relativeURI
2325      */
2326     public boolean isRelativeURI() {
2327         return (_scheme == null);
2328     }
2329 
2330 
2331     /**
2332      * Tell whether or not the absoluteURI of this URI is hier_part.
2333      *
2334      * @return true iif the absoluteURI is hier_part
2335      */
2336     public boolean isHierPart() {
2337         return _is_hier_part;
2338     }
2339 
2340 
2341     /**
2342      * Tell whether or not the absoluteURI of this URI is opaque_part.
2343      *
2344      * @return true iif the absoluteURI is opaque_part
2345      */
2346     public boolean isOpaquePart() {
2347         return _is_opaque_part;
2348     }
2349 
2350 
2351     /**
2352      * Tell whether or not the relativeURI or heir_part of this URI is net_path.
2353      * It's the same function as the has_authority() method.
2354      *
2355      * @return true iif the relativeURI or heir_part is net_path
2356      * @see #hasAuthority
2357      */
2358     public boolean isNetPath() {
2359         return _is_net_path || (_authority != null);
2360     }
2361 
2362 
2363     /**
2364      * Tell whether or not the relativeURI or hier_part of this URI is abs_path.
2365      *
2366      * @return true iif the relativeURI or hier_part is abs_path
2367      */
2368     public boolean isAbsPath() {
2369         return _is_abs_path;
2370     }
2371 
2372 
2373     /**
2374      * Tell whether or not the relativeURI of this URI is rel_path.
2375      *
2376      * @return true iif the relativeURI is rel_path
2377      */
2378     public boolean isRelPath() {
2379         return _is_rel_path;
2380     }
2381 
2382 
2383     /**
2384      * Tell whether or not this URI has authority.
2385      * It's the same function as the is_net_path() method.
2386      *
2387      * @return true iif this URI has authority
2388      * @see #isNetPath
2389      */
2390     public boolean hasAuthority() {
2391         return (_authority != null) || _is_net_path;
2392     }
2393 
2394     /**
2395      * Tell whether or not the authority component of this URI is reg_name.
2396      *
2397      * @return true iif the authority component is reg_name
2398      */
2399     public boolean isRegName() {
2400         return _is_reg_name;
2401     }
2402   
2403 
2404     /**
2405      * Tell whether or not the authority component of this URI is server.
2406      *
2407      * @return true iif the authority component is server
2408      */
2409     public boolean isServer() {
2410         return _is_server;
2411     }
2412   
2413 
2414     /**
2415      * Tell whether or not this URI has userinfo.
2416      *
2417      * @return true iif this URI has userinfo
2418      */
2419     public boolean hasUserinfo() {
2420         return (_userinfo != null);
2421     }
2422   
2423 
2424     /**
2425      * Tell whether or not the host part of this URI is hostname.
2426      *
2427      * @return true iif the host part is hostname
2428      */
2429     public boolean isHostname() {
2430         return _is_hostname;
2431     }
2432 
2433 
2434     /**
2435      * Tell whether or not the host part of this URI is IPv4address.
2436      *
2437      * @return true iif the host part is IPv4address
2438      */
2439     public boolean isIPv4address() {
2440         return _is_IPv4address;
2441     }
2442 
2443 
2444     /**
2445      * Tell whether or not the host part of this URI is IPv6reference.
2446      *
2447      * @return true iif the host part is IPv6reference
2448      */
2449     public boolean isIPv6reference() {
2450         return _is_IPv6reference;
2451     }
2452 
2453 
2454     /**
2455      * Tell whether or not this URI has query.
2456      *
2457      * @return true iif this URI has query
2458      */
2459     public boolean hasQuery() {
2460         return (_query != null);
2461     }
2462    
2463 
2464     /**
2465      * Tell whether or not this URI has fragment.
2466      *
2467      * @return true iif this URI has fragment
2468      */
2469     public boolean hasFragment() {
2470         return (_fragment != null);
2471     }
2472    
2473    
2474     // ---------------------------------------------------------------- Charset
2475 
2476 
2477     /**
2478      * Set the default charset of the protocol.
2479      * <p>
2480      * The character set used to store files SHALL remain a local decision and
2481      * MAY depend on the capability of local operating systems. Prior to the
2482      * exchange of URIs they SHOULD be converted into a ISO/IEC 10646 format
2483      * and UTF-8 encoded. This approach, while allowing international exchange
2484      * of URIs, will still allow backward compatibility with older systems
2485      * because the code set positions for ASCII characters are identical to the
2486      * one byte sequence in UTF-8.
2487      * <p>
2488      * An individual URI scheme may require a single charset, define a default
2489      * charset, or provide a way to indicate the charset used.
2490      *
2491      * <p>
2492      * Always all the time, the setter method is always succeeded and throws
2493      * <code>DefaultCharsetChanged</code> exception.
2494      *
2495      * So API programmer must follow the following way:
2496      * <code><pre>
2497      *  import org.apache.util.URI$DefaultCharsetChanged;
2498      *      .
2499      *      .
2500      *      .
2501      *  try {
2502      *      URI.setDefaultProtocolCharset("UTF-8");
2503      *  } catch (DefaultCharsetChanged cc) {
2504      *      // CASE 1: the exception could be ignored, when it is set by user
2505      *      if (cc.getReasonCode() == DefaultCharsetChanged.PROTOCOL_CHARSET) {
2506      *      // CASE 2: let user know the default protocol charset changed
2507      *      } else {
2508      *      // CASE 2: let user know the default document charset changed
2509      *      }
2510      *  }
2511      *  </pre></code>
2512      *
2513      * The API programmer is responsible to set the correct charset.
2514      * And each application should remember its own charset to support.
2515      *
2516      * @param charset the default charset for each protocol
2517      * @throws DefaultCharsetChanged default charset changed
2518      */
2519     public static void setDefaultProtocolCharset(String charset) 
2520         throws DefaultCharsetChanged {
2521             
2522         defaultProtocolCharset = charset;
2523         throw new DefaultCharsetChanged(DefaultCharsetChanged.PROTOCOL_CHARSET,
2524                 "the default protocol charset changed");
2525     }
2526 
2527 
2528     /**
2529      * Get the default charset of the protocol.
2530      * <p>
2531      * An individual URI scheme may require a single charset, define a default
2532      * charset, or provide a way to indicate the charset used.
2533      * <p>
2534      * To work globally either requires support of a number of character sets
2535      * and to be able to convert between them, or the use of a single preferred
2536      * character set.
2537      * For support of global compatibility it is STRONGLY RECOMMENDED that
2538      * clients and servers use UTF-8 encoding when exchanging URIs.
2539      *
2540      * @return the default charset string
2541      */
2542     public static String getDefaultProtocolCharset() {
2543         return defaultProtocolCharset;
2544     }
2545 
2546 
2547     /**
2548      * Get the protocol charset used by this current URI instance.
2549      * It was set by the constructor for this instance. If it was not set by
2550      * contructor, it will return the default protocol charset.
2551      *
2552      * @return the protocol charset string
2553      * @see #getDefaultProtocolCharset
2554      */
2555     public String getProtocolCharset() {
2556         return (protocolCharset != null) 
2557             ? protocolCharset 
2558             : defaultProtocolCharset;
2559     }
2560 
2561 
2562     /**
2563      * Set the default charset of the document.
2564      * <p>
2565      * Notice that it will be possible to contain mixed characters (e.g.
2566      * ftp://host/KoreanNamespace/ChineseResource). To handle the Bi-directional
2567      * display of these character sets, the protocol charset could be simply
2568      * used again. Because it's not yet implemented that the insertion of BIDI
2569      * control characters at different points during composition is extracted.
2570      * <p>
2571      *
2572      * Always all the time, the setter method is always succeeded and throws
2573      * <code>DefaultCharsetChanged</code> exception.
2574      *
2575      * So API programmer must follow the following way:
2576      * <code><pre>
2577      *  import org.apache.util.URI$DefaultCharsetChanged;
2578      *      .
2579      *      .
2580      *      .
2581      *  try {
2582      *      URI.setDefaultDocumentCharset("EUC-KR");
2583      *  } catch (DefaultCharsetChanged cc) {
2584      *      // CASE 1: the exception could be ignored, when it is set by user
2585      *      if (cc.getReasonCode() == DefaultCharsetChanged.DOCUMENT_CHARSET) {
2586      *      // CASE 2: let user know the default document charset changed
2587      *      } else {
2588      *      // CASE 2: let user know the default protocol charset changed
2589      *      }
2590      *  }
2591      *  </pre></code>
2592      *
2593      * The API programmer is responsible to set the correct charset.
2594      * And each application should remember its own charset to support.
2595      *
2596      * @param charset the default charset for the document
2597      * @throws DefaultCharsetChanged default charset changed
2598      */
2599     public static void setDefaultDocumentCharset(String charset) 
2600         throws DefaultCharsetChanged {
2601             
2602         defaultDocumentCharset = charset;
2603         throw new DefaultCharsetChanged(DefaultCharsetChanged.DOCUMENT_CHARSET,
2604                 "the default document charset changed");
2605     }
2606 
2607 
2608     /**
2609      * Get the recommended default charset of the document.
2610      *
2611      * @return the default charset string
2612      */
2613     public static String getDefaultDocumentCharset() {
2614         return defaultDocumentCharset;
2615     }
2616 
2617 
2618     /**
2619      * Get the default charset of the document by locale.
2620      *
2621      * @return the default charset string by locale
2622      */
2623     public static String getDefaultDocumentCharsetByLocale() {
2624         return defaultDocumentCharsetByLocale;
2625     }
2626 
2627 
2628     /**
2629      * Get the default charset of the document by platform.
2630      *
2631      * @return the default charset string by platform
2632      */
2633     public static String getDefaultDocumentCharsetByPlatform() {
2634         return defaultDocumentCharsetByPlatform;
2635     }
2636 
2637     // ------------------------------------------------------------- The scheme
2638 
2639     /**
2640      * Get the scheme.
2641      *
2642      * @return the scheme
2643      */
2644     public char[] getRawScheme() {
2645         return _scheme;
2646     }
2647 
2648 
2649     /**
2650      * Get the scheme.
2651      *
2652      * @return the scheme
2653      * null if undefined scheme
2654      */
2655     public String getScheme() {
2656         return (_scheme == null) ? null : new String(_scheme);
2657     }
2658 
2659     // ---------------------------------------------------------- The authority
2660 
2661     /**
2662      * Set the authority.  It can be one type of server, hostport, hostname,
2663      * IPv4address, IPv6reference and reg_name.
2664      * <p><blockquote><pre>
2665      *   authority     = server | reg_name
2666      * </pre></blockquote><p>
2667      *
2668      * @param escapedAuthority the raw escaped authority
2669      * @throws URIException If {@link 
2670      * #parseAuthority(java.lang.String,boolean)} fails
2671      * @throws NullPointerException null authority
2672      */
2673     public void setRawAuthority(char[] escapedAuthority) 
2674         throws URIException, NullPointerException {
2675             
2676         parseAuthority(new String(escapedAuthority), true);
2677         setURI();
2678     }
2679 
2680 
2681     /**
2682      * Set the authority.  It can be one type of server, hostport, hostname,
2683      * IPv4address, IPv6reference and reg_name.
2684      * Note that there is no setAuthority method by the escape encoding reason.
2685      *
2686      * @param escapedAuthority the escaped authority string
2687      * @throws URIException If {@link 
2688      * #parseAuthority(java.lang.String,boolean)} fails
2689      */
2690     public void setEscapedAuthority(String escapedAuthority)
2691         throws URIException {
2692 
2693         parseAuthority(escapedAuthority, true);
2694         setURI();
2695     }
2696 
2697 
2698     /**
2699      * Get the raw-escaped authority.
2700      *
2701      * @return the raw-escaped authority
2702      */
2703     public char[] getRawAuthority() {
2704         return _authority;
2705     }
2706 
2707 
2708     /**
2709      * Get the escaped authority.
2710      *
2711      * @return the escaped authority
2712      */
2713     public String getEscapedAuthority() {
2714         return (_authority == null) ? null : new String(_authority);
2715     }
2716 
2717 
2718     /**
2719      * Get the authority.
2720      *
2721      * @return the authority
2722      * @throws URIException If {@link #decode} fails
2723      */
2724     public String getAuthority() throws URIException {
2725         return (_authority == null) ? null : decode(_authority,
2726                 getProtocolCharset());
2727     }
2728 
2729     // ----------------------------------------------------------- The userinfo
2730 
2731     /**
2732      * Get the raw-escaped userinfo.
2733      *
2734      * @return the raw-escaped userinfo
2735      * @see #getAuthority
2736      */
2737     public char[] getRawUserinfo() {
2738         return _userinfo;
2739     }
2740 
2741 
2742     /**
2743      * Get the escaped userinfo.
2744      *
2745      * @return the escaped userinfo
2746      * @see #getAuthority
2747      */
2748     public String getEscapedUserinfo() {
2749         return (_userinfo == null) ? null : new String(_userinfo);
2750     }
2751 
2752 
2753     /**
2754      * Get the userinfo.
2755      *
2756      * @return the userinfo
2757      * @throws URIException If {@link #decode} fails
2758      * @see #getAuthority
2759      */
2760     public String getUserinfo() throws URIException {
2761         return (_userinfo == null) ? null : decode(_userinfo,
2762                 getProtocolCharset());
2763     }
2764 
2765     // --------------------------------------------------------------- The host
2766 
2767     /**
2768      * Get the host.
2769      * <p><blockquote><pre>
2770      *   host          = hostname | IPv4address | IPv6reference
2771      * </pre></blockquote><p>
2772      *
2773      * @return the host
2774      * @see #getAuthority
2775      */
2776     public char[] getRawHost() {
2777         return _host;
2778     }
2779 
2780 
2781     /**
2782      * Get the host.
2783      * <p><blockquote><pre>
2784      *   host          = hostname | IPv4address | IPv6reference
2785      * </pre></blockquote><p>
2786      *
2787      * @return the host
2788      * @throws URIException If {@link #decode} fails
2789      * @see #getAuthority
2790      */
2791     public String getHost() throws URIException {
2792         if (_host != null) {
2793             return decode(_host, getProtocolCharset());
2794         } else {
2795             return null;
2796         }
2797     }
2798 
2799     // --------------------------------------------------------------- The port
2800 
2801     /**
2802      * Get the port.  In order to get the specfic default port, the specific
2803      * protocol-supported class extended from the URI class should be used.
2804      * It has the server-based naming authority.
2805      *
2806      * @return the port
2807      * if -1, it has the default port for the scheme or the server-based
2808      * naming authority is not supported in the specific URI.
2809      */
2810     public int getPort() {
2811         return _port;
2812     }
2813 
2814     // --------------------------------------------------------------- The path
2815 
2816     /**
2817      * Set the raw-escaped path.
2818      *
2819      * @param escapedPath the path character sequence
2820      * @throws URIException encoding error or not proper for initial instance
2821      * @see #encode
2822      */
2823     public void setRawPath(char[] escapedPath) throws URIException {
2824         if (escapedPath == null || escapedPath.length == 0) {
2825             _path = _opaque = escapedPath;
2826             setURI();
2827             return;
2828         }
2829         // remove the fragment identifier
2830         escapedPath = removeFragmentIdentifier(escapedPath);
2831         if (_is_net_path || _is_abs_path) {
2832             if (escapedPath[0] != '/') {
2833                 throw new URIException(URIException.PARSING,
2834                         "not absolute path");
2835             }
2836             if (!validate(escapedPath, abs_path)) {
2837                 throw new URIException(URIException.ESCAPING,
2838                         "escaped absolute path not valid");
2839             }
2840             _path = escapedPath;
2841         } else if (_is_rel_path) {
2842             int at = indexFirstOf(escapedPath, '/');
2843             if (at == 0) {
2844                 throw new URIException(URIException.PARSING, "incorrect path");
2845             }
2846             if (at > 0 && !validate(escapedPath, 0, at - 1, rel_segment) 
2847                 && !validate(escapedPath, at, -1, abs_path) 
2848                 || at < 0 && !validate(escapedPath, 0, -1, rel_segment)) {
2849             
2850                 throw new URIException(URIException.ESCAPING,
2851                         "escaped relative path not valid");
2852             }
2853             _path = escapedPath;
2854         } else if (_is_opaque_part) {
2855             if (!uric_no_slash.get(escapedPath[0]) 
2856                 && !validate(escapedPath, 1, -1, uric)) {
2857                 throw new URIException(URIException.ESCAPING,
2858                     "escaped opaque part not valid");
2859             }
2860             _opaque = escapedPath;
2861         } else {
2862             throw new URIException(URIException.PARSING, "incorrect path");
2863         }
2864         setURI();
2865     }
2866 
2867 
2868     /**
2869      * Set the escaped path.
2870      *
2871      * @param escapedPath the escaped path string
2872      * @throws URIException encoding error or not proper for initial instance
2873      * @see #encode
2874      */
2875     public void setEscapedPath(String escapedPath) throws URIException {
2876         if (escapedPath == null) {
2877             _path = _opaque = null;
2878             setURI();
2879             return;
2880         }
2881         setRawPath(escapedPath.toCharArray());
2882     }
2883 
2884 
2885     /**
2886      * Set the path.
2887      *
2888      * @param path the path string
2889      * @throws URIException set incorrectly or fragment only
2890      * @see #encode
2891      */
2892     public void setPath(String path) throws URIException {
2893 
2894         if (path == null || path.length() == 0) {
2895             _path = _opaque = (path == null) ? null : path.toCharArray();
2896             setURI();
2897             return;
2898         }
2899         // set the charset to do escape encoding
2900         String charset = getProtocolCharset();
2901 
2902         if (_is_net_path || _is_abs_path) {
2903             _path = encode(path, allowed_abs_path, charset);
2904         } else if (_is_rel_path) {
2905             StringBuffer buff = new StringBuffer(path.length());
2906             int at = path.indexOf('/');
2907             if (at == 0) { // never 0
2908                 throw new URIException(URIException.PARSING,
2909                         "incorrect relative path");
2910             }
2911             if (at > 0) {
2912                 buff.append(encode(path.substring(0, at), allowed_rel_path,
2913                             charset));
2914                 buff.append(encode(path.substring(at), allowed_abs_path,
2915                             charset));
2916             } else {
2917                 buff.append(encode(path, allowed_rel_path, charset));
2918             }
2919             _path = buff.toString().toCharArray();
2920         } else if (_is_opaque_part) {
2921             StringBuffer buf = new StringBuffer();
2922             buf.insert(0, encode(path.substring(0, 1), uric_no_slash, charset));
2923             buf.insert(1, encode(path.substring(1), uric, charset));
2924             _opaque = buf.toString().toCharArray();
2925         } else {
2926             throw new URIException(URIException.PARSING, "incorrect path");
2927         }
2928         setURI();
2929     }
2930 
2931 
2932     /**
2933      * Resolve the base and relative path.
2934      *
2935      * @param basePath a character array of the basePath
2936      * @param relPath a character array of the relPath
2937      * @return the resolved path
2938      * @throws URIException no more higher path level to be resolved
2939      */
2940     protected char[] resolvePath(char[] basePath, char[] relPath)
2941         throws URIException {
2942 
2943         // REMINDME: paths are never null
2944         String base = (basePath == null) ? "" : new String(basePath);
2945 
2946         // _path could be empty
2947         if (relPath == null || relPath.length == 0) {
2948             return normalize(basePath);
2949         } else if (relPath[0] == '/') {
2950             return normalize(relPath);
2951         } else {
2952             int at = base.lastIndexOf('/');
2953             if (at != -1) {
2954                 basePath = base.substring(0, at + 1).toCharArray();
2955             }
2956             StringBuffer buff = new StringBuffer(base.length() 
2957                 + relPath.length);
2958             buff.append((at != -1) ? base.substring(0, at + 1) : "/");
2959             buff.append(relPath);
2960             return normalize(buff.toString().toCharArray());
2961         }
2962     }
2963 
2964 
2965     /**
2966      * Get the raw-escaped current hierarchy level in the given path.
2967      * If the last namespace is a collection, the slash mark ('/') should be
2968      * ended with at the last character of the path string.
2969      *
2970      * @param path the path
2971      * @return the current hierarchy level
2972      * @throws URIException no hierarchy level
2973      */
2974     protected char[] getRawCurrentHierPath(char[] path) throws URIException {
2975 
2976         if (_is_opaque_part) {
2977             throw new URIException(URIException.PARSING, "no hierarchy level");
2978         }
2979         if (path == null) {
2980             throw new URIException(URIException.PARSING, "empty path");
2981         }
2982         String buff = new String(path);
2983         int first = buff.indexOf('/');
2984         int last = buff.lastIndexOf('/');
2985         if (last == 0) {
2986             return rootPath;
2987         } else if (first != last && last != -1) {
2988             return buff.substring(0, last).toCharArray();
2989         }
2990         // FIXME: it could be a document on the server side
2991         return path;
2992     }
2993 
2994 
2995     /**
2996      * Get the raw-escaped current hierarchy level.
2997      *
2998      * @return the raw-escaped current hierarchy level
2999      * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails.
3000      */
3001     public char[] getRawCurrentHierPath() throws URIException {
3002         return (_path == null) ? null : getRawCurrentHierPath(_path);
3003     }
3004  
3005 
3006     /**
3007      * Get the escaped current hierarchy level.
3008      *
3009      * @return the escaped current hierarchy level
3010      * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails.
3011      */
3012     public String getEscapedCurrentHierPath() throws URIException {
3013         char[] path = getRawCurrentHierPath();
3014         return (path == null) ? null : new String(path);
3015     }
3016  
3017 
3018     /**
3019      * Get the current hierarchy level.
3020      *
3021      * @return the current hierarchy level
3022      * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails.
3023      * @see #decode
3024      */
3025     public String getCurrentHierPath() throws URIException {
3026         char[] path = getRawCurrentHierPath();
3027         return (path == null) ? null : decode(path, getProtocolCharset());
3028     }
3029 
3030 
3031     /**
3032      * Get the level above the this hierarchy level.
3033      *
3034      * @return the raw above hierarchy level
3035      * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails.
3036      */
3037     public char[] getRawAboveHierPath() throws URIException {
3038         char[] path = getRawCurrentHierPath();
3039         return (path == null) ? null : getRawCurrentHierPath(path);
3040     }
3041 
3042 
3043     /**
3044      * Get the level above the this hierarchy level.
3045      *
3046      * @return the raw above hierarchy level
3047      * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails.
3048      */
3049     public String getEscapedAboveHierPath() throws URIException {
3050         char[] path = getRawAboveHierPath();
3051         return (path == null) ? null : new String(path);
3052     }
3053 
3054 
3055     /**
3056      * Get the level above the this hierarchy level.
3057      *
3058      * @return the above hierarchy level
3059      * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails.
3060      * @see #decode
3061      */
3062     public String getAboveHierPath() throws URIException {
3063         char[] path = getRawAboveHierPath();
3064         return (path == null) ? null : decode(path, getProtocolCharset());
3065     }
3066 
3067 
3068     /**
3069      * Get the raw-escaped path.
3070      * <p><blockquote><pre>
3071      *   path          = [ abs_path | opaque_part ]
3072      * </pre></blockquote><p>
3073      *
3074      * @return the raw-escaped path
3075      */
3076     public char[] getRawPath() {
3077         return _is_opaque_part ? _opaque : _path;
3078     }
3079 
3080 
3081     /**
3082      * Get the escaped path.
3083      * <p><blockquote><pre>
3084      *   path          = [ abs_path | opaque_part ]
3085      *   abs_path      = "/"  path_segments 
3086      *   opaque_part   = uric_no_slash *uric
3087      * </pre></blockquote><p>
3088      *
3089      * @return the escaped path string
3090      */
3091     public String getEscapedPath() {
3092         char[] path = getRawPath();
3093         return (path == null) ? null : new String(path);
3094     }
3095 
3096 
3097     /**
3098      * Get the path.
3099      * <p><blockquote><pre>
3100      *   path          = [ abs_path | opaque_part ]
3101      * </pre></blockquote><p>
3102      * @return the path string
3103      * @throws URIException If {@link #decode} fails.
3104      * @see #decode
3105      */
3106     public String getPath() throws URIException { 
3107         char[] path =  getRawPath();
3108         return (path == null) ? null : decode(path, getProtocolCharset());
3109     }
3110 
3111 
3112     /**
3113      * Get the raw-escaped basename of the path.
3114      *
3115      * @return the raw-escaped basename
3116      */
3117     public char[] getRawName() {
3118         if (_path == null) { 
3119             return null;
3120         }
3121 
3122         int at = 0;
3123         for (int i = _path.length - 1; i >= 0; i--) {
3124             if (_path[i] == '/') {
3125                 at = i + 1;
3126                 break;
3127             }
3128         }
3129         int len = _path.length - at;
3130         char[] basename =  new char[len];
3131         System.arraycopy(_path, at, basename, 0, len);
3132         return basename;
3133     }
3134 
3135 
3136     /**
3137      * Get the escaped basename of the path.
3138      *
3139      * @return the escaped basename string
3140      */
3141     public String getEscapedName() {
3142         char[] basename = getRawName();
3143         return (basename == null) ? null : new String(basename);
3144     }
3145 
3146 
3147     /**
3148      * Get the basename of the path.
3149      *
3150      * @return the basename string
3151      * @throws URIException incomplete trailing escape pattern or unsupported
3152      * character encoding
3153      * @see #decode
3154      */
3155     public String getName() throws URIException {
3156         char[] basename = getRawName();
3157         return (basename == null) ? null : decode(getRawName(),
3158                 getProtocolCharset());
3159     }
3160 
3161     // ----------------------------------------------------- The path and query 
3162 
3163     /**
3164      * Get the raw-escaped path and query.
3165      *
3166      * @return the raw-escaped path and query
3167      */
3168     public char[] getRawPathQuery() {
3169 
3170         if (_path == null && _query == null) {
3171             return null;
3172         }
3173         StringBuffer buff = new StringBuffer();
3174         if (_path != null) {
3175             buff.append(_path);
3176         }
3177         if (_query != null) {
3178             buff.append('?');
3179             buff.append(_query);
3180         }
3181         return buff.toString().toCharArray();
3182     }
3183 
3184 
3185     /**
3186      * Get the escaped query.
3187      *
3188      * @return the escaped path and query string
3189      */
3190     public String getEscapedPathQuery() {
3191         char[] rawPathQuery = getRawPathQuery();
3192         return (rawPathQuery == null) ? null : new String(rawPathQuery);
3193     }
3194 
3195 
3196     /**
3197      * Get the path and query.
3198      *
3199      * @return the path and query string.
3200      * @throws URIException incomplete trailing escape pattern or unsupported
3201      * character encoding
3202      * @see #decode
3203      */
3204     public String getPathQuery() throws URIException {
3205         char[] rawPathQuery = getRawPathQuery();
3206         return (rawPathQuery == null) ? null : decode(rawPathQuery,
3207                 getProtocolCharset());
3208     }
3209 
3210     // -------------------------------------------------------------- The query 
3211 
3212     /**
3213      * Set the raw-escaped query.
3214      *
3215      * @param escapedQuery the raw-escaped query
3216      * @throws URIException escaped query not valid
3217      */
3218     public void setRawQuery(char[] escapedQuery) throws URIException {
3219         if (escapedQuery == null || escapedQuery.length == 0) {
3220             _query = escapedQuery;
3221             setURI();
3222             return;
3223         }
3224         // remove the fragment identifier
3225         escapedQuery = removeFragmentIdentifier(escapedQuery);
3226         if (!validate(escapedQuery, query)) {
3227             throw new URIException(URIException.ESCAPING,
3228                     "escaped query not valid");
3229         }
3230         _query = escapedQuery;
3231         setURI();
3232     }
3233 
3234 
3235     /**
3236      * Set the escaped query string.
3237      *
3238      * @param escapedQuery the escaped query string
3239      * @throws URIException escaped query not valid
3240      */
3241     public void setEscapedQuery(String escapedQuery) throws URIException {
3242         if (escapedQuery == null) {
3243             _query = null;
3244             setURI();
3245             return;
3246         }
3247         setRawQuery(escapedQuery.toCharArray());
3248     }
3249 
3250 
3251     /**
3252      * Set the query.
3253      * <p>
3254      * When a query string is not misunderstood the reserved special characters
3255      * ("&amp;", "=", "+", ",", and "$") within a query component, it is
3256      * recommended to use in encoding the whole query with this method.
3257      * <p>
3258      * The additional APIs for the special purpose using by the reserved
3259      * special characters used in each protocol are implemented in each protocol
3260      * classes inherited from <code>URI</code>.  So refer to the same-named APIs
3261      * implemented in each specific protocol instance.
3262      *
3263      * @param query the query string.
3264      * @throws URIException incomplete trailing escape pattern or unsupported
3265      * character encoding
3266      * @see #encode
3267      */
3268     public void setQuery(String query) throws URIException {
3269         if (query == null || query.length() == 0) {
3270             _query = (query == null) ? null : query.toCharArray();
3271             setURI();
3272             return;
3273         }
3274         setRawQuery(encode(query, allowed_query, getProtocolCharset()));
3275     }
3276 
3277 
3278     /**
3279      * Get the raw-escaped query.
3280      *
3281      * @return the raw-escaped query
3282      */
3283     public char[] getRawQuery() {
3284         return _query;
3285     }
3286 
3287 
3288     /**
3289      * Get the escaped query.
3290      *
3291      * @return the escaped query string
3292      */
3293     public String getEscapedQuery() {
3294         return (_query == null) ? null : new String(_query);
3295     }
3296 
3297 
3298     /**
3299      * Get the query.
3300      *
3301      * @return the query string.
3302      * @throws URIException incomplete trailing escape pattern or unsupported
3303      * character encoding
3304      * @see #decode
3305      */
3306     public String getQuery() throws URIException {
3307         return (_query == null) ? null : decode(_query, getProtocolCharset());
3308     }
3309 
3310     // ----------------------------------------------------------- The fragment 
3311 
3312     /**
3313      * Set the raw-escaped fragment.
3314      *
3315      * @param escapedFragment the raw-escaped fragment
3316      * @throws URIException escaped fragment not valid
3317      */
3318     public void setRawFragment(char[] escapedFragment) throws URIException {
3319         if (escapedFragment == null || escapedFragment.length == 0) {
3320             _fragment = escapedFragment;
3321             hash = 0;
3322             return;
3323         }
3324         if (!validate(escapedFragment, fragment)) {
3325             throw new URIException(URIException.ESCAPING,
3326                     "escaped fragment not valid");
3327         }
3328         _fragment = escapedFragment;
3329         hash = 0;
3330     }
3331 
3332 
3333     /**
3334      * Set the escaped fragment string.
3335      *
3336      * @param escapedFragment the escaped fragment string
3337      * @throws URIException escaped fragment not valid
3338      */
3339     public void setEscapedFragment(String escapedFragment) throws URIException {
3340         if (escapedFragment == null) {
3341             _fragment = null;
3342             hash = 0;
3343             return;
3344         }
3345         setRawFragment(escapedFragment.toCharArray());
3346     }
3347 
3348 
3349     /**
3350      * Set the fragment.
3351      *
3352      * @param fragment the fragment string.
3353      * @throws URIException If an error occurs.
3354      */
3355     public void setFragment(String fragment) throws URIException {
3356         if (fragment == null || fragment.length() == 0) {
3357             _fragment = (fragment == null) ? null : fragment.toCharArray();
3358             hash = 0;
3359             return;
3360         }
3361         _fragment = encode(fragment, allowed_fragment, getProtocolCharset());
3362         hash = 0;
3363     }
3364 
3365 
3366     /**
3367      * Get the raw-escaped fragment.
3368      * <p>
3369      * The optional fragment identifier is not part of a URI, but is often used
3370      * in conjunction with a URI.
3371      * <p>
3372      * The format and interpretation of fragment identifiers is dependent on
3373      * the media type [RFC2046] of the retrieval result.
3374      * <p>
3375      * A fragment identifier is only meaningful when a URI reference is
3376      * intended for retrieval and the result of that retrieval is a document
3377      * for which the identified fragment is consistently defined.
3378      *
3379      * @return the raw-escaped fragment
3380      */
3381     public char[] getRawFragment() {
3382         return _fragment;
3383     }
3384 
3385 
3386     /**
3387      * Get the escaped fragment.
3388      *
3389      * @return the escaped fragment string
3390      */
3391     public String getEscapedFragment() {
3392         return (_fragment == null) ? null : new String(_fragment);
3393     }
3394 
3395 
3396     /**
3397      * Get the fragment.
3398      *
3399      * @return the fragment string
3400      * @throws URIException incomplete trailing escape pattern or unsupported
3401      * character encoding
3402      * @see #decode
3403      */
3404     public String getFragment() throws URIException {
3405         return (_fragment == null) ? null : decode(_fragment,
3406                 getProtocolCharset());
3407     }
3408 
3409     // ------------------------------------------------------------- Utilities 
3410 
3411     /**
3412      * Remove the fragment identifier of the given component.
3413      *
3414      * @param component the component that a fragment may be included
3415      * @return the component that the fragment identifier is removed
3416      */
3417     protected char[] removeFragmentIdentifier(char[] component) {
3418         if (component == null) { 
3419             return null;
3420         }
3421         int lastIndex = new String(component).indexOf('#');
3422         if (lastIndex != -1) {
3423             component = new String(component).substring(0,
3424                     lastIndex).toCharArray();
3425         }
3426         return component;
3427     }
3428 
3429 
3430     /**
3431      * Normalize the given hier path part.
3432      * 
3433      * <p>Algorithm taken from URI reference parser at 
3434      * http://www.apache.org/~fielding/uri/rev-2002/issues.html.
3435      *
3436      * @param path the path to normalize
3437      * @return the normalized path
3438      * @throws URIException no more higher path level to be normalized
3439      */
3440     protected char[] normalize(char[] path) throws URIException {
3441 
3442         if (path == null) { 
3443             return null;
3444         }
3445 
3446         String normalized = new String(path);
3447 
3448         // If the buffer begins with "./" or "../", the "." or ".." is removed.
3449         if (normalized.startsWith("./")) {
3450             normalized = normalized.substring(1);
3451         } else if (normalized.startsWith("../")) {
3452             normalized = normalized.substring(2);
3453         } else if (normalized.startsWith("..")) {
3454             normalized = normalized.substring(2);
3455         }
3456 
3457         // All occurrences of "/./" in the buffer are replaced with "/"
3458         int index = -1;
3459         while ((index = normalized.indexOf("/./")) != -1) {
3460             normalized = normalized.substring(0, index) + normalized.substring(index + 2);
3461         }
3462 
3463         // If the buffer ends with "/.", the "." is removed.
3464         if (normalized.endsWith("/.")) {
3465             normalized = normalized.substring(0, normalized.length() - 1);
3466         }
3467 
3468         int startIndex = 0;
3469 
3470         // All occurrences of "/<segment>/../" in the buffer, where ".."
3471         // and <segment> are complete path segments, are iteratively replaced
3472         // with "/" in order from left to right until no matching pattern remains.
3473         // If the buffer ends with "/<segment>/..", that is also replaced
3474         // with "/".  Note that <segment> may be empty.
3475         while ((index = normalized.indexOf("/../", startIndex)) != -1) {
3476             int slashIndex = normalized.lastIndexOf('/', index - 1);
3477             if (slashIndex >= 0) {
3478                 normalized = normalized.substring(0, slashIndex) + normalized.substring(index + 3);
3479             } else {
3480                 startIndex = index + 3;   
3481             }
3482         }
3483         if (normalized.endsWith("/..")) {
3484             int slashIndex = normalized.lastIndexOf('/', normalized.length() - 4);
3485             if (slashIndex >= 0) {
3486                 normalized = normalized.substring(0, slashIndex + 1);
3487             }
3488         }
3489 
3490         // All prefixes of "<segment>/../" in the buffer, where ".."
3491         // and <segment> are complete path segments, are iteratively replaced
3492         // with "/" in order from left to right until no matching pattern remains.
3493         // If the buffer ends with "<segment>/..", that is also replaced
3494         // with "/".  Note that <segment> may be empty.
3495         while ((index = normalized.indexOf("/../")) != -1) {
3496             int slashIndex = normalized.lastIndexOf('/', index - 1);
3497             if (slashIndex >= 0) {
3498                 break;
3499             } else {
3500                 normalized = normalized.substring(index + 3);
3501             }
3502         }
3503         if (normalized.endsWith("/..")) {
3504             int slashIndex = normalized.lastIndexOf('/', normalized.length() - 4);
3505             if (slashIndex < 0) {
3506                 normalized = "/";
3507             }
3508         }
3509 
3510         return normalized.toCharArray();
3511     }
3512 
3513 
3514     /**
3515      * Normalizes the path part of this URI.  Normalization is only meant to be performed on 
3516      * URIs with an absolute path.  Calling this method on a relative path URI will have no
3517      * effect.
3518      *
3519      * @throws URIException no more higher path level to be normalized
3520      * 
3521      * @see #isAbsPath()
3522      */
3523     public void normalize() throws URIException {
3524         if (isAbsPath()) {
3525             _path = normalize(_path);
3526             setURI();
3527         }
3528     }
3529 
3530 
3531     /**
3532      * Test if the first array is equal to the second array.
3533      *
3534      * @param first the first character array
3535      * @param second the second character array
3536      * @return true if they're equal
3537      */
3538     protected boolean equals(char[] first, char[] second) {
3539 
3540         if (first == null && second == null) {
3541             return true;
3542         }
3543         if (first == null || second == null) {
3544             return false;
3545         }
3546         if (first.length != second.length) {
3547             return false;
3548         }
3549         for (int i = 0; i < first.length; i++) {
3550             if (first[i] != second[i]) {
3551                 return false;
3552             }
3553         }
3554         return true;
3555     }
3556 
3557 
3558     /**
3559      * Test an object if this URI is equal to another.
3560      *
3561      * @param obj an object to compare
3562      * @return true if two URI objects are equal
3563      */
3564     public boolean equals(Object obj) {
3565 
3566         // normalize and test each components
3567         if (obj == this) {
3568             return true;
3569         }
3570         if (!(obj instanceof URI)) {
3571             return false;
3572         }
3573         URI another = (URI) obj;
3574         // scheme
3575         if (!equals(_scheme, another._scheme)) {
3576             return false;
3577         }
3578         // is_opaque_part or is_hier_part?  and opaque
3579         if (!equals(_opaque, another._opaque)) {
3580             return false;
3581         }
3582         // is_hier_part
3583         // has_authority
3584         if (!equals(_authority, another._authority)) {
3585             return false;
3586         }
3587         // path
3588         if (!equals(_path, another._path)) {
3589             return false;
3590         }
3591         // has_query
3592         if (!equals(_query, another._query)) {
3593             return false;
3594         }
3595         // has_fragment?  should be careful of the only fragment case.
3596         if (!equals(_fragment, another._fragment)) {
3597             return false;
3598         }
3599         return true;
3600     }
3601 
3602     // ---------------------------------------------------------- Serialization
3603 
3604     /**
3605      * Write the content of this URI.
3606      *
3607      * @param oos the object-output stream
3608      * @throws IOException If an IO problem occurs.
3609      */
3610     private void writeObject(ObjectOutputStream oos)
3611         throws IOException {
3612 
3613         oos.defaultWriteObject();
3614     }
3615 
3616 
3617     /**
3618      * Read a URI.
3619      *
3620      * @param ois the object-input stream
3621      * @throws ClassNotFoundException If one of the classes specified in the
3622      * input stream cannot be found.
3623      * @throws IOException If an IO problem occurs.
3624      */
3625     private void readObject(ObjectInputStream ois)
3626         throws ClassNotFoundException, IOException {
3627 
3628         ois.defaultReadObject();
3629     }
3630 
3631     // -------------------------------------------------------------- Hash code
3632 
3633     /**
3634      * Return a hash code for this URI.
3635      *
3636      * @return a has code value for this URI
3637      */
3638     public int hashCode() {
3639         if (hash == 0) {
3640             char[] c = _uri;
3641             if (c != null) {
3642                 for (int i = 0, len = c.length; i < len; i++) {
3643                     hash = 31 * hash + c[i];
3644                 }
3645             }
3646             c = _fragment;
3647             if (c != null) {
3648                 for (int i = 0, len = c.length; i < len; i++) {
3649                     hash = 31 * hash + c[i];
3650                 }
3651             }
3652         }
3653         return hash;
3654     }
3655 
3656     // ------------------------------------------------------------- Comparison 
3657 
3658     /**
3659      * Compare this URI to another object. 
3660      *
3661      * @param obj the object to be compared.
3662      * @return 0, if it's same,
3663      * -1, if failed, first being compared with in the authority component
3664      * @throws ClassCastException not URI argument
3665      */
3666     public int compareTo(Object obj) throws ClassCastException {
3667 
3668         URI another = (URI) obj;
3669         if (!equals(_authority, another.getRawAuthority())) { 
3670             return -1;
3671         }
3672         return toString().compareTo(another.toString());
3673     }
3674 
3675     // ------------------------------------------------------------------ Clone
3676 
3677     /**
3678      * Create and return a copy of this object, the URI-reference containing
3679      * the userinfo component.  Notice that the whole URI-reference including
3680      * the userinfo component counld not be gotten as a <code>String</code>.
3681      * <p>
3682      * To copy the identical <code>URI</code> object including the userinfo
3683      * component, it should be used.
3684      *
3685      * @return a clone of this instance
3686      */
3687     public synchronized Object clone() throws CloneNotSupportedException {
3688 
3689         URI instance = (URI) super.clone();
3690 
3691         instance._uri = _uri;
3692         instance._scheme = _scheme;
3693         instance._opaque = _opaque;
3694         instance._authority = _authority;
3695         instance._userinfo = _userinfo;
3696         instance._host = _host;
3697         instance._port = _port;
3698         instance._path = _path;
3699         instance._query = _query;
3700         instance._fragment = _fragment;
3701         // the charset to do escape encoding for this instance
3702         instance.protocolCharset = protocolCharset;
3703         // flags
3704         instance._is_hier_part = _is_hier_part;
3705         instance._is_opaque_part = _is_opaque_part;
3706         instance._is_net_path = _is_net_path;
3707         instance._is_abs_path = _is_abs_path;
3708         instance._is_rel_path = _is_rel_path;
3709         instance._is_reg_name = _is_reg_name;
3710         instance._is_server = _is_server;
3711         instance._is_hostname = _is_hostname;
3712         instance._is_IPv4address = _is_IPv4address;
3713         instance._is_IPv6reference = _is_IPv6reference;
3714 
3715         return instance;
3716     }
3717 
3718     // ------------------------------------------------------------ Get the URI
3719 
3720     /**
3721      * It can be gotten the URI character sequence. It's raw-escaped.
3722      * For the purpose of the protocol to be transported, it will be useful.
3723      * <p>
3724      * It is clearly unwise to use a URL that contains a password which is
3725      * intended to be secret. In particular, the use of a password within
3726      * the 'userinfo' component of a URL is strongly disrecommended except
3727      * in those rare cases where the 'password' parameter is intended to be
3728      * public.
3729      * <p>
3730      * When you want to get each part of the userinfo, you need to use the
3731      * specific methods in the specific URL. It depends on the specific URL.
3732      *
3733      * @return the URI character sequence
3734      */
3735     public char[] getRawURI() {
3736         return _uri;
3737     }
3738 
3739 
3740     /**
3741      * It can be gotten the URI character sequence. It's escaped.
3742      * For the purpose of the protocol to be transported, it will be useful.
3743      *
3744      * @return the escaped URI string
3745      */
3746     public String getEscapedURI() {
3747         return (_uri == null) ? null : new String(_uri);
3748     }
3749     
3750 
3751     /**
3752      * It can be gotten the URI character sequence.
3753      *
3754      * @return the original URI string
3755      * @throws URIException incomplete trailing escape pattern or unsupported
3756      * character encoding
3757      * @see #decode
3758      */
3759     public String getURI() throws URIException {
3760         return (_uri == null) ? null : decode(_uri, getProtocolCharset());
3761     }
3762 
3763 
3764     /**
3765      * Get the URI reference character sequence.
3766      *
3767      * @return the URI reference character sequence
3768      */
3769     public char[] getRawURIReference() {
3770         if (_fragment == null) { 
3771             return _uri;
3772         }
3773         if (_uri == null) { 
3774             return _fragment;
3775         }
3776         // if _uri != null &&  _fragment != null
3777         String uriReference = new String(_uri) + "#" + new String(_fragment);
3778         return uriReference.toCharArray();
3779     }
3780 
3781 
3782     /**
3783      * Get the escaped URI reference string.
3784      *
3785      * @return the escaped URI reference string
3786      */
3787     public String getEscapedURIReference() {
3788         char[] uriReference = getRawURIReference();
3789         return (uriReference == null) ? null : new String(uriReference);
3790     }
3791 
3792 
3793     /**
3794      * Get the original URI reference string.
3795      *
3796      * @return the original URI reference string
3797      * @throws URIException If {@link #decode} fails.
3798      */
3799     public String getURIReference() throws URIException {
3800         char[] uriReference = getRawURIReference();
3801         return (uriReference == null) ? null : decode(uriReference,
3802                 getProtocolCharset());
3803     }
3804 
3805 
3806     /**
3807      * Get the escaped URI string.
3808      * <p>
3809      * On the document, the URI-reference form is only used without the userinfo
3810      * component like http://jakarta.apache.org/ by the security reason.
3811      * But the URI-reference form with the userinfo component could be parsed.
3812      * <p>
3813      * In other words, this URI and any its subclasses must not expose the
3814      * URI-reference expression with the userinfo component like
3815      * http://user:password@hostport/restricted_zone.<br>
3816      * It means that the API client programmer should extract each user and
3817      * password to access manually.  Probably it will be supported in the each
3818      * subclass, however, not a whole URI-reference expression.
3819      *
3820      * @return the escaped URI string
3821      * @see #clone()
3822      */
3823     public String toString() {
3824         return getEscapedURI();
3825     }
3826 
3827 
3828     // ------------------------------------------------------------ Inner class
3829 
3830     /** 
3831      * The charset-changed normal operation to represent to be required to
3832      * alert to user the fact the default charset is changed.
3833      */
3834     public static class DefaultCharsetChanged extends RuntimeException {
3835 
3836         // ------------------------------------------------------- constructors
3837 
3838         /**
3839          * The constructor with a reason string and its code arguments.
3840          *
3841          * @param reasonCode the reason code
3842          * @param reason the reason
3843          */
3844         public DefaultCharsetChanged(int reasonCode, String reason) {
3845             super(reason);
3846             this.reason = reason;
3847             this.reasonCode = reasonCode;
3848         }
3849 
3850         // ---------------------------------------------------------- constants
3851 
3852         /** No specified reason code. */
3853         public static final int UNKNOWN = 0;
3854 
3855         /** Protocol charset changed. */
3856         public static final int PROTOCOL_CHARSET = 1;
3857 
3858         /** Document charset changed. */
3859         public static final int DOCUMENT_CHARSET = 2;
3860 
3861         // ------------------------------------------------- instance variables
3862 
3863         /** The reason code. */
3864         private int reasonCode;
3865 
3866         /** The reason message. */
3867         private String reason;
3868 
3869         // ------------------------------------------------------------ methods
3870 
3871         /**
3872          * Get the reason code.
3873          *
3874          * @return the reason code
3875          */
3876         public int getReasonCode() {
3877             return reasonCode;
3878         }
3879 
3880         /**
3881          * Get the reason message.
3882          *
3883          * @return the reason message
3884          */
3885         public String getReason() {
3886             return reason;
3887         }
3888 
3889     }
3890 
3891 
3892     /** 
3893      * A mapping to determine the (somewhat arbitrarily) preferred charset for a
3894      * given locale.  Supports all locales recognized in JDK 1.1.
3895      * <p>
3896      * The distribution of this class is Servlets.com.    It was originally
3897      * written by Jason Hunter [jhunter at acm.org] and used by with permission.
3898      */
3899     public static class LocaleToCharsetMap {
3900 
3901         /** A mapping of language code to charset */
3902         private static final Hashtable LOCALE_TO_CHARSET_MAP;
3903         static {
3904             LOCALE_TO_CHARSET_MAP = new Hashtable();
3905             LOCALE_TO_CHARSET_MAP.put("ar", "ISO-8859-6");
3906             LOCALE_TO_CHARSET_MAP.put("be", "ISO-8859-5");
3907             LOCALE_TO_CHARSET_MAP.put("bg", "ISO-8859-5");
3908             LOCALE_TO_CHARSET_MAP.put("ca", "ISO-8859-1");
3909             LOCALE_TO_CHARSET_MAP.put("cs", "ISO-8859-2");
3910             LOCALE_TO_CHARSET_MAP.put("da", "ISO-8859-1");
3911             LOCALE_TO_CHARSET_MAP.put("de", "ISO-8859-1");
3912             LOCALE_TO_CHARSET_MAP.put("el", "ISO-8859-7");
3913             LOCALE_TO_CHARSET_MAP.put("en", "ISO-8859-1");
3914             LOCALE_TO_CHARSET_MAP.put("es", "ISO-8859-1");
3915             LOCALE_TO_CHARSET_MAP.put("et", "ISO-8859-1");
3916             LOCALE_TO_CHARSET_MAP.put("fi", "ISO-8859-1");
3917             LOCALE_TO_CHARSET_MAP.put("fr", "ISO-8859-1");
3918             LOCALE_TO_CHARSET_MAP.put("hr", "ISO-8859-2");
3919             LOCALE_TO_CHARSET_MAP.put("hu", "ISO-8859-2");
3920             LOCALE_TO_CHARSET_MAP.put("is", "ISO-8859-1");
3921             LOCALE_TO_CHARSET_MAP.put("it", "ISO-8859-1");
3922             LOCALE_TO_CHARSET_MAP.put("iw", "ISO-8859-8");
3923             LOCALE_TO_CHARSET_MAP.put("ja", "Shift_JIS");
3924             LOCALE_TO_CHARSET_MAP.put("ko", "EUC-KR");
3925             LOCALE_TO_CHARSET_MAP.put("lt", "ISO-8859-2");
3926             LOCALE_TO_CHARSET_MAP.put("lv", "ISO-8859-2");
3927             LOCALE_TO_CHARSET_MAP.put("mk", "ISO-8859-5");
3928             LOCALE_TO_CHARSET_MAP.put("nl", "ISO-8859-1");
3929             LOCALE_TO_CHARSET_MAP.put("no", "ISO-8859-1");
3930             LOCALE_TO_CHARSET_MAP.put("pl", "ISO-8859-2");
3931             LOCALE_TO_CHARSET_MAP.put("pt", "ISO-8859-1");
3932             LOCALE_TO_CHARSET_MAP.put("ro", "ISO-8859-2");
3933             LOCALE_TO_CHARSET_MAP.put("ru", "ISO-8859-5");
3934             LOCALE_TO_CHARSET_MAP.put("sh", "ISO-8859-5");
3935             LOCALE_TO_CHARSET_MAP.put("sk", "ISO-8859-2");
3936             LOCALE_TO_CHARSET_MAP.put("sl", "ISO-8859-2");
3937             LOCALE_TO_CHARSET_MAP.put("sq", "ISO-8859-2");
3938             LOCALE_TO_CHARSET_MAP.put("sr", "ISO-8859-5");
3939             LOCALE_TO_CHARSET_MAP.put("sv", "ISO-8859-1");
3940             LOCALE_TO_CHARSET_MAP.put("tr", "ISO-8859-9");
3941             LOCALE_TO_CHARSET_MAP.put("uk", "ISO-8859-5");
3942             LOCALE_TO_CHARSET_MAP.put("zh", "GB2312");
3943             LOCALE_TO_CHARSET_MAP.put("zh_TW", "Big5");
3944         }
3945        
3946         /**
3947          * Get the preferred charset for the given locale.
3948          *
3949          * @param locale the locale
3950          * @return the preferred charset or null if the locale is not
3951          * recognized.
3952          */
3953         public static String getCharset(Locale locale) {
3954             // try for an full name match (may include country)
3955             String charset =
3956                 (String) LOCALE_TO_CHARSET_MAP.get(locale.toString());
3957             if (charset != null) { 
3958                 return charset;
3959             }
3960            
3961             // if a full name didn't match, try just the language
3962             charset = (String) LOCALE_TO_CHARSET_MAP.get(locale.getLanguage());
3963             return charset;  // may be null
3964         }
3965 
3966     }
3967 
3968 }
3969 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/URIException.html100644 0 0 33741 10661532627 25334 0ustar 0 0 URIException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/URIException.java,v 1.12 2004/09/30 18:53:20 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  /**
34   * The URI parsing and escape encoding exception.
35   *
36   * @author <a href="mailto:jericho at apache.org">Sung-Gu</a>
37   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
38   * @version $Revision: 480424 $ $Date: 2002/03/14 15:14:01 
39   */
40  public class URIException extends HttpException {
41  
42      // ----------------------------------------------------------- constructors
43  
44      /**
45       * Default constructor.
46       */
47      public URIException() {
48      }
49  
50  
51      /**
52       * The constructor with a reason code argument.
53       *
54       * @param reasonCode the reason code
55       */
56      public URIException(int reasonCode) {
57          this.reasonCode = reasonCode;
58      }
59  
60  
61      /**
62       * The constructor with a reason string and its code arguments.
63       *
64       * @param reasonCode the reason code
65       * @param reason the reason
66       */
67      public URIException(int reasonCode, String reason) {
68          super(reason); // for backward compatibility of Throwable
69          this.reason = reason;
70          this.reasonCode = reasonCode;
71      }
72  
73  
74      /**
75       * The constructor with a reason string argument.
76       *
77       * @param reason the reason
78       */
79      public URIException(String reason) {
80          super(reason); // for backward compatibility of Throwable
81          this.reason = reason;
82          this.reasonCode = UNKNOWN;
83      }
84  
85      // -------------------------------------------------------------- constants
86  
87      /**
88       * No specified reason code.
89       */
90      public static final int UNKNOWN = 0;
91  
92  
93      /**
94       * The URI parsing error.
95       */
96      public static final int PARSING = 1;
97  
98  
99      /**
100      * The unsupported character encoding.
101      */
102     public static final int UNSUPPORTED_ENCODING = 2;
103 
104 
105     /**
106      * The URI escape encoding and decoding error.
107      */
108     public static final int ESCAPING = 3;
109 
110 
111     /**
112      * The DNS punycode encoding or decoding error.
113      */
114     public static final int PUNYCODE = 4;
115 
116     // ------------------------------------------------------------- properties
117 
118     /**
119      * The reason code.
120      */
121     protected int reasonCode;
122 
123 
124     /**
125      * The reason message.
126      */
127     protected String reason;
128 
129     // ---------------------------------------------------------------- methods
130 
131     /**
132      * Get the reason code.
133      *
134      * @return the reason code
135      */
136     public int getReasonCode() {
137         return reasonCode;
138     }
139 
140     /**
141      * Set the reason code.
142      *
143      * @param reasonCode the reason code
144      *
145      * @deprecated Callers should set the reason code as a parameter to the
146      *  constructor.
147      */
148     public void setReasonCode(int reasonCode) {
149         this.reasonCode = reasonCode;
150     }
151 
152 
153     /**
154      * Get the reason message.
155      *
156      * @return the reason message
157      *
158      * @deprecated You should instead call {@link #getMessage()}.
159      */
160     public String getReason() {
161         return reason;
162     }
163 
164 
165     /**
166      * Set the reason message.
167      *
168      * @param reason the reason message
169      *
170      * @deprecated Callers should instead set this via a parameter to the constructor.
171      */
172     public void setReason(String reason) {
173         this.reason = reason;
174     }
175 
176 
177 }
178 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/UsernamePasswordCredentials.html100644 0 0 43135 10661532627 30474 0ustar 0 0 UsernamePasswordCredentials xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/UsernamePasswordCredentials.java,v 1.14 2004/04/18 23:51:35 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import org.apache.commons.httpclient.util.LangUtils;
34  
35  /**
36   * <p>Username and password {@link Credentials}.</p>
37   *
38   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
39   * @author Sean C. Sullivan
40   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
41   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
42   * 
43   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
44   * 
45   */
46  public class UsernamePasswordCredentials implements Credentials {
47  
48      // ----------------------------------------------------------- Constructors
49  
50      /**
51       * Default constructor.
52       * 
53       * @deprecated Do not use. Null user name no longer allowed
54       */
55      public UsernamePasswordCredentials() {
56          super();
57      }
58  
59  
60      /**
61       * The constructor with the username and password combined string argument.
62       *
63       * @param usernamePassword the username:password formed string
64       * @see #toString
65       */
66      public UsernamePasswordCredentials(String usernamePassword) {
67          super();
68          if (usernamePassword == null) {
69              throw new IllegalArgumentException("Username:password string may not be null");            
70          }
71          int atColon = usernamePassword.indexOf(':');
72          if (atColon >= 0) {
73              this.userName = usernamePassword.substring(0, atColon);
74              this.password = usernamePassword.substring(atColon + 1);
75          } else {
76              this.userName = usernamePassword;
77          }
78      }
79  
80  
81      /**
82       * The constructor with the username and password arguments.
83       *
84       * @param userName the user name
85       * @param password the password
86       */
87      public UsernamePasswordCredentials(String userName, String password) {
88          super();
89          if (userName == null) {
90              throw new IllegalArgumentException("Username may not be null");            
91          }
92          this.userName = userName;
93          this.password = password;
94      }
95  
96      // ----------------------------------------------------- Instance Variables
97  
98      /**
99       * User name.
100      */
101     private String userName;
102 
103 
104     /**
105      * Password.
106      */
107     private String password;
108 
109 
110     // ------------------------------------------------------------- Properties
111 
112 
113     /**
114      * User name property setter. User name may not be null.
115      *
116      * @param userName
117      * @see #getUserName()
118      * 
119      * @deprecated Do not use. The UsernamePasswordCredentials objects should be immutable
120      */
121     public void setUserName(String userName) {
122         if (userName == null) {
123             throw new IllegalArgumentException("Username may not be null");            
124         }
125         this.userName = userName;
126     }
127 
128 
129     /**
130      * User name property getter.
131      *
132      * @return the userName
133      * @see #setUserName(String)
134      */
135     public String getUserName() {
136         return userName;
137     }
138 
139 
140     /**
141      * Password property setter.
142      *
143      * @param password
144      * @see #getPassword()
145      * 
146      * @deprecated Do not use. The UsernamePasswordCredentials objects should be immutable
147      */
148     public void setPassword(String password) {
149         this.password = password;
150     }
151 
152 
153     /**
154      * Password property getter.
155      *
156      * @return the password
157      * @see #setPassword(String)
158      */
159     public String getPassword() {
160         return password;
161     }
162 
163     
164     /**
165      * Get this object string.
166      *
167      * @return the username:password formed string
168      */
169     public String toString() {
170         StringBuffer result = new StringBuffer();
171         result.append(this.userName);
172         result.append(":");
173         result.append((this.password == null) ? "null" : this.password);
174         return result.toString();
175     }
176 
177     /**
178      * Does a hash of both user name and password.
179      *
180      * @return The hash code including user name and password.
181      */
182     public int hashCode() {
183         int hash = LangUtils.HASH_SEED;
184         hash = LangUtils.hashCode(hash, this.userName);
185         hash = LangUtils.hashCode(hash, this.password);
186         return hash;
187     }
188 
189     /**
190      * These credentials are assumed equal if the username and password are the
191      * same.
192      *
193      * @param o The other object to compare with.
194      *
195      * @return  <code>true</code> if the object is equivalent.
196      */
197     public boolean equals(Object o) {
198         if (o == null) return false;
199         if (this == o) return true;
200         // note - to allow for sub-classing, this checks that class is the same
201         // rather than do "instanceof".
202         if (this.getClass().equals(o.getClass())) {
203             UsernamePasswordCredentials that = (UsernamePasswordCredentials) o;
204 
205             if (LangUtils.equals(this.userName, that.userName)
206                     && LangUtils.equals(this.password, that.password) ) {
207                 return true;
208             }
209         }
210         return false;
211     }
212 
213 }
214 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/Wire.html100644 0 0 35427 10661532627 23727 0ustar 0 0 Wire xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Wire.java,v 1.9 2004/06/24 21:39:52 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.io.ByteArrayInputStream;
36  import org.apache.commons.logging.Log;
37  import org.apache.commons.logging.LogFactory;
38  
39  /**
40   * Logs data to the wire LOG.
41   *
42   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
43   * 
44   * @since 2.0beta1
45   */
46  class Wire {
47  
48      public static Wire HEADER_WIRE = new Wire(LogFactory.getLog("httpclient.wire.header"));
49      
50      public static Wire CONTENT_WIRE = new Wire(LogFactory.getLog("httpclient.wire.content"));
51      
52      /** Log for any wire messages. */
53      private Log log;
54      
55      private Wire(Log log) {
56          this.log = log;
57      }
58      
59      private void wire(String header, InputStream instream)
60        throws IOException {
61          StringBuffer buffer = new StringBuffer();
62          int ch;
63          while ((ch = instream.read()) != -1) {
64              if (ch == 13) {
65                  buffer.append("[\\r]");
66              } else if (ch == 10) {
67                      buffer.append("[\\n]\"");
68                      buffer.insert(0, "\"");
69                      buffer.insert(0, header);
70                      log.debug(buffer.toString());
71                      buffer.setLength(0);
72              } else if ((ch < 32) || (ch > 127)) {
73                  buffer.append("[0x");
74                  buffer.append(Integer.toHexString(ch));
75                  buffer.append("]");
76              } else {
77                  buffer.append((char) ch);
78              }
79          } 
80          if (buffer.length() > 0) {
81              buffer.append("\"");
82              buffer.insert(0, "\"");
83              buffer.insert(0, header);
84              log.debug(buffer.toString());
85          }
86      }
87  
88  
89      public boolean enabled() {
90          return log.isDebugEnabled();
91      }    
92      
93      public void output(InputStream outstream)
94        throws IOException {
95          if (outstream == null) {
96              throw new IllegalArgumentException("Output may not be null"); 
97          }
98          wire(">> ", outstream);
99      }
100 
101     public void input(InputStream instream)
102       throws IOException {
103         if (instream == null) {
104             throw new IllegalArgumentException("Input may not be null"); 
105         }
106         wire("<< ", instream);
107     }
108 
109     public void output(byte[] b, int off, int len)
110       throws IOException {
111         if (b == null) {
112             throw new IllegalArgumentException("Output may not be null"); 
113         }
114         wire(">> ", new ByteArrayInputStream(b, off, len));
115     }
116 
117     public void input(byte[] b, int off, int len)
118       throws IOException {
119         if (b == null) {
120             throw new IllegalArgumentException("Input may not be null"); 
121         }
122         wire("<< ", new ByteArrayInputStream(b, off, len));
123     }
124 
125     public void output(byte[] b)
126       throws IOException {
127         if (b == null) {
128             throw new IllegalArgumentException("Output may not be null"); 
129         }
130         wire(">> ", new ByteArrayInputStream(b));
131     }
132 
133     public void input(byte[] b)
134       throws IOException {
135         if (b == null) {
136             throw new IllegalArgumentException("Input may not be null"); 
137         }
138         wire("<< ", new ByteArrayInputStream(b));
139     }
140 
141     public void output(int b)
142       throws IOException {
143         output(new byte[] {(byte) b});
144     }
145 
146     public void input(int b)
147       throws IOException {
148         input(new byte[] {(byte) b});
149     }
150 
151     public void output(final String s)
152       throws IOException {
153         if (s == null) {
154             throw new IllegalArgumentException("Output may not be null"); 
155         }
156         output(s.getBytes());
157     }
158 
159     public void input(final String s)
160       throws IOException {
161         if (s == null) {
162             throw new IllegalArgumentException("Input may not be null"); 
163         }
164         input(s.getBytes());
165     }
166 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/WireLogInputStream.html100644 0 0 21470 10661532627 26556 0ustar 0 0 WireLogInputStream xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/WireLogInputStream.java,v 1.15 2004/06/24 21:39:52 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.FilterInputStream;
34  import java.io.IOException;
35  import java.io.InputStream;
36  
37  /**
38   * Logs all data read to the wire LOG.
39   *
40   * @author Ortwin Gl?ck
41   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
42   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
43   * 
44   * @since 2.0
45   */
46  class WireLogInputStream extends FilterInputStream {
47       
48      /** Original input stream. */
49      private InputStream in;
50  
51      /** The wire log to use for writing. */
52      private Wire wire;
53      
54      /**
55       * Create an instance that wraps the specified input stream.
56       * @param in The input stream.
57       * @param wire The wire log to use.
58       */
59      public WireLogInputStream(InputStream in, Wire wire) {
60          super(in);
61          this.in = in;
62          this.wire = wire;
63      }
64      /**
65       * 
66       * @see java.io.InputStream#read(byte[], int, int)
67       */
68      public int read(byte[] b, int off, int len) throws IOException {
69          int l = this.in.read(b,  off,  len);
70          if (l > 0) {
71              wire.input(b, off, l);
72          }
73          return l;
74      }
75  
76      /**
77       * 
78       * @see java.io.InputStream#read()
79       */
80      public int read() throws IOException {
81          int l = this.in.read();
82          if (l > 0) { 
83              wire.input(l);
84          }
85          return l;
86      }
87  
88      /**
89       * 
90       * @see java.io.InputStream#read(byte[])
91       */
92      public int read(byte[] b) throws IOException {
93          int l = this.in.read(b);
94          if (l > 0) {
95              wire.input(b, 0, l);
96          }
97          return l;
98      }
99  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/WireLogOutputStream.html100644 0 0 20033 10661532627 26751 0ustar 0 0 WireLogOutputStream xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/WireLogOutputStream.java,v 1.7 2004/06/24 21:39:52 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient;
32  
33  import java.io.FilterOutputStream;
34  import java.io.IOException;
35  import java.io.OutputStream;
36  
37  /**
38   * Logs all data written to the wire LOG.
39   *
40   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
41   * 
42   * @since 2.0beta1
43   */
44  class WireLogOutputStream extends FilterOutputStream {
45  
46      /** Original input stream. */
47      private OutputStream out;
48      
49      /** The wire log to use. */
50      private Wire wire;
51  
52      /**
53       * Create an instance that wraps the specified output stream.
54       * @param out The output stream.
55       * @param wire The Wire log to use.
56       */
57      public WireLogOutputStream(OutputStream out, Wire wire) {
58          super(out);
59          this.out = out;
60          this.wire = wire;
61      }
62      
63      /**
64       * 
65       * @see java.io.OutputStream#write(byte[], int, int)
66       */
67      public void write(byte[] b, int off, int len) throws IOException {
68          this.out.write(b,  off,  len);
69          wire.output(b, off, len);
70      }
71  
72      /**
73       * 
74       * @see java.io.OutputStream#write()
75       */
76      public void write(int b) throws IOException {
77          this.out.write(b);
78          wire.output(b);
79      }
80  
81      /**
82       * 
83       * @see java.io.OutputStream#write(byte[])
84       */
85      public void write(byte[] b) throws IOException {
86          this.out.write(b);
87          wire.output(b);
88      }
89  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/AuthChallengeException.html100644 0 0 16122 10661532627 30334 0ustar 0 0 AuthChallengeException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthChallengeException.java,v 1.2 2004/04/18 23:51:36 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  /**
34   * Signals a failure processing authentication challenge
35   *
36   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
37   * 
38   * @since 3.0
39   */
40  public class AuthChallengeException extends AuthenticationException {
41  
42      /**
43       * Creates a new AuthChallengeException with a <tt>null</tt> detail message. 
44       */
45      public AuthChallengeException() {
46          super();
47      }
48  
49      /**
50       * Creates a new AuthChallengeException with the specified message.
51       * 
52       * @param message the exception detail message
53       */
54      public AuthChallengeException(String message) {
55          super(message);
56      }
57  
58      /**
59       * Creates a new AuthChallengeException with the specified detail message and cause.
60       * 
61       * @param message the exception detail message
62       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
63       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
64       */
65      public AuthChallengeException(String message, Throwable cause) {
66          super(message, cause);
67      }
68  
69  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/AuthChallengeParser.html100644 0 0 32267 10661532627 27642 0ustar 0 0 AuthChallengeParser xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthChallengeParser.java,v 1.10 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import java.util.HashMap;
34  import java.util.List;
35  import java.util.Map;
36  
37  import org.apache.commons.httpclient.Header;
38  import org.apache.commons.httpclient.NameValuePair;
39  import org.apache.commons.httpclient.util.ParameterParser;
40  
41  /**
42   * This class provides utility methods for parsing HTTP www and proxy authentication 
43   * challenges.
44   * 
45   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
46   * 
47   * @since 2.0beta1
48   */
49  public final class AuthChallengeParser {
50      /** 
51       * Extracts authentication scheme from the given authentication 
52       * challenge.
53       *
54       * @param challengeStr the authentication challenge string
55       * @return authentication scheme
56       * 
57       * @throws MalformedChallengeException when the authentication challenge string
58       *  is malformed
59       * 
60       * @since 2.0beta1
61       */
62      public static String extractScheme(final String challengeStr) 
63        throws MalformedChallengeException {
64          if (challengeStr == null) {
65              throw new IllegalArgumentException("Challenge may not be null"); 
66          }
67          int idx = challengeStr.indexOf(' ');
68          String s = null; 
69          if (idx == -1) {
70              s = challengeStr;
71          } else {
72              s = challengeStr.substring(0, idx);
73          }
74          if (s.equals("")) {
75              throw new MalformedChallengeException("Invalid challenge: " + challengeStr);
76          }
77          return s.toLowerCase();
78      }
79  
80      /** 
81       * Extracts a map of challenge parameters from an authentication challenge.
82       * Keys in the map are lower-cased
83       *
84       * @param challengeStr the authentication challenge string
85       * @return a map of authentication challenge parameters
86       * @throws MalformedChallengeException when the authentication challenge string
87       *  is malformed
88       * 
89       * @since 2.0beta1
90       */
91      public static Map extractParams(final String challengeStr)
92        throws MalformedChallengeException {
93          if (challengeStr == null) {
94              throw new IllegalArgumentException("Challenge may not be null"); 
95          }
96          int idx = challengeStr.indexOf(' ');
97          if (idx == -1) {
98              throw new MalformedChallengeException("Invalid challenge: " + challengeStr);
99          }
100         Map map = new HashMap();
101         ParameterParser parser = new ParameterParser();
102         List params = parser.parse(
103             challengeStr.substring(idx + 1, challengeStr.length()), ',');
104         for (int i = 0; i < params.size(); i++) {
105             NameValuePair param = (NameValuePair) params.get(i);
106             map.put(param.getName().toLowerCase(), param.getValue());
107         }
108         return map;
109     }
110 
111     /** 
112      * Extracts a map of challenges ordered by authentication scheme name
113      *
114      * @param headers the array of authorization challenges
115      * @return a map of authorization challenges
116      * 
117      * @throws MalformedChallengeException if any of challenge strings
118      *  is malformed
119      * 
120      * @since 3.0
121      */
122     public static Map parseChallenges(final Header[] headers)
123       throws MalformedChallengeException {
124         if (headers == null) {
125             throw new IllegalArgumentException("Array of challenges may not be null");
126         }
127         String challenge = null;
128         Map challengemap = new HashMap(headers.length); 
129         for (int i = 0; i < headers.length; i++) {
130             challenge = headers[i].getValue();
131             String s = AuthChallengeParser.extractScheme(challenge);
132             challengemap.put(s, challenge);
133         }
134         return challengemap;
135    }
136 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/AuthChallengeProcessor.html100644 0 0 40500 10661532627 30352 0ustar 0 0 AuthChallengeProcessor xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthChallengeProcessor.java,v 1.2 2004/04/18 23:51:36 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import java.util.Collection;
34  import java.util.Iterator;
35  import java.util.Map;
36  
37  import org.apache.commons.httpclient.params.HttpParams;
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  
41  /**
42   * This class provides utility methods for processing HTTP www and proxy authentication 
43   * challenges.
44   * 
45   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
46   * 
47   * @since 3.0
48   */
49  public final class AuthChallengeProcessor {
50  
51      private static final Log LOG = LogFactory.getLog(AuthChallengeProcessor.class);
52  
53      private HttpParams params = null;
54      
55      /**
56       * Creates an authentication challenge processor with the given {@link HttpParams HTTP 
57       * parameters}
58       * 
59       * @param params the {@link HttpParams HTTP parameters} used by this processor
60       */
61      public AuthChallengeProcessor(final HttpParams params) {
62          super();
63          if (params == null) {
64              throw new IllegalArgumentException("Parameter collection may not be null");
65          }
66          this.params = params;
67      }
68  
69      /**
70       * Determines the preferred {@link AuthScheme authentication scheme} that can be used 
71       * to respond to the given collection of challenges.
72       * 
73       * @param challenges the collection of authentication challenges
74       * 
75       * @return the preferred {@link AuthScheme authentication scheme}
76       * 
77       * @throws AuthChallengeException if the preferred authentication scheme 
78       * cannot be determined or is not supported
79       */
80      public AuthScheme selectAuthScheme(final Map challenges) throws AuthChallengeException {
81          if (challenges == null) {
82              throw new IllegalArgumentException("Challenge map may not be null"); 
83          }
84          Collection authPrefs = (Collection) this.params.getParameter(
85              AuthPolicy.AUTH_SCHEME_PRIORITY);
86          if (authPrefs == null || authPrefs.isEmpty()) {
87              authPrefs = AuthPolicy.getDefaultAuthPrefs();    
88          }
89          if (LOG.isDebugEnabled()) {
90              LOG.debug("Supported authentication schemes in the order of preference: " 
91                  + authPrefs);
92          }
93          AuthScheme authscheme = null;
94          String challenge = null;
95          Iterator item = authPrefs.iterator();
96          while (item.hasNext()) {
97              String id = (String) item.next();
98              challenge = (String) challenges.get(id.toLowerCase()); 
99              if (challenge != null) {
100                 if (LOG.isInfoEnabled()) {
101                     LOG.info(id + " authentication scheme selected");
102                 }
103                 try {
104                     authscheme = AuthPolicy.getAuthScheme(id);
105                 } catch (IllegalStateException e) {
106                     throw new AuthChallengeException(e.getMessage());
107                 }
108                 break;
109             } else {
110                 if (LOG.isDebugEnabled()) {
111                     LOG.debug("Challenge for " + id + " authentication scheme not available");
112                     // Try again
113                 }
114             }
115         }
116         if (authscheme == null) {
117             // If none selected, something is wrong
118             throw new AuthChallengeException(
119                 "Unable to respond to any of these challenges: "
120                     + challenges);
121         }
122         return authscheme;
123     }
124 
125     /**
126      * Processes the given collection of challenges and updates the 
127      * {@link AuthState state} of the authentication process.
128      * 
129      * @param challenges the collection of authentication challenges
130      * 
131      * @return the {@link AuthScheme authentication scheme} used to 
132      * process the challenge
133      * 
134      * @throws AuthChallengeException if authentication challenges cannot be 
135      * successfully processed or the preferred authentication scheme cannot
136      * be determined
137      */
138     public AuthScheme processChallenge(final AuthState state, final Map challenges)
139         throws MalformedChallengeException, AuthenticationException
140     {    
141         if (state == null) {
142             throw new IllegalArgumentException("Authentication state may not be null"); 
143         }
144         if (challenges == null) {
145             throw new IllegalArgumentException("Challenge map may not be null"); 
146         }
147         
148         if (state.isPreemptive() || state.getAuthScheme() == null) {
149             // Authentication not attempted before
150             state.setAuthScheme(selectAuthScheme(challenges));
151         }
152         AuthScheme authscheme = state.getAuthScheme();
153         String id = authscheme.getSchemeName();
154         if (LOG.isDebugEnabled()) {
155             LOG.debug("Using authentication scheme: " + id);
156         }
157         String challenge = (String) challenges.get(id.toLowerCase());
158         if (challenge == null) {
159             throw new AuthenticationException(id + 
160                 " authorization challenge expected, but not found");
161         }
162         authscheme.processChallenge(challenge);
163         LOG.debug("Authorization challenge processed");
164         return authscheme;
165     }
166 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/AuthPolicy.html100644 0 0 43241 10661532627 26034 0ustar 0 0 AuthPolicy xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthPolicy.java,v 1.6 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import java.util.ArrayList;
34  import java.util.HashMap;
35  import java.util.List;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  
40  /**
41   * Authentication policy class. The Authentication policy provides corresponding
42   * authentication scheme interfrace for a given type of authorization challenge. 
43   * <p>The following specifications are provided:
44   *  <ul>
45   *   <li><tt>Basic</tt>: Basic authentication scheme as defined in RFC2617
46   *           (considered inherently insecure, but most widely supported)
47   *   <li><tt>Digest</tt>: Digest authentication scheme as defined in RFC2617
48   *   <li><tt>NTLM</tt>: The NTLM scheme is a proprietary Microsoft Windows 
49   *           Authentication protocol (considered to be the most secure among
50   *           currently supported authentication schemes)
51   *  </ul>
52   * 
53   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
54   *
55   * @version $Revision: 480424 $
56   * @since 3.0
57   */
58  public abstract class AuthPolicy {
59  
60      private static final HashMap   SCHEMES     = new HashMap();
61      private static final ArrayList SCHEME_LIST = new ArrayList();
62      
63      /**
64       * The key used to look up the list of IDs of supported {@link AuthScheme 
65       * authentication schemes} in their order of preference. The scheme IDs are 
66       * stored in a {@link java.util.Collection} as {@link java.lang.String}s. 
67       * 
68       * <p>
69       * If several schemes are returned in the <tt>WWW-Authenticate</tt> 
70       * or <tt>Proxy-Authenticate</tt> header, this parameter defines which
71       * {@link AuthScheme authentication schemes} takes precedence over others.
72       * The first item in the collection represents the most preferred 
73       * {@link AuthScheme authentication scheme}, the last item represents the ID 
74       * of the least preferred one.
75       * </p>
76       * 
77       * @see org.apache.commons.httpclient.params.DefaultHttpParams
78       */
79      public static final String AUTH_SCHEME_PRIORITY = "http.auth.scheme-priority";
80  
81      /**
82       * The NTLM scheme is a proprietary Microsoft Windows Authentication 
83       * protocol (considered to be the most secure among currently supported 
84       * authentication schemes).
85       */
86      public static final String NTLM = "NTLM";
87      
88      /** 
89       * Digest authentication scheme as defined in RFC2617.
90       */
91      public static final String DIGEST = "Digest";
92  
93      /** 
94       * Basic authentication scheme as defined in RFC2617 (considered inherently
95       * insecure, but most widely supported)
96       */
97      public static final String BASIC = "Basic";
98      
99      static {
100         AuthPolicy.registerAuthScheme(NTLM,   NTLMScheme.class);
101         AuthPolicy.registerAuthScheme(DIGEST, DigestScheme.class);
102         AuthPolicy.registerAuthScheme(BASIC,  BasicScheme.class);
103     }
104     
105     /** Log object. */
106     protected static final Log LOG = LogFactory.getLog(AuthPolicy.class);
107 
108     /**
109      * Registers a class implementing an {@link AuthScheme authentication scheme} with 
110      * the given identifier. If a class with the given ID already exists it will be overridden.  
111      * This ID is the same one used to retrieve the {@link AuthScheme authentication scheme} 
112      * from {@link #getAuthScheme(String)}.
113      * 
114      * <p>
115      * Please note that custom authentication preferences, if used, need to be updated accordingly 
116      * for the new {@link AuthScheme authentication scheme} to take effect.
117      * </p>    
118      * 
119      * @param id the identifier for this scheme
120      * @param clazz the class to register
121      * 
122      * @see #getAuthScheme(String)
123      * @see #AUTH_SCHEME_PRIORITY
124      */
125     public static synchronized void registerAuthScheme(final String id, Class clazz) {
126          if (id == null) {
127              throw new IllegalArgumentException("Id may not be null");
128          }
129         if (clazz == null) {
130             throw new IllegalArgumentException("Authentication scheme class may not be null");
131         }
132         SCHEMES.put(id.toLowerCase(), clazz);
133         SCHEME_LIST.add(id.toLowerCase());
134     }
135 
136     /**
137      * Unregisters the class implementing an {@link AuthScheme authentication scheme} with 
138      * the given ID.
139      * 
140      * @param id the ID of the class to unregister
141      */
142     public static synchronized void unregisterAuthScheme(final String id) {
143          if (id == null) {
144              throw new IllegalArgumentException("Id may not be null");
145          }
146         SCHEMES.remove(id.toLowerCase());
147         SCHEME_LIST.remove(id.toLowerCase());
148     }
149 
150     /**
151      * Gets the {@link AuthScheme authentication scheme} with the given ID.
152      * 
153      * @param id the {@link AuthScheme authentication scheme} ID
154      * 
155      * @return {@link AuthScheme authentication scheme}
156      * 
157      * @throws IllegalStateException if a scheme with the ID cannot be found
158      */
159     public static synchronized AuthScheme getAuthScheme(final String id) 
160         throws IllegalStateException {
161 
162         if (id == null) {
163             throw new IllegalArgumentException("Id may not be null");
164         }
165         Class clazz = (Class)SCHEMES.get(id.toLowerCase());
166         if (clazz != null) {
167             try {
168                 return (AuthScheme)clazz.newInstance();
169             } catch (Exception e) {
170                 LOG.error("Error initializing authentication scheme: " + id, e);
171                 throw new IllegalStateException(id + 
172                     " authentication scheme implemented by " +
173                     clazz.getName() + " could not be initialized");
174             }
175         } else {
176             throw new IllegalStateException("Unsupported authentication scheme " + id);
177         }
178     } 
179 
180     /**
181      * Returns a list containing all registered {@link AuthScheme authentication 
182      * schemes} in their default order.
183      * 
184      * @return {@link AuthScheme authentication scheme}
185      */
186     public static synchronized List getDefaultAuthPrefs() {
187         return (List)SCHEME_LIST.clone(); 
188     } 
189 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/AuthScheme.html100644 0 0 41351 10661532627 26001 0ustar 0 0 AuthScheme xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthScheme.java,v 1.12 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import org.apache.commons.httpclient.Credentials;
34  import org.apache.commons.httpclient.HttpMethod;
35  
36  /**
37   * <p>
38   * This interface represents an abstract challenge-response oriented 
39   * authentication scheme.
40   * </p>
41   * <p>
42   * An authentication scheme should be able to support the following
43   * functions:
44   * <ul>
45   *   <li>Parse and process the challenge sent by the targer server
46   *       in response to request for a protected resource
47   *   <li>Provide its textual designation
48   *   <li>Provide its parameters, if available
49   *   <li>Provide the realm this authentication scheme is applicable to,
50   *       if available
51   *   <li>Generate authorization string for the given set of credentials,
52   *       request method and URI as specificed in the HTTP request line
53   *       in response to the actual authorization challenge
54   * </ul>
55   * </p>
56   * <p>
57   * Authentication schemes may ignore method name and URI parameters
58   * if they are not relevant for the given authentication mechanism
59   * </p>
60   * <p>
61   * Authentication schemes may be stateful involving a series of 
62   * challenge-response exchanges
63   * </p>
64   * 
65   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
66   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
67   *
68   * @since 2.0beta1
69   */
70  
71  public interface AuthScheme {
72  
73      /**
74       * Processes the given challenge token. Some authentication schemes
75       * may involve multiple challenge-response exchanges. Such schemes must be able 
76       * to maintain the state information when dealing with sequential challenges 
77       * 
78       * @param challenge the challenge string
79       * 
80       * @since 3.0
81       */
82      void processChallenge(final String challenge) throws MalformedChallengeException;
83      
84      /**
85       * Returns textual designation of the given authentication scheme.
86       * 
87       * @return the name of the given authentication scheme
88       */
89      String getSchemeName();
90  
91      /**
92       * Returns authentication parameter with the given name, if available.
93       * 
94       * @param name The name of the parameter to be returned
95       * 
96       * @return the parameter with the given name
97       */
98      String getParameter(final String name);
99  
100     /**
101      * Returns authentication realm. If the concept of an authentication
102      * realm is not applicable to the given authentication scheme, returns
103      * <code>null</code>.
104      * 
105      * @return the authentication realm
106      */
107     String getRealm();
108     
109     /**
110      * Returns a String identifying the authentication challenge.  This is
111      * used, in combination with the host and port to determine if
112      * authorization has already been attempted or not.  Schemes which
113      * require multiple requests to complete the authentication should
114      * return a different value for each stage in the request.
115      * 
116      * <p>Additionally, the ID should take into account any changes to the
117      * authentication challenge and return a different value when appropriate.
118      * For example when the realm changes in basic authentication it should be
119      * considered a different authentication attempt and a different value should
120      * be returned.</p>
121      * 
122      * @return String a String identifying the authentication challenge.  The
123      * returned value may be null.
124      * 
125      * @deprecated no longer used
126      */
127     String getID();
128 
129     /**
130      * Tests if the authentication scheme is provides authorization on a per
131      * connection basis instead of usual per request basis
132      * 
133      * @return <tt>true</tt> if the scheme is connection based, <tt>false</tt>
134      * if the scheme is request based.
135      * 
136      * @since 3.0
137      */
138     boolean isConnectionBased();    
139     
140     /**
141      * Authentication process may involve a series of challenge-response exchanges.
142      * This method tests if the authorization process has been completed, either
143      * successfully or unsuccessfully, that is, all the required authorization 
144      * challenges have been processed in their entirety.
145      * 
146      * @return <tt>true</tt> if the authentication process has been completed, 
147      * <tt>false</tt> otherwise.
148      * 
149      * @since 3.0
150      */
151     boolean isComplete();    
152     /**
153      * @deprecated Use {@link #authenticate(Credentials, HttpMethod)}
154      * 
155      * Produces an authorization string for the given set of {@link Credentials},
156      * method name and URI using the given authentication scheme in response to 
157      * the actual authorization challenge.
158      * 
159      * @param credentials The set of credentials to be used for athentication
160      * @param method The name of the method that requires authorization. 
161      *   This parameter may be ignored, if it is irrelevant 
162      *   or not applicable to the given authentication scheme
163      * @param uri The URI for which authorization is needed. 
164      *   This parameter may be ignored, if it is irrelevant or not 
165      *   applicable to the given authentication scheme
166      * @throws AuthenticationException if authorization string cannot 
167      *   be generated due to an authentication failure
168      * 
169      * @return the authorization string
170      * 
171      * @see org.apache.commons.httpclient.HttpMethod#getName()
172      * @see org.apache.commons.httpclient.HttpMethod#getPath()
173      */
174     String authenticate(Credentials credentials, String method, String uri) 
175       throws AuthenticationException;
176 
177     /**
178      * Produces an authorization string for the given set of {@link Credentials}.
179      * 
180      * @param credentials The set of credentials to be used for athentication
181      * @param method The method being authenticated
182      * @throws AuthenticationException if authorization string cannot 
183      *   be generated due to an authentication failure
184      * 
185      * @return the authorization string
186      * 
187      * @since 3.0
188      */
189     String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException;
190     
191 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/AuthSchemeBase.html100644 0 0 21262 10661532627 26573 0ustar 0 0 AuthSchemeBase xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthSchemeBase.java,v 1.7 2004/04/18 23:51:36 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  /**
34   * <p>
35   * Abstract authentication scheme class that implements {@link AuthScheme}
36   * interface and provides a default contstructor.
37   * </p>
38   * @deprecated No longer used
39   *
40   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
41   */
42  public abstract class AuthSchemeBase implements AuthScheme {
43  
44      /**
45       * Original challenge string as received from the server.
46       */
47      private String challenge = null;
48  
49      /**
50       * Constructor for an abstract authetication schemes.
51       * 
52       * @param challenge authentication challenge
53       * 
54       * @throws MalformedChallengeException is thrown if the authentication challenge
55       * is malformed
56       * 
57       * @deprecated Use parameterless constructor and {@link AuthScheme#processChallenge(String)} 
58       *             method
59       */
60      public AuthSchemeBase(final String challenge) 
61        throws MalformedChallengeException {
62          super();
63          if (challenge == null) {
64              throw new IllegalArgumentException("Challenge may not be null"); 
65          }
66          this.challenge = challenge;
67      }
68  
69      /**
70       * @see java.lang.Object#equals(Object)
71       */
72      public boolean equals(Object obj) {
73          if (obj instanceof AuthSchemeBase) {
74              return this.challenge.equals(((AuthSchemeBase) obj).challenge);
75          } else {
76              return super.equals(obj);
77          }
78      }
79  
80      /**
81       * @see java.lang.Object#hashCode()
82       */
83      public int hashCode() {
84          return this.challenge.hashCode();
85      }
86  
87      /**
88       * @see java.lang.Object#toString()
89       */
90      public String toString() {
91          return this.challenge;
92      }
93  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/AuthScope.html100644 0 0 67076 10661532627 25662 0ustar 0 0 AuthScope xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthScope.java,v 1.2 2004/06/23 06:50:25 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import org.apache.commons.httpclient.util.LangUtils;
34  
35  /** 
36   * The class represents an authentication scope consisting of a host name,
37   * a port number, a realm name and an authentication scheme name which 
38   * {@link org.apache.commons.httpclient.Credentials} apply to.
39   * 
40   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
41   * @author <a href="mailto:adrian@intencha.com">Adrian Sutton</a>
42   * 
43   * @since 3.0
44   */
45  public class AuthScope {
46      
47      /** 
48       * The <tt>null</tt> value represents any host. In the future versions of 
49       * HttpClient the use of this parameter will be discontinued.  
50       */
51      public static final String ANY_HOST = null;
52  
53      /** 
54       * The <tt>-1</tt> value represents any port.  
55       */
56      public static final int ANY_PORT = -1;
57  
58      /** 
59       * The <tt>null</tt> value represents any realm.  
60       */
61      public static final String ANY_REALM = null;
62  
63      /** 
64       * The <tt>null</tt> value represents any authentication scheme.  
65       */
66      public static final String ANY_SCHEME = null;
67      
68      /** 
69       * Default scope matching any host, port, realm and authentication scheme. 
70       * In the future versions of HttpClient the use of this parameter will be 
71       * discontinued.  
72       */
73      public static final AuthScope ANY = new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, ANY_SCHEME);
74  
75      /** The authentication scheme the credentials apply to. */
76      private String scheme = null;
77      
78      /** The realm the credentials apply to. */
79      private String realm = null;
80      
81      /** The host the credentials apply to. */
82      private String host = null;
83          
84      /** The port the credentials apply to. */
85      private int port = -1;
86          
87      /** Creates a new credentials scope for the given 
88       * <tt>host</tt>, <tt>port</tt>, <tt>realm</tt>, and 
89       * <tt>authentication scheme</tt>.
90       * 
91       * @param host the host the credentials apply to. May be set
92       *   to <tt>null</tt> if credenticals are applicable to
93       *   any host. 
94       * @param port the port the credentials apply to. May be set
95       *   to negative value if credenticals are applicable to
96       *   any port. 
97       * @param realm the realm the credentials apply to. May be set 
98       *   to <tt>null</tt> if credenticals are applicable to
99       *   any realm. 
100      * @param scheme the authentication scheme the credentials apply to. 
101      *   May be set to <tt>null</tt> if credenticals are applicable to
102      *   any authentication scheme. 
103      * 
104      * @since 3.0
105      */
106     public AuthScope(final String host, int port, 
107         final String realm, final String scheme)
108     {
109         this.host =   (host == null)   ? ANY_HOST: host.toLowerCase();
110         this.port =   (port < 0)       ? ANY_PORT: port;
111         this.realm =  (realm == null)  ? ANY_REALM: realm;
112         this.scheme = (scheme == null) ? ANY_SCHEME: scheme.toUpperCase();;
113     }
114     
115     /** Creates a new credentials scope for the given 
116      * <tt>host</tt>, <tt>port</tt>, <tt>realm</tt>, and any
117      * authentication scheme.
118      * 
119      * @param host the host the credentials apply to. May be set
120      *   to <tt>null</tt> if credenticals are applicable to
121      *   any host. 
122      * @param port the port the credentials apply to. May be set
123      *   to negative value if credenticals are applicable to
124      *   any port. 
125      * @param realm the realm the credentials apply to. May be set 
126      *   to <tt>null</tt> if credenticals are applicable to
127      *   any realm. 
128      * 
129      * @since 3.0
130      */
131     public AuthScope(final String host, int port, final String realm) {
132         this(host, port, realm, ANY_SCHEME);
133     }
134     
135     /** Creates a new credentials scope for the given 
136      * <tt>host</tt>, <tt>port</tt>, any realm name, and any
137      * authentication scheme.
138      * 
139      * @param host the host the credentials apply to. May be set
140      *   to <tt>null</tt> if credenticals are applicable to
141      *   any host. 
142      * @param port the port the credentials apply to. May be set
143      *   to negative value if credenticals are applicable to
144      *   any port. 
145      * 
146      * @since 3.0
147      */
148     public AuthScope(final String host, int port) {
149         this(host, port, ANY_REALM, ANY_SCHEME);
150     }
151     
152     /** 
153      * Creates a copy of the given credentials scope.
154      * 
155      * @since 3.0
156      */
157     public AuthScope(final AuthScope authscope) {
158         super();
159         if (authscope == null) {
160             throw new IllegalArgumentException("Scope may not be null");
161         }
162         this.host = authscope.getHost();
163         this.port = authscope.getPort();
164         this.realm = authscope.getRealm();
165         this.scheme = authscope.getScheme();
166     }
167     
168     /**
169      * @return the host
170      * 
171      * @since 3.0
172      */
173     public String getHost() {
174         return this.host;
175     }
176 
177     /**
178      * @return the port
179      * 
180      * @since 3.0
181      */
182     public int getPort() {
183         return this.port;
184     }
185 
186     /**
187      * @return the realm name
188      * 
189      * @since 3.0
190      */
191     public String getRealm() {
192         return this.realm;
193     }
194 
195     /**
196      * @return the scheme type
197      * 
198      * @since 3.0
199      */
200     public String getScheme() {
201         return this.scheme;
202     }
203 
204     /** Determines if the given parameters are equal.
205      * 
206      * @param p1 the parameter
207      * @param p2 the other parameter
208      * @return boolean true if the parameters are equal, otherwise false.
209      */
210     private static boolean paramsEqual(final String p1, final String p2) {
211         if (p1 == null) {
212             return p1 == p2;
213         } else {
214             return p1.equals(p2);
215         }
216     }
217 
218     /** Determines if the given parameters are equal.  
219      * 
220      * @param p1 the parameter
221      * @param p2 the other parameter
222      * @return boolean true if the parameters are equal, otherwise false.
223      */
224     private static boolean paramsEqual(int p1, int p2) {
225         return p1 == p2;
226     }
227 
228     /**
229      * Tests if the authentication scopes match. 
230      * 
231      * @return the match factor. Negative value signifies no match. 
232      *    Non-negative signifies a match. The greater the returned value 
233      *    the closer the match.
234      * 
235      * @since 3.0
236      */
237     public int match(final AuthScope that) {
238         int factor = 0;
239         if (paramsEqual(this.scheme, that.scheme)) {
240             factor += 1;
241         } else {
242             if (this.scheme != ANY_SCHEME && that.scheme != ANY_SCHEME) {
243                 return -1;
244             }
245         }
246         if (paramsEqual(this.realm, that.realm)) {
247             factor += 2;
248         } else {
249             if (this.realm != ANY_REALM && that.realm != ANY_REALM) {
250                 return -1;
251             }
252         }
253         if (paramsEqual(this.port, that.port)) {
254             factor += 4;
255         } else {
256             if (this.port != ANY_PORT && that.port != ANY_PORT) {
257                 return -1;
258             }
259         }
260         if (paramsEqual(this.host, that.host)) {
261             factor += 8;
262         } else {
263             if (this.host != ANY_HOST && that.host != ANY_HOST) {
264                 return -1;
265             }
266         }
267         return factor;
268     }
269 
270     /**
271      * @see java.lang.Object#equals(Object)
272      */
273     public boolean equals(Object o) {
274         if (o == null) {
275             return false;
276         }
277         if (o == this) {
278             return true;
279         }
280         if (!(o instanceof AuthScope)) {
281             return super.equals(o);
282         }
283         AuthScope that = (AuthScope) o;
284         return 
285         paramsEqual(this.host, that.host) 
286           && paramsEqual(this.port, that.port)
287           && paramsEqual(this.realm, that.realm)
288           && paramsEqual(this.scheme, that.scheme);
289     }
290 
291     /**
292      * @see java.lang.Object#toString()
293      */
294     public String toString() {
295         StringBuffer buffer = new StringBuffer();
296         if (this.scheme != null) {
297             buffer.append(this.scheme.toUpperCase());
298             buffer.append(' ');
299         }
300         if (this.realm != null) {
301             buffer.append('\'');
302             buffer.append(this.realm);
303             buffer.append('\'');
304         } else {
305             buffer.append("<any realm>");
306         }
307         if (this.host != null) {
308             buffer.append('@');
309             buffer.append(this.host);
310             if (this.port >= 0) {
311                 buffer.append(':');
312                 buffer.append(this.port);
313             }
314         }
315         return buffer.toString();
316     }
317     
318     /**
319      * @see java.lang.Object#hashCode()
320      */
321     public int hashCode() {
322         int hash = LangUtils.HASH_SEED;
323         hash = LangUtils.hashCode(hash, this.host);
324         hash = LangUtils.hashCode(hash, this.port);
325         hash = LangUtils.hashCode(hash, this.realm);
326         hash = LangUtils.hashCode(hash, this.scheme);
327         return hash;
328     }
329 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/AuthState.html100644 0 0 41203 10661532627 25651 0ustar 0 0 AuthState xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthState.java,v 1.3 2004/11/02 19:39:16 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  /**
34   * This class provides detailed information about the state of the
35   * authentication process.
36   * 
37   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
38   * @since 3.0
39   */
40  public class AuthState {
41  
42      public static final String PREEMPTIVE_AUTH_SCHEME = "basic";
43      
44      /** Actual authentication scheme */
45      private AuthScheme authScheme = null;
46  
47      /** Whether an authetication challenged has been received */
48      private boolean authRequested = false;
49  
50      /** Whether the authetication challenge has been responsed to */
51      private boolean authAttempted = false;
52  
53      /** Whether preemtive authentication is attempted */
54      private boolean preemptive  = false; 
55        
56      /**
57       * Default constructor.
58       * 
59       */
60      public AuthState() {
61          super();
62      }
63  
64      /**
65       * Invalidates the authentication state by resetting its parameters.
66       */
67      public void invalidate() {
68          this.authScheme = null;
69          this.authRequested = false;
70          this.authAttempted = false;
71          this.preemptive = false;
72      }
73  
74      /** 
75       * Tests whether authenication challenge has been received
76       *  
77       * @return <tt>true</tt> if authenication challenge has been received, 
78       *  <tt>false</tt> otherwise
79       */
80      public boolean isAuthRequested() {
81          return this.authRequested;
82      }
83          
84      /** 
85       * Sets authentication request status
86       *  
87       * @param challengeReceived <tt>true</tt> if authenication has been requested, 
88       *  <tt>false</tt> otherwise
89       */
90      public void setAuthRequested(boolean challengeReceived) {
91          this.authRequested = challengeReceived;
92      }
93      
94      /** 
95       * Tests whether authenication challenge has been responsed to
96       *  
97       * @return <tt>true</tt> if authenication challenge has been responsed to, 
98       *  <tt>false</tt> otherwise
99       */
100     public boolean isAuthAttempted() {
101         return this.authAttempted;
102     }
103         
104     /** 
105      * Sets authentication attempt status
106      *  
107      * @param challengeResponded <tt>true</tt> if authenication has been attempted, 
108      *  <tt>false</tt> otherwise
109      */
110     public void setAuthAttempted(boolean challengeResponded) {
111         this.authAttempted = challengeResponded;
112     }
113     
114     /**
115      * Preemptively assigns Basic authentication scheme.
116      */
117     public void setPreemptive() {
118         if (!this.preemptive) {
119             if (this.authScheme != null) {
120                 throw new IllegalStateException("Authentication state already initialized");
121             }
122             this.authScheme = AuthPolicy.getAuthScheme(PREEMPTIVE_AUTH_SCHEME);
123             this.preemptive = true;
124         }
125     }
126 
127     /**
128      * Tests if preemptive authentication is used.
129      * 
130      * @return <tt>true</tt> if using the default Basic {@link AuthScheme 
131      * authentication scheme}, <tt>false</tt> otherwise.
132      */
133     public boolean isPreemptive() {
134         return this.preemptive;
135     }
136     
137     /**
138      * Assigns the given {@link AuthScheme authentication scheme}.
139      * 
140      * @param authScheme the {@link AuthScheme authentication scheme}
141      */
142     public void setAuthScheme(final AuthScheme authScheme) {
143         if (authScheme == null) {
144             invalidate();
145             return;
146         }
147         if (this.preemptive && !(this.authScheme.getClass().isInstance(authScheme))) {
148             this.preemptive = false;
149             this.authAttempted = false;
150         }
151         this.authScheme = authScheme;
152     }
153 
154     /**
155      * Returns the {@link AuthScheme authentication scheme}.
156      * 
157      * @return {@link AuthScheme authentication scheme}
158      */
159     public AuthScheme getAuthScheme() {
160         return authScheme;
161     }
162     
163     /**
164      * Returns the authentication realm.
165      * 
166      * @return the name of the authentication realm
167      */
168     public String getRealm() {
169         if (this.authScheme != null) {
170             return this.authScheme.getRealm();
171         } else {
172             return null;
173         }
174     }
175     
176     public String toString() {
177         StringBuffer buffer = new StringBuffer();
178         buffer.append("Auth state: auth requested [");
179         buffer.append(this.authRequested);
180         buffer.append("]; auth attempted [");
181         buffer.append(this.authAttempted);
182         if (this.authScheme != null) {
183             buffer.append("]; auth scheme [");
184             buffer.append(this.authScheme.getSchemeName());
185             buffer.append("]; realm [");
186             buffer.append(this.authScheme.getRealm());            
187         }
188         buffer.append("] preemptive [");
189         buffer.append(this.preemptive);
190         buffer.append("]");
191         return buffer.toString();
192     }
193 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/AuthenticationException.html100644 0 0 16472 10661532627 30617 0ustar 0 0 AuthenticationException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthenticationException.java,v 1.6 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import org.apache.commons.httpclient.ProtocolException;
34  
35  /**
36   * Signals a failure in authentication process
37   *
38   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
39   * 
40   * @since 2.0
41   */
42  public class AuthenticationException extends ProtocolException {
43  
44      /**
45       * Creates a new AuthenticationException with a <tt>null</tt> detail message. 
46       */
47      public AuthenticationException() {
48          super();
49      }
50  
51      /**
52       * Creates a new AuthenticationException with the specified message.
53       * 
54       * @param message the exception detail message
55       */
56      public AuthenticationException(String message) {
57          super(message);
58      }
59  
60      /**
61       * Creates a new AuthenticationException with the specified detail message and cause.
62       * 
63       * @param message the exception detail message
64       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
65       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
66       * 
67       * @since 3.0
68       */
69      public AuthenticationException(String message, Throwable cause) {
70          super(message, cause);
71      }
72  
73  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/BasicScheme.html100644 0 0 54655 10661532627 26134 0ustar 0 0 BasicScheme xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/BasicScheme.java,v 1.17 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import org.apache.commons.codec.binary.Base64;
34  import org.apache.commons.httpclient.Credentials;
35  import org.apache.commons.httpclient.HttpMethod;
36  import org.apache.commons.httpclient.UsernamePasswordCredentials;
37  import org.apache.commons.httpclient.util.EncodingUtil;
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  
41  /**
42   * <p>
43   * Basic authentication scheme as defined in RFC 2617.
44   * </p>
45   * 
46   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
47   * @author Rodney Waldhoff
48   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
49   * @author Ortwin Gl?ck
50   * @author Sean C. Sullivan
51   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
52   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
53   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
54   */
55  
56  public class BasicScheme extends RFC2617Scheme {
57      
58      /** Log object for this class. */
59      private static final Log LOG = LogFactory.getLog(BasicScheme.class);
60      
61      /** Whether the basic authentication process is complete */
62      private boolean complete;
63      
64      /**
65       * Default constructor for the basic authetication scheme.
66       * 
67       * @since 3.0
68       */
69      public BasicScheme() {
70          super();
71          this.complete = false;
72      }
73  
74      /**
75       * Constructor for the basic authetication scheme.
76       * 
77       * @param challenge authentication challenge
78       * 
79       * @throws MalformedChallengeException is thrown if the authentication challenge
80       * is malformed
81       * 
82       * @deprecated Use parameterless constructor and {@link AuthScheme#processChallenge(String)} 
83       *             method
84       */
85      public BasicScheme(final String challenge) throws MalformedChallengeException {
86          super(challenge);
87          this.complete = true;
88      }
89  
90      /**
91       * Returns textual designation of the basic authentication scheme.
92       * 
93       * @return <code>basic</code>
94       */
95      public String getSchemeName() {
96          return "basic";
97      }
98  
99      /**
100      * Processes the Basic challenge.
101      *  
102      * @param challenge the challenge string
103      * 
104      * @throws MalformedChallengeException is thrown if the authentication challenge
105      * is malformed
106      * 
107      * @since 3.0
108      */
109     public void processChallenge(String challenge) 
110         throws MalformedChallengeException 
111     {
112         super.processChallenge(challenge);
113         this.complete = true;
114     }
115 
116     /**
117      * Tests if the Basic authentication process has been completed.
118      * 
119      * @return <tt>true</tt> if Basic authorization has been processed,
120      *   <tt>false</tt> otherwise.
121      * 
122      * @since 3.0
123      */
124     public boolean isComplete() {
125         return this.complete;
126     }
127 
128     /**
129      * Produces basic authorization string for the given set of 
130      * {@link Credentials}.
131      * 
132      * @param credentials The set of credentials to be used for athentication
133      * @param method Method name is ignored by the basic authentication scheme
134      * @param uri URI is ignored by the basic authentication scheme
135      * @throws InvalidCredentialsException if authentication credentials
136      *         are not valid or not applicable for this authentication scheme
137      * @throws AuthenticationException if authorization string cannot 
138      *   be generated due to an authentication failure
139      * 
140      * @return a basic authorization string
141      * 
142      * @deprecated Use {@link #authenticate(Credentials, HttpMethod)}
143      */
144     public String authenticate(Credentials credentials, String method, String uri)
145       throws AuthenticationException {
146 
147         LOG.trace("enter BasicScheme.authenticate(Credentials, String, String)");
148 
149         UsernamePasswordCredentials usernamepassword = null;
150         try {
151             usernamepassword = (UsernamePasswordCredentials) credentials;
152         } catch (ClassCastException e) {
153             throw new InvalidCredentialsException(
154              "Credentials cannot be used for basic authentication: " 
155               + credentials.getClass().getName());
156         }
157         return BasicScheme.authenticate(usernamepassword);
158     }
159 
160     /**
161      * Returns <tt>false</tt>. Basic authentication scheme is request based.
162      * 
163      * @return <tt>false</tt>.
164      * 
165      * @since 3.0
166      */
167     public boolean isConnectionBased() {
168         return false;    
169     }
170 
171     /**
172      * Produces basic authorization string for the given set of {@link Credentials}.
173      * 
174      * @param credentials The set of credentials to be used for athentication
175      * @param method The method being authenticated
176      * @throws InvalidCredentialsException if authentication credentials
177      *         are not valid or not applicable for this authentication scheme
178      * @throws AuthenticationException if authorization string cannot 
179      *   be generated due to an authentication failure
180      * 
181      * @return a basic authorization string
182      * 
183      * @since 3.0
184      */
185     public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {
186 
187         LOG.trace("enter BasicScheme.authenticate(Credentials, HttpMethod)");
188 
189         if (method == null) {
190             throw new IllegalArgumentException("Method may not be null");
191         }
192         UsernamePasswordCredentials usernamepassword = null;
193         try {
194             usernamepassword = (UsernamePasswordCredentials) credentials;
195         } catch (ClassCastException e) {
196             throw new InvalidCredentialsException(
197                     "Credentials cannot be used for basic authentication: " 
198                     + credentials.getClass().getName());
199         }
200         return BasicScheme.authenticate(
201             usernamepassword, 
202             method.getParams().getCredentialCharset());
203     }
204     
205     /**
206      * @deprecated Use {@link #authenticate(UsernamePasswordCredentials, String)}
207      * 
208      * Returns a basic <tt>Authorization</tt> header value for the given 
209      * {@link UsernamePasswordCredentials}.
210      * 
211      * @param credentials The credentials to encode.
212      * 
213      * @return a basic authorization string
214      */
215     public static String authenticate(UsernamePasswordCredentials credentials) {
216         return authenticate(credentials, "ISO-8859-1");
217     }
218 
219     /**
220      * Returns a basic <tt>Authorization</tt> header value for the given 
221      * {@link UsernamePasswordCredentials} and charset.
222      * 
223      * @param credentials The credentials to encode.
224      * @param charset The charset to use for encoding the credentials
225      * 
226      * @return a basic authorization string
227      * 
228      * @since 3.0
229      */
230     public static String authenticate(UsernamePasswordCredentials credentials, String charset) {
231 
232         LOG.trace("enter BasicScheme.authenticate(UsernamePasswordCredentials, String)");
233 
234         if (credentials == null) {
235             throw new IllegalArgumentException("Credentials may not be null"); 
236         }
237         if (charset == null || charset.length() == 0) {
238             throw new IllegalArgumentException("charset may not be null or empty");
239         }
240         StringBuffer buffer = new StringBuffer();
241         buffer.append(credentials.getUserName());
242         buffer.append(":");
243         buffer.append(credentials.getPassword());
244         
245         return "Basic " + EncodingUtil.getAsciiString(
246                 Base64.encodeBase64(EncodingUtil.getBytes(buffer.toString(), charset)));
247     }
248     
249 }

././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/CredentialsNotAvailableException.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/CredentialsNotAvailableException100644 0 0 16361 10661532627 31411 0ustar 0 0 CredentialsNotAvailableException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/CredentialsNotAvailableException.java,v 1.4 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  /**
34   * Authentication credentials required to respond to a authentication 
35   * challenge are not available
36   *
37   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
38   * 
39   * @since 3.0
40   */
41  public class CredentialsNotAvailableException extends AuthenticationException {
42      /**
43       * Creates a new CredentialsNotAvailableException with a <tt>null</tt> detail message. 
44       */
45      public CredentialsNotAvailableException() {
46          super();
47      }
48  
49      /**
50       * Creates a new CredentialsNotAvailableException with the specified message.
51       * 
52       * @param message the exception detail message
53       */
54      public CredentialsNotAvailableException(String message) {
55          super(message);
56      }
57  
58      /**
59       * Creates a new CredentialsNotAvailableException with the specified detail message and cause.
60       * 
61       * @param message the exception detail message
62       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
63       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
64       */
65      public CredentialsNotAvailableException(String message, Throwable cause) {
66          super(message, cause);
67      }
68  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/CredentialsProvider.html100644 0 0 21263 10661532627 27723 0ustar 0 0 CredentialsProvider xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/CredentialsProvider.java,v 1.6 2004/07/05 22:46:59 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import org.apache.commons.httpclient.Credentials;
34  
35  /**
36   * <p>
37   * Credentials provider interface can be used to provide {@link 
38   * org.apache.commons.httpclient.HttpMethod HTTP method} with a means to request
39   * authentication credentials if no credentials have been given or given
40   * credentials are incorrect.
41   * </p>
42   * <p>
43   * HttpClient makes no provisions to check whether the same credentials have
44   * been tried already. It is a responsibility of the custom credentials provider
45   * to keep track of authentication attempts and to ensure that credentials known
46   * to be invalid are not retried. HttpClient will simply store the set of
47   * credentials returned by the custom credentials provider in the
48   * {@link org.apache.commons.httpclient.HttpState http state} object and will
49   * attempt to use these credentials for all subsequent requests with the given
50   * authentication scope.
51   * </p>
52   * <p>
53   * Classes implementing this interface must synchronize access to shared data as
54   * methods of this interfrace may be executed from multiple threads
55   * </p>
56   * 
57   * 
58   * @author Ortwin Glueck
59   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
60   * 
61   * @since 3.0
62   */
63  public interface CredentialsProvider {
64  
65      /**
66       * Sets the credentials provider parameter.
67       * <p>
68       * This parameter expects a value of type {@link CredentialsProvider}.
69       * </p>
70       */ 
71      public static final String PROVIDER = "http.authentication.credential-provider";
72      
73      /**
74       * Requests additional {@link Credentials authentication credentials}.
75       * 
76       * @param scheme the {@link AuthScheme authentication scheme}
77       * @param host the authentication host
78       * @param port the port of the authentication host
79       * @param proxy <tt>true</tt> if authenticating with a proxy,
80       *              <tt>false</tt> otherwise
81       */ 
82      public Credentials getCredentials(
83          final AuthScheme scheme, 
84          final String host, 
85          int port, 
86          boolean proxy) throws CredentialsNotAvailableException; 
87  
88  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/DigestScheme.html100644 0 0 146123 10661532627 26342 0ustar 0 0 DigestScheme xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/DigestScheme.java,v 1.22 2004/12/30 11:01:27 oglueck Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import java.security.MessageDigest;
34  import java.security.NoSuchAlgorithmException;
35  import java.util.ArrayList;
36  import java.util.List;
37  import java.util.StringTokenizer;
38  
39  import org.apache.commons.httpclient.Credentials;
40  import org.apache.commons.httpclient.HttpClientError;
41  import org.apache.commons.httpclient.HttpMethod;
42  import org.apache.commons.httpclient.NameValuePair;
43  import org.apache.commons.httpclient.UsernamePasswordCredentials;
44  import org.apache.commons.httpclient.util.EncodingUtil;
45  import org.apache.commons.httpclient.util.ParameterFormatter;
46  import org.apache.commons.logging.Log;
47  import org.apache.commons.logging.LogFactory;
48  
49  /**
50   * <p>
51   * Digest authentication scheme as defined in RFC 2617.
52   * Both MD5 (default) and MD5-sess are supported.
53   * Currently only qop=auth or no qop is supported. qop=auth-int
54   * is unsupported. If auth and auth-int are provided, auth is
55   * used.
56   * </p>
57   * <p>
58   * Credential charset is configured via the 
59   * {@link org.apache.commons.httpclient.params.HttpMethodParams#CREDENTIAL_CHARSET credential
60   * charset} parameter.  Since the digest username is included as clear text in the generated 
61   * Authentication header, the charset of the username must be compatible with the 
62   * {@link org.apache.commons.httpclient.params.HttpMethodParams#HTTP_ELEMENT_CHARSET http element 
63   * charset}.
64   * </p>
65   * TODO: make class more stateful regarding repeated authentication requests
66   * 
67   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
68   * @author Rodney Waldhoff
69   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
70   * @author Ortwin Gl?ck
71   * @author Sean C. Sullivan
72   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
73   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
74   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
75   */
76  
77  public class DigestScheme extends RFC2617Scheme {
78      
79      /** Log object for this class. */
80      private static final Log LOG = LogFactory.getLog(DigestScheme.class);
81  
82      /**
83       * Hexa values used when creating 32 character long digest in HTTP DigestScheme
84       * in case of authentication.
85       * 
86       * @see #encode(byte[])
87       */
88      private static final char[] HEXADECIMAL = {
89          '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 
90          'e', 'f'
91      };
92      
93      /** Whether the digest authentication process is complete */
94      private boolean complete;
95      
96      //TODO: supply a real nonce-count, currently a server will interprete a repeated request as a replay  
97      private static final String NC = "00000001"; //nonce-count is always 1
98      private static final int QOP_MISSING = 0;
99      private static final int QOP_AUTH_INT = 1;
100     private static final int QOP_AUTH = 2;
101 
102     private int qopVariant = QOP_MISSING;
103     private String cnonce;
104 
105     private final ParameterFormatter formatter;
106     /**
107      * Default constructor for the digest authetication scheme.
108      * 
109      * @since 3.0
110      */
111     public DigestScheme() {
112         super();
113         this.complete = false;
114         this.formatter = new ParameterFormatter();
115     }
116 
117     /**
118      * Gets an ID based upon the realm and the nonce value.  This ensures that requests
119      * to the same realm with different nonce values will succeed.  This differentiation
120      * allows servers to request re-authentication using a fresh nonce value.
121      * 
122      * @deprecated no longer used
123      */
124     public String getID() {
125         
126         String id = getRealm();
127         String nonce = getParameter("nonce");
128         if (nonce != null) {
129             id += "-" + nonce;
130         }
131         
132         return id;
133     }
134 
135     /**
136      * Constructor for the digest authetication scheme.
137      * 
138      * @param challenge authentication challenge
139      * 
140      * @throws MalformedChallengeException is thrown if the authentication challenge
141      * is malformed
142      * 
143      * @deprecated Use parameterless constructor and {@link AuthScheme#processChallenge(String)} 
144      *             method
145      */
146     public DigestScheme(final String challenge) 
147       throws MalformedChallengeException {
148         this();
149         processChallenge(challenge);
150     }
151 
152     /**
153      * Processes the Digest challenge.
154      *  
155      * @param challenge the challenge string
156      * 
157      * @throws MalformedChallengeException is thrown if the authentication challenge
158      * is malformed
159      * 
160      * @since 3.0
161      */
162     public void processChallenge(final String challenge) 
163       throws MalformedChallengeException {
164         super.processChallenge(challenge);
165         
166         if (getParameter("realm") == null) {
167             throw new MalformedChallengeException("missing realm in challange");
168         }
169         if (getParameter("nonce") == null) {
170             throw new MalformedChallengeException("missing nonce in challange");   
171         }
172         
173         boolean unsupportedQop = false;
174         // qop parsing
175         String qop = getParameter("qop");
176         if (qop != null) {
177             StringTokenizer tok = new StringTokenizer(qop,",");
178             while (tok.hasMoreTokens()) {
179                 String variant = tok.nextToken().trim();
180                 if (variant.equals("auth")) {
181                     qopVariant = QOP_AUTH;
182                     break; //that's our favourite, because auth-int is unsupported
183                 } else if (variant.equals("auth-int")) {
184                     qopVariant = QOP_AUTH_INT;               
185                 } else {
186                     unsupportedQop = true;
187                     LOG.warn("Unsupported qop detected: "+ variant);   
188                 }     
189             }
190         }        
191         
192         if (unsupportedQop && (qopVariant == QOP_MISSING)) {
193             throw new MalformedChallengeException("None of the qop methods is supported");   
194         }
195         
196         cnonce = createCnonce();   
197         this.complete = true;
198     }
199 
200     /**
201      * Tests if the Digest authentication process has been completed.
202      * 
203      * @return <tt>true</tt> if Digest authorization has been processed,
204      *   <tt>false</tt> otherwise.
205      * 
206      * @since 3.0
207      */
208     public boolean isComplete() {
209         String s = getParameter("stale");
210         if ("true".equalsIgnoreCase(s)) {
211             return false;
212         } else {
213             return this.complete;
214         }
215     }
216 
217     /**
218      * Returns textual designation of the digest authentication scheme.
219      * 
220      * @return <code>digest</code>
221      */
222     public String getSchemeName() {
223         return "digest";
224     }
225 
226     /**
227      * Returns <tt>false</tt>. Digest authentication scheme is request based.
228      * 
229      * @return <tt>false</tt>.
230      * 
231      * @since 3.0
232      */
233     public boolean isConnectionBased() {
234         return false;    
235     }
236 
237     /**
238      * Produces a digest authorization string for the given set of 
239      * {@link Credentials}, method name and URI.
240      * 
241      * @param credentials A set of credentials to be used for athentication
242      * @param method the name of the method that requires authorization. 
243      * @param uri The URI for which authorization is needed. 
244      * 
245      * @throws InvalidCredentialsException if authentication credentials
246      *         are not valid or not applicable for this authentication scheme
247      * @throws AuthenticationException if authorization string cannot 
248      *   be generated due to an authentication failure
249      * 
250      * @return a digest authorization string
251      * 
252      * @see org.apache.commons.httpclient.HttpMethod#getName()
253      * @see org.apache.commons.httpclient.HttpMethod#getPath()
254      * 
255      * @deprecated Use {@link #authenticate(Credentials, HttpMethod)}
256      */
257     public String authenticate(Credentials credentials, String method, String uri)
258       throws AuthenticationException {
259 
260         LOG.trace("enter DigestScheme.authenticate(Credentials, String, String)");
261 
262         UsernamePasswordCredentials usernamepassword = null;
263         try {
264             usernamepassword = (UsernamePasswordCredentials) credentials;
265         } catch (ClassCastException e) {
266             throw new InvalidCredentialsException(
267              "Credentials cannot be used for digest authentication: " 
268               + credentials.getClass().getName());
269         }
270         getParameters().put("methodname", method);
271         getParameters().put("uri", uri);
272         String digest = createDigest(
273             usernamepassword.getUserName(),
274             usernamepassword.getPassword());
275         return "Digest " + createDigestHeader(usernamepassword.getUserName(), digest);
276     }
277 
278     /**
279      * Produces a digest authorization string for the given set of 
280      * {@link Credentials}, method name and URI.
281      * 
282      * @param credentials A set of credentials to be used for athentication
283      * @param method The method being authenticated
284      * 
285      * @throws InvalidCredentialsException if authentication credentials
286      *         are not valid or not applicable for this authentication scheme
287      * @throws AuthenticationException if authorization string cannot 
288      *   be generated due to an authentication failure
289      * 
290      * @return a digest authorization string
291      * 
292      * @since 3.0
293      */
294     public String authenticate(Credentials credentials, HttpMethod method)
295     throws AuthenticationException {
296 
297         LOG.trace("enter DigestScheme.authenticate(Credentials, HttpMethod)");
298 
299         UsernamePasswordCredentials usernamepassword = null;
300         try {
301             usernamepassword = (UsernamePasswordCredentials) credentials;
302         } catch (ClassCastException e) {
303             throw new InvalidCredentialsException(
304                     "Credentials cannot be used for digest authentication: " 
305                     + credentials.getClass().getName());
306         }
307         getParameters().put("methodname", method.getName());
308         StringBuffer buffer = new StringBuffer(method.getPath());
309         String query = method.getQueryString();
310         if (query != null) {
311             if (query.indexOf("?") != 0) {
312                 buffer.append("?");
313             }
314             buffer.append(method.getQueryString());
315         }
316         getParameters().put("uri", buffer.toString());
317         String charset = getParameter("charset");
318         if (charset == null) {
319             getParameters().put("charset", method.getParams().getCredentialCharset());
320         }
321         String digest = createDigest(
322             usernamepassword.getUserName(),
323             usernamepassword.getPassword());
324         return "Digest " + createDigestHeader(usernamepassword.getUserName(),
325                 digest);
326     }
327     
328     /**
329      * Creates an MD5 response digest.
330      * 
331      * @param uname Username
332      * @param pwd Password
333      * @param charset The credential charset
334      * 
335      * @return The created digest as string. This will be the response tag's
336      *         value in the Authentication HTTP header.
337      * @throws AuthenticationException when MD5 is an unsupported algorithm
338      */
339     private String createDigest(final String uname, final String pwd) throws AuthenticationException {
340 
341         LOG.trace("enter DigestScheme.createDigest(String, String, Map)");
342 
343         final String digAlg = "MD5";
344 
345         // Collecting required tokens
346         String uri = getParameter("uri");
347         String realm = getParameter("realm");
348         String nonce = getParameter("nonce");
349         String qop = getParameter("qop");
350         String method = getParameter("methodname");
351         String algorithm = getParameter("algorithm");
352         // If an algorithm is not specified, default to MD5.
353         if (algorithm == null) {
354             algorithm = "MD5";
355         }
356         // If an charset is not specified, default to ISO-8859-1.
357         String charset = getParameter("charset");
358         if (charset == null) {
359             charset = "ISO-8859-1";
360         }
361 
362         if (qopVariant == QOP_AUTH_INT) {
363             LOG.warn("qop=auth-int is not supported");
364             throw new AuthenticationException(
365                 "Unsupported qop in HTTP Digest authentication");   
366         }
367 
368         MessageDigest md5Helper;
369 
370         try {
371             md5Helper = MessageDigest.getInstance(digAlg);
372         } catch (Exception e) {
373             throw new AuthenticationException(
374               "Unsupported algorithm in HTTP Digest authentication: "
375                + digAlg);
376         }
377 
378         // 3.2.2.2: Calculating digest
379         StringBuffer tmp = new StringBuffer(uname.length() + realm.length() + pwd.length() + 2);
380         tmp.append(uname);
381         tmp.append(':');
382         tmp.append(realm);
383         tmp.append(':');
384         tmp.append(pwd);
385         // unq(username-value) ":" unq(realm-value) ":" passwd
386         String a1 = tmp.toString();
387         //a1 is suitable for MD5 algorithm
388         if(algorithm.equals("MD5-sess")) {
389             // H( unq(username-value) ":" unq(realm-value) ":" passwd )
390             //      ":" unq(nonce-value)
391             //      ":" unq(cnonce-value)
392 
393             String tmp2=encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset)));
394             StringBuffer tmp3 = new StringBuffer(tmp2.length() + nonce.length() + cnonce.length() + 2);
395             tmp3.append(tmp2);
396             tmp3.append(':');
397             tmp3.append(nonce);
398             tmp3.append(':');
399             tmp3.append(cnonce);
400             a1 = tmp3.toString();
401         } else if(!algorithm.equals("MD5")) {
402             LOG.warn("Unhandled algorithm " + algorithm + " requested");
403         }
404         String md5a1 = encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset)));
405 
406         String a2 = null;
407         if (qopVariant == QOP_AUTH_INT) {
408             LOG.error("Unhandled qop auth-int");
409             //we do not have access to the entity-body or its hash
410             //TODO: add Method ":" digest-uri-value ":" H(entity-body)      
411         } else {
412             a2 = method + ":" + uri;
413         }
414         String md5a2 = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(a2)));
415 
416         // 3.2.2.1
417         String serverDigestValue;
418         if (qopVariant == QOP_MISSING) {
419             LOG.debug("Using null qop method");
420             StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length() + md5a2.length());
421             tmp2.append(md5a1);
422             tmp2.append(':');
423             tmp2.append(nonce);
424             tmp2.append(':');
425             tmp2.append(md5a2);
426             serverDigestValue = tmp2.toString();
427         } else {
428             if (LOG.isDebugEnabled()) {
429                 LOG.debug("Using qop method " + qop);
430             }
431             String qopOption = getQopVariantString();
432             StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length()
433                 + NC.length() + cnonce.length() + qopOption.length() + md5a2.length() + 5);
434             tmp2.append(md5a1);
435             tmp2.append(':');
436             tmp2.append(nonce);
437             tmp2.append(':');
438             tmp2.append(NC);
439             tmp2.append(':');
440             tmp2.append(cnonce);
441             tmp2.append(':');
442             tmp2.append(qopOption);
443             tmp2.append(':');
444             tmp2.append(md5a2); 
445             serverDigestValue = tmp2.toString();
446         }
447 
448         String serverDigest =
449             encode(md5Helper.digest(EncodingUtil.getAsciiBytes(serverDigestValue)));
450 
451         return serverDigest;
452     }
453 
454     /**
455      * Creates digest-response header as defined in RFC2617.
456      * 
457      * @param uname Username
458      * @param digest The response tag's value as String.
459      * 
460      * @return The digest-response as String.
461      */
462     private String createDigestHeader(final String uname, final String digest) 
463         throws AuthenticationException {
464 
465         LOG.trace("enter DigestScheme.createDigestHeader(String, Map, "
466             + "String)");
467 
468         String uri = getParameter("uri");
469         String realm = getParameter("realm");
470         String nonce = getParameter("nonce");
471         String opaque = getParameter("opaque");
472         String response = digest;
473         String algorithm = getParameter("algorithm");
474 
475         List params = new ArrayList(20);
476         params.add(new NameValuePair("username", uname));
477         params.add(new NameValuePair("realm", realm));
478         params.add(new NameValuePair("nonce", nonce));
479         params.add(new NameValuePair("uri", uri));
480         params.add(new NameValuePair("response", response));
481         
482         if (qopVariant != QOP_MISSING) {
483             params.add(new NameValuePair("qop", getQopVariantString()));
484             params.add(new NameValuePair("nc", NC));
485             params.add(new NameValuePair("cnonce", this.cnonce));
486         }
487         if (algorithm != null) {
488             params.add(new NameValuePair("algorithm", algorithm));
489         }    
490         if (opaque != null) {
491             params.add(new NameValuePair("opaque", opaque));
492         }
493 
494         StringBuffer buffer = new StringBuffer();
495         for (int i = 0; i < params.size(); i++) {
496             NameValuePair param = (NameValuePair) params.get(i);
497             if (i > 0) {
498                 buffer.append(", ");
499             }
500             boolean noQuotes = "nc".equals(param.getName()) ||
501                                "qop".equals(param.getName());
502             this.formatter.setAlwaysUseQuotes(!noQuotes);
503             this.formatter.format(buffer, param);
504         }
505         return buffer.toString();
506     }
507 
508     private String getQopVariantString() {
509         String qopOption;
510         if (qopVariant == QOP_AUTH_INT) {
511             qopOption = "auth-int";   
512         } else {
513             qopOption = "auth";
514         }
515         return qopOption;            
516     }
517 
518     /**
519      * Encodes the 128 bit (16 bytes) MD5 digest into a 32 characters long 
520      * <CODE>String</CODE> according to RFC 2617.
521      * 
522      * @param binaryData array containing the digest
523      * @return encoded MD5, or <CODE>null</CODE> if encoding failed
524      */
525     private static String encode(byte[] binaryData) {
526         LOG.trace("enter DigestScheme.encode(byte[])");
527 
528         if (binaryData.length != 16) {
529             return null;
530         } 
531 
532         char[] buffer = new char[32];
533         for (int i = 0; i < 16; i++) {
534             int low = (int) (binaryData[i] & 0x0f);
535             int high = (int) ((binaryData[i] & 0xf0) >> 4);
536             buffer[i * 2] = HEXADECIMAL[high];
537             buffer[(i * 2) + 1] = HEXADECIMAL[low];
538         }
539 
540         return new String(buffer);
541     }
542 
543 
544     /**
545      * Creates a random cnonce value based on the current time.
546      * 
547      * @return The cnonce value as String.
548      * @throws HttpClientError if MD5 algorithm is not supported.
549      */
550     public static String createCnonce() {
551         LOG.trace("enter DigestScheme.createCnonce()");
552 
553         String cnonce;
554         final String digAlg = "MD5";
555         MessageDigest md5Helper;
556 
557         try {
558             md5Helper = MessageDigest.getInstance(digAlg);
559         } catch (NoSuchAlgorithmException e) {
560             throw new HttpClientError(
561               "Unsupported algorithm in HTTP Digest authentication: "
562                + digAlg);
563         }
564 
565         cnonce = Long.toString(System.currentTimeMillis());
566         cnonce = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(cnonce)));
567 
568         return cnonce;
569     }
570 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/HttpAuthRealm.html100644 0 0 14434 10661532627 26477 0ustar 0 0 HttpAuthRealm xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/HttpAuthRealm.java,v 1.9 2004/06/12 22:47:23 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  /** The key used to look up authentication credentials.
34   * 
35   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
36   * @author <a href="mailto:adrian@intencha.com">Adrian Sutton</a>
37   * 
38   * @deprecated no longer used
39   */
40  public class HttpAuthRealm extends AuthScope {
41      
42      /** Creates a new HttpAuthRealm for the given <tt>domain</tt> and 
43       * <tt>realm</tt>.
44       * 
45       * @param domain the domain the credentials apply to. May be set
46       *   to <tt>null</tt> if credenticals are applicable to
47       *   any domain. 
48       * @param realm the realm the credentials apply to. May be set 
49       *   to <tt>null</tt> if credenticals are applicable to
50       *   any realm. 
51       *   
52       */
53      public HttpAuthRealm(final String domain, final String realm) {
54          super(domain, ANY_PORT, realm, ANY_SCHEME);
55      }
56      
57  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/HttpAuthenticator.html100644 0 0 114072 10661532627 27446 0ustar 0 0 HttpAuthenticator xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/HttpAuthenticator.java,v 1.19 2004/10/06 17:32:04 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import java.util.HashMap;
34  import java.util.Map;
35  
36  import org.apache.commons.httpclient.Credentials;
37  import org.apache.commons.httpclient.Header;
38  import org.apache.commons.httpclient.HttpConnection;
39  import org.apache.commons.httpclient.HttpMethod;
40  import org.apache.commons.httpclient.HttpState;
41  import org.apache.commons.httpclient.UsernamePasswordCredentials;
42  import org.apache.commons.logging.Log;
43  import org.apache.commons.logging.LogFactory;
44  
45  /**
46   * Utility methods for HTTP authorization and authentication.  This class
47   * provides utility methods for generating responses to HTTP www and proxy
48   * authentication challenges.
49   * 
50   * <blockquote>
51   * A client SHOULD assume that all paths at or deeper than the depth of the
52   * last symbolic element in the path field of the Request-URI also are within
53   * the protection space specified by the basic realm value of the current
54   * challenge. A client MAY preemptively send the corresponding Authorization
55   * header with requests for resources in that space without receipt of another
56   * challenge from the server. Similarly, when a client sends a request to a
57   * proxy, it may reuse a userid and password in the Proxy-Authorization header
58   * field without receiving another challenge from the proxy server.
59   * </blockquote>
60   * </p>
61   * 
62   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
63   * @author Rodney Waldhoff
64   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
65   * @author Ortwin Gl?ck
66   * @author Sean C. Sullivan
67   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
68   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
69   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
70   * 
71   * @deprecated no longer used
72   */
73  public final class HttpAuthenticator {
74  
75      /** Log object for this class. */
76      private static final Log LOG = LogFactory.getLog(HttpAuthenticator.class);
77  
78      /**
79       * The www authenticate challange header.
80       */
81      public static final String WWW_AUTH = "WWW-Authenticate";
82  
83      /**
84       * The www authenticate response header.
85       */
86      public static final String WWW_AUTH_RESP = "Authorization";
87  
88      /**
89       * The proxy authenticate challange header.
90       */
91      public static final String PROXY_AUTH = "Proxy-Authenticate";
92  
93      /**
94       * The proxy authenticate response header.
95       */
96      public static final String PROXY_AUTH_RESP = "Proxy-Authorization";
97  
98      /** Chooses the strongest authentication scheme supported from the
99       * array of authentication challenges. Currently only <code>NTLM</code>,
100      * <code>Digest</code>, <code>Basic</code> schemes are recognized. 
101      * The <code>NTLM</code> scheme is considered the strongest and is 
102      * preferred to all others. The <code>Digest</code> scheme is preferred to 
103      * the <code>Basic</code> one which provides no encryption for credentials.
104      * The <code>Basic</code> scheme is used only if it is the only one 
105      * supported.
106      * 
107      * @param challenges The array of authentication challenges
108      * 
109      * @return The strongest authentication scheme supported
110      * 
111      * @throws MalformedChallengeException is thrown if an authentication 
112      *  challenge is malformed
113      * @throws UnsupportedOperationException when none of challenge types
114      *  available is supported.
115      * 
116      * @deprecated Use {@link AuthChallengeParser#parseChallenges(Header[])} and 
117      *      {@link AuthPolicy#getAuthScheme(String)}
118      */
119     public static AuthScheme selectAuthScheme(final Header[] challenges)
120       throws MalformedChallengeException {
121         LOG.trace("enter HttpAuthenticator.selectAuthScheme(Header[])");
122         if (challenges == null) {
123             throw new IllegalArgumentException("Array of challenges may not be null");
124         }
125         if (challenges.length == 0) {
126             throw new IllegalArgumentException("Array of challenges may not be empty");
127         }
128         String challenge = null;
129         Map challengemap = new HashMap(challenges.length); 
130         for (int i = 0; i < challenges.length; i++) {
131             challenge = challenges[i].getValue();
132             String s = AuthChallengeParser.extractScheme(challenge);
133             challengemap.put(s, challenge);
134         }
135         challenge = (String) challengemap.get("ntlm");
136         if (challenge != null) {
137             return new NTLMScheme(challenge);
138         }
139         challenge = (String) challengemap.get("digest");
140         if (challenge != null) {
141             return new DigestScheme(challenge);
142         }
143         challenge = (String) challengemap.get("basic");
144         if (challenge != null) {
145             return new BasicScheme(challenge);
146         }
147         throw new UnsupportedOperationException(
148           "Authentication scheme(s) not supported: " + challengemap.toString()); 
149     }
150     
151     private static boolean doAuthenticateDefault(
152         HttpMethod method, 
153         HttpConnection conn,
154         HttpState state, 
155         boolean proxy)
156       throws AuthenticationException {
157         if (method == null) {
158             throw new IllegalArgumentException("HTTP method may not be null");
159         }
160         if (state == null) {
161             throw new IllegalArgumentException("HTTP state may not be null");
162         }
163         String host = null;
164         if (conn != null) {
165             host = proxy ? conn.getProxyHost() : conn.getHost();
166         }
167         Credentials credentials = proxy 
168             ? state.getProxyCredentials(null, host) : state.getCredentials(null, host);
169         if (credentials == null) {
170             return false;
171         }
172         if (!(credentials instanceof UsernamePasswordCredentials)) {
173             throw new InvalidCredentialsException(
174              "Credentials cannot be used for basic authentication: " 
175               + credentials.toString());
176         }
177         String auth = BasicScheme.authenticate(
178             (UsernamePasswordCredentials) credentials,
179             method.getParams().getCredentialCharset());
180         if (auth != null) {
181             String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP;
182             Header header = new Header(s, auth, true);
183             method.addRequestHeader(header);
184             return true;
185         } else {
186             return false;
187         }
188     }
189     
190     
191     /**
192      * Attempt to provide default authentication credentials 
193      * to the given method in the given context using basic 
194      * authentication scheme.
195      * 
196      * @param method the HttpMethod which requires authentication
197      * @param conn the connection to a specific host. This parameter 
198      *   may be <tt>null</tt> if default credentials (not specific 
199      *   to any particular host) are to be used
200      * @param state the HttpState object providing Credentials
201      * 
202      * @return true if the <tt>Authenticate</tt> response header 
203      *   was added
204      * 
205      * @throws InvalidCredentialsException if authentication credentials
206      *         are not valid or not applicable for basic scheme
207      * @throws AuthenticationException when a parsing or other error occurs
208      *
209      * @see HttpState#setCredentials(String,String,Credentials)
210      * 
211      * @deprecated use AuthScheme
212      */
213     public static boolean authenticateDefault(
214         HttpMethod method, 
215         HttpConnection conn,
216         HttpState state)
217       throws AuthenticationException {
218         LOG.trace(
219             "enter HttpAuthenticator.authenticateDefault(HttpMethod, HttpConnection, HttpState)");
220         return doAuthenticateDefault(method, conn, state, false);
221     }
222 
223 
224     /**
225      * Attempt to provide default proxy authentication credentials 
226      * to the given method in the given context using basic 
227      * authentication scheme.
228      * 
229      * @param method the HttpMethod which requires authentication
230      * @param conn the connection to a specific host. This parameter 
231      *   may be <tt>null</tt> if default credentials (not specific 
232      *   to any particular host) are to be used
233      * @param state the HttpState object providing Credentials
234      * 
235      * @return true if the <tt>Proxy-Authenticate</tt> response header 
236      *   was added
237      * 
238      * @throws InvalidCredentialsException if authentication credentials
239      *         are not valid or not applicable for basic scheme
240      * @throws AuthenticationException when a parsing or other error occurs
241 
242      * @see HttpState#setCredentials(String,String,Credentials)
243      * 
244      * @deprecated use AuthScheme
245      */
246     public static boolean authenticateProxyDefault(
247         HttpMethod method, 
248         HttpConnection conn,
249         HttpState state)
250       throws AuthenticationException {
251         LOG.trace("enter HttpAuthenticator.authenticateProxyDefault(HttpMethod, HttpState)");
252         return doAuthenticateDefault(method, conn, state, true);
253     }
254 
255 
256     private static boolean doAuthenticate(
257         AuthScheme authscheme, 
258         HttpMethod method, 
259         HttpConnection conn,
260         HttpState state, 
261         boolean proxy)
262        throws AuthenticationException {
263         if (authscheme == null) {
264             throw new IllegalArgumentException("Authentication scheme may not be null");
265         }
266         if (method == null) {
267             throw new IllegalArgumentException("HTTP method may not be null");
268         }
269         if (state == null) {
270             throw new IllegalArgumentException("HTTP state may not be null");
271         }
272         String host = null;
273         if (conn != null) {
274             if (proxy) {
275                 host = conn.getProxyHost();
276             } else {
277                 host = method.getParams().getVirtualHost();
278                 if (host == null) {
279                     host = conn.getHost();
280                 }
281             }
282         }
283         String realm = authscheme.getRealm();
284         if (LOG.isDebugEnabled()) {
285             StringBuffer buffer = new StringBuffer();
286             buffer.append("Using credentials for ");
287             if (realm == null) {
288                 buffer.append("default");
289             } else {
290                 buffer.append('\'');
291                 buffer.append(realm);
292                 buffer.append('\'');
293             }
294             buffer.append(" authentication realm at "); 
295             buffer.append(host); 
296             LOG.debug(buffer.toString());
297         }
298         Credentials credentials = proxy 
299             ? state.getProxyCredentials(realm, host) 
300             : state.getCredentials(realm, host);
301         if (credentials == null) {
302             StringBuffer buffer = new StringBuffer();
303             buffer.append("No credentials available for the "); 
304             if (realm == null) {
305                 buffer.append("default");
306             } else {
307                 buffer.append('\'');
308                 buffer.append(realm);
309                 buffer.append('\'');
310             }
311             buffer.append(" authentication realm at "); 
312             buffer.append(host); 
313             throw new CredentialsNotAvailableException(buffer.toString());
314         }
315         String auth = authscheme.authenticate(credentials, method);
316         if (auth != null) {
317             String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP;
318             Header header = new Header(s, auth, true);
319             method.addRequestHeader(header);
320             return true;
321         } else {
322             return false;
323         }
324     }
325 
326     /**
327      * Attempt to provide requisite authentication credentials to the 
328      * given method in the given context using the given 
329      * authentication scheme.
330      * 
331      * @param authscheme The authentication scheme to be used
332      * @param method The HttpMethod which requires authentication
333      * @param conn the connection to a specific host. This parameter 
334      *   may be <tt>null</tt> if default credentials (not specific 
335      *   to any particular host) are to be used
336      * @param state The HttpState object providing Credentials
337      * 
338      * @return true if the <tt>Authenticate</tt> response header was added
339      * 
340      * @throws CredentialsNotAvailableException if authentication credentials
341      *         required to respond to the authentication challenge are not available
342      * @throws AuthenticationException when a parsing or other error occurs
343 
344      * @see HttpState#setCredentials(String,String,Credentials)
345      * 
346      * @deprecated use AuthScheme
347      */
348     public static boolean authenticate(
349         AuthScheme authscheme, 
350         HttpMethod method, 
351         HttpConnection conn,
352         HttpState state) 
353         throws AuthenticationException {
354        LOG.trace(
355             "enter HttpAuthenticator.authenticate(AuthScheme, HttpMethod, HttpConnection, "
356             + "HttpState)");
357         return doAuthenticate(authscheme, method, conn, state, false);
358     }
359 
360 
361     /**
362      * Attempt to provide requisite proxy authentication credentials 
363      * to the given method in the given context using 
364      * the given authentication scheme.
365      * 
366      * @param authscheme The authentication scheme to be used
367      * @param method the HttpMethod which requires authentication
368      * @param conn the connection to a specific host. This parameter 
369      *   may be <tt>null</tt> if default credentials (not specific 
370      *   to any particular host) are to be used
371      * @param state the HttpState object providing Credentials
372      * 
373      * @return true if the <tt>Proxy-Authenticate</tt> response header 
374      *  was added
375      * 
376      * @throws CredentialsNotAvailableException if authentication credentials
377      *         required to respond to the authentication challenge are not available
378      * @throws AuthenticationException when a parsing or other error occurs
379 
380      * @see HttpState#setCredentials(String,String,Credentials)
381      * 
382      * @deprecated use AuthScheme
383      */
384     public static boolean authenticateProxy(
385         AuthScheme authscheme, 
386         HttpMethod method, 
387         HttpConnection conn,
388         HttpState state
389     ) throws AuthenticationException {
390        LOG.trace("enter HttpAuthenticator.authenticateProxy(AuthScheme, HttpMethod, HttpState)");
391        return doAuthenticate(authscheme, method, conn, state, true);
392     }
393 }

././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/InvalidCredentialsException.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/InvalidCredentialsException.html100644 0 0 16245 10661532627 31402 0ustar 0 0 InvalidCredentialsException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/InvalidCredentialsException.java,v 1.4 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  /**
34   * Authentication credentials required to respond to a authentication 
35   * challenge are invalid
36   *
37   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
38   * 
39   * @since 3.0
40   */
41  public class InvalidCredentialsException extends AuthenticationException {
42      /**
43       * Creates a new InvalidCredentialsException with a <tt>null</tt> detail message. 
44       */
45      public InvalidCredentialsException() {
46          super();
47      }
48  
49      /**
50       * Creates a new InvalidCredentialsException with the specified message.
51       * 
52       * @param message the exception detail message
53       */
54      public InvalidCredentialsException(String message) {
55          super(message);
56      }
57  
58      /**
59       * Creates a new InvalidCredentialsException with the specified detail message and cause.
60       * 
61       * @param message the exception detail message
62       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
63       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
64       */
65      public InvalidCredentialsException(String message, Throwable cause) {
66          super(message, cause);
67      }
68  }

././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/MalformedChallengeException.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/MalformedChallengeException.html100644 0 0 16657 10661532627 31356 0ustar 0 0 MalformedChallengeException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/MalformedChallengeException.java,v 1.6 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import org.apache.commons.httpclient.ProtocolException;
34  
35  /**
36   * Signals that authentication challenge is in some way invalid or 
37   * illegal in the given context
38   *
39   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
40   * 
41   * @since 2.0
42   */
43  public class MalformedChallengeException extends ProtocolException {
44  
45      /**
46       * Creates a new MalformedChallengeException with a <tt>null</tt> detail message. 
47       */
48      public MalformedChallengeException() {
49          super();
50      }
51  
52      /**
53       * Creates a new MalformedChallengeException with the specified message.
54       * 
55       * @param message the exception detail message
56       */
57      public MalformedChallengeException(String message) {
58          super(message);
59      }
60  
61      /**
62       * Creates a new MalformedChallengeException with the specified detail message and cause.
63       * 
64       * @param message the exception detail message
65       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
66       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
67       * 
68       * @since 3.0
69       */
70      public MalformedChallengeException(String message, Throwable cause) {
71          super(message, cause);
72      }
73  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/NTLM.html100644 0 0 131024 10661532627 24542 0ustar 0 0 NTLM xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/NTLM.java,v 1.11 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import java.security.InvalidKeyException;
34  import java.security.NoSuchAlgorithmException;
35  
36  import javax.crypto.BadPaddingException;
37  import javax.crypto.Cipher;
38  import javax.crypto.IllegalBlockSizeException;
39  import javax.crypto.NoSuchPaddingException;
40  import javax.crypto.spec.SecretKeySpec;
41  
42  import org.apache.commons.codec.binary.Base64;
43  import org.apache.commons.httpclient.util.EncodingUtil;
44  
45  /**
46   * Provides an implementation of the NTLM authentication protocol.
47   * <p>
48   * This class provides methods for generating authentication
49   * challenge responses for the NTLM authentication protocol.  The NTLM
50   * protocol is a proprietary Microsoft protocol and as such no RFC
51   * exists for it.  This class is based upon the reverse engineering
52   * efforts of a wide range of people.</p>
53   *
54   * <p>Please note that an implementation of JCE must be correctly installed and configured when
55   * using NTLM support.</p>
56   *
57   * <p>This class should not be used externally to HttpClient as it's API is specifically
58   * designed to work with HttpClient's use case, in particular it's connection management.</p>
59   *
60   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
61   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
62   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
63   *
64   * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
65   * @since 3.0
66   */
67  final class NTLM {
68  
69      /** Character encoding */
70      public static final String DEFAULT_CHARSET = "ASCII";
71  
72      /** The current response */
73      private byte[] currentResponse;
74  
75      /** The current position */
76      private int currentPosition = 0;
77  
78      /** The character set to use for encoding the credentials */
79      private String credentialCharset = DEFAULT_CHARSET;
80      
81      /**
82       * Returns the response for the given message.
83       *
84       * @param message the message that was received from the server.
85       * @param username the username to authenticate with.
86       * @param password the password to authenticate with.
87       * @param host The host.
88       * @param domain the NT domain to authenticate in.
89       * @return The response.
90       * @throws HttpException If the messages cannot be retrieved.
91       */
92      public final String getResponseFor(String message,
93              String username, String password, String host, String domain)
94              throws AuthenticationException {
95                  
96          final String response;
97          if (message == null || message.trim().equals("")) {
98              response = getType1Message(host, domain);
99          } else {
100             response = getType3Message(username, password, host, domain,
101                     parseType2Message(message));
102         }
103         return response;
104     }
105 
106     /**
107      * Return the cipher for the specified key.
108      * @param key The key.
109      * @return Cipher The cipher.
110      * @throws AuthenticationException If the cipher cannot be retrieved.
111      */
112     private Cipher getCipher(byte[] key) throws AuthenticationException {
113         try {
114             final Cipher ecipher = Cipher.getInstance("DES/ECB/NoPadding");
115             key = setupKey(key);
116             ecipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "DES"));
117             return ecipher;
118         } catch (NoSuchAlgorithmException e) {
119             throw new AuthenticationException("DES encryption is not available.", e);
120         } catch (InvalidKeyException e) {
121             throw new AuthenticationException("Invalid key for DES encryption.", e);
122         } catch (NoSuchPaddingException e) {
123             throw new AuthenticationException(
124                 "NoPadding option for DES is not available.", e);
125         }
126     }
127 
128     /** 
129      * Adds parity bits to the key.
130      * @param key56 The key
131      * @return The modified key.
132      */
133     private byte[] setupKey(byte[] key56) {
134         byte[] key = new byte[8];
135         key[0] = (byte) ((key56[0] >> 1) & 0xff);
136         key[1] = (byte) ((((key56[0] & 0x01) << 6) 
137             | (((key56[1] & 0xff) >> 2) & 0xff)) & 0xff);
138         key[2] = (byte) ((((key56[1] & 0x03) << 5) 
139             | (((key56[2] & 0xff) >> 3) & 0xff)) & 0xff);
140         key[3] = (byte) ((((key56[2] & 0x07) << 4) 
141             | (((key56[3] & 0xff) >> 4) & 0xff)) & 0xff);
142         key[4] = (byte) ((((key56[3] & 0x0f) << 3) 
143             | (((key56[4] & 0xff) >> 5) & 0xff)) & 0xff);
144         key[5] = (byte) ((((key56[4] & 0x1f) << 2) 
145             | (((key56[5] & 0xff) >> 6) & 0xff)) & 0xff);
146         key[6] = (byte) ((((key56[5] & 0x3f) << 1) 
147             | (((key56[6] & 0xff) >> 7) & 0xff)) & 0xff);
148         key[7] = (byte) (key56[6] & 0x7f);
149         
150         for (int i = 0; i < key.length; i++) {
151             key[i] = (byte) (key[i] << 1);
152         }
153         return key;
154     }
155 
156     /**
157      * Encrypt the data.
158      * @param key The key.
159      * @param bytes The data
160      * @return byte[] The encrypted data
161      * @throws HttpException If {@link Cipher.doFinal(byte[])} fails
162      */
163     private byte[] encrypt(byte[] key, byte[] bytes)
164         throws AuthenticationException {
165         Cipher ecipher = getCipher(key);
166         try {
167             byte[] enc = ecipher.doFinal(bytes);
168             return enc;
169         } catch (IllegalBlockSizeException e) {
170             throw new AuthenticationException("Invalid block size for DES encryption.", e);
171         } catch (BadPaddingException e) {
172             throw new AuthenticationException("Data not padded correctly for DES encryption.", e);
173         }
174     }
175 
176     /** 
177      * Prepares the object to create a response of the given length.
178      * @param length the length of the response to prepare.
179      */
180     private void prepareResponse(int length) {
181         currentResponse = new byte[length];
182         currentPosition = 0;
183     }
184 
185     /** 
186      * Adds the given byte to the response.
187      * @param b the byte to add.
188      */
189     private void addByte(byte b) {
190         currentResponse[currentPosition] = b;
191         currentPosition++;
192     }
193 
194     /** 
195      * Adds the given bytes to the response.
196      * @param bytes the bytes to add.
197      */
198     private void addBytes(byte[] bytes) {
199         for (int i = 0; i < bytes.length; i++) {
200             currentResponse[currentPosition] = bytes[i];
201             currentPosition++;
202         }
203     }
204 
205     /** 
206      * Returns the response that has been generated after shrinking the array if
207      * required and base64 encodes the response.
208      * @return The response as above.
209      */
210     private String getResponse() {
211         byte[] resp;
212         if (currentResponse.length > currentPosition) {
213             byte[] tmp = new byte[currentPosition];
214             for (int i = 0; i < currentPosition; i++) {
215                 tmp[i] = currentResponse[i];
216             }
217             resp = tmp;
218         } else {
219             resp = currentResponse;
220         }
221         return EncodingUtil.getAsciiString(Base64.encodeBase64(resp));
222     }
223     
224     /**
225      * Creates the first message (type 1 message) in the NTLM authentication sequence.
226      * This message includes the user name, domain and host for the authentication session.
227      *
228      * @param host the computer name of the host requesting authentication.
229      * @param domain The domain to authenticate with.
230      * @return String the message to add to the HTTP request header.
231      */
232     public String getType1Message(String host, String domain) {
233         host = host.toUpperCase();
234         domain = domain.toUpperCase();
235         byte[] hostBytes = EncodingUtil.getBytes(host, DEFAULT_CHARSET);
236         byte[] domainBytes = EncodingUtil.getBytes(domain, DEFAULT_CHARSET);
237 
238         int finalLength = 32 + hostBytes.length + domainBytes.length;
239         prepareResponse(finalLength);
240         
241         // The initial id string.
242         byte[] protocol = EncodingUtil.getBytes("NTLMSSP", DEFAULT_CHARSET);
243         addBytes(protocol);
244         addByte((byte) 0);
245 
246         // Type
247         addByte((byte) 1);
248         addByte((byte) 0);
249         addByte((byte) 0);
250         addByte((byte) 0);
251 
252         // Flags
253         addByte((byte) 6);
254         addByte((byte) 82);
255         addByte((byte) 0);
256         addByte((byte) 0);
257 
258         // Domain length (first time).
259         int iDomLen = domainBytes.length;
260         byte[] domLen = convertShort(iDomLen);
261         addByte(domLen[0]);
262         addByte(domLen[1]);
263 
264         // Domain length (second time).
265         addByte(domLen[0]);
266         addByte(domLen[1]);
267 
268         // Domain offset.
269         byte[] domOff = convertShort(hostBytes.length + 32);
270         addByte(domOff[0]);
271         addByte(domOff[1]);
272         addByte((byte) 0);
273         addByte((byte) 0);
274 
275         // Host length (first time).
276         byte[] hostLen = convertShort(hostBytes.length);
277         addByte(hostLen[0]);
278         addByte(hostLen[1]);
279 
280         // Host length (second time).
281         addByte(hostLen[0]);
282         addByte(hostLen[1]);
283 
284         // Host offset (always 32).
285         byte[] hostOff = convertShort(32);
286         addByte(hostOff[0]);
287         addByte(hostOff[1]);
288         addByte((byte) 0);
289         addByte((byte) 0);
290 
291         // Host String.
292         addBytes(hostBytes);
293 
294         // Domain String.
295         addBytes(domainBytes);
296 
297         return getResponse();
298     }
299 
300     /** 
301      * Extracts the server nonce out of the given message type 2.
302      * 
303      * @param message the String containing the base64 encoded message.
304      * @return an array of 8 bytes that the server sent to be used when
305      * hashing the password.
306      */
307     public byte[] parseType2Message(String message) {
308         // Decode the message first.
309         byte[] msg = Base64.decodeBase64(EncodingUtil.getBytes(message, DEFAULT_CHARSET));
310         byte[] nonce = new byte[8];
311         // The nonce is the 8 bytes starting from the byte in position 24.
312         for (int i = 0; i < 8; i++) {
313             nonce[i] = msg[i + 24];
314         }
315         return nonce;
316     }
317 
318     /** 
319      * Creates the type 3 message using the given server nonce.  The type 3 message includes all the
320      * information for authentication, host, domain, username and the result of encrypting the
321      * nonce sent by the server using the user's password as the key.
322      *
323      * @param user The user name.  This should not include the domain name.
324      * @param password The password.
325      * @param host The host that is originating the authentication request.
326      * @param domain The domain to authenticate within.
327      * @param nonce the 8 byte array the server sent.
328      * @return The type 3 message.
329      * @throws AuthenticationException If {@encrypt(byte[],byte[])} fails.
330      */
331     public String getType3Message(String user, String password,
332             String host, String domain, byte[] nonce)
333     throws AuthenticationException {
334 
335         int ntRespLen = 0;
336         int lmRespLen = 24;
337         domain = domain.toUpperCase();
338         host = host.toUpperCase();
339         user = user.toUpperCase();
340         byte[] domainBytes = EncodingUtil.getBytes(domain, DEFAULT_CHARSET);
341         byte[] hostBytes = EncodingUtil.getBytes(host, DEFAULT_CHARSET);
342         byte[] userBytes = EncodingUtil.getBytes(user, credentialCharset);
343         int domainLen = domainBytes.length;
344         int hostLen = hostBytes.length;
345         int userLen = userBytes.length;
346         int finalLength = 64 + ntRespLen + lmRespLen + domainLen 
347             + userLen + hostLen;
348         prepareResponse(finalLength);
349         byte[] ntlmssp = EncodingUtil.getBytes("NTLMSSP", DEFAULT_CHARSET);
350         addBytes(ntlmssp);
351         addByte((byte) 0);
352         addByte((byte) 3);
353         addByte((byte) 0);
354         addByte((byte) 0);
355         addByte((byte) 0);
356 
357         // LM Resp Length (twice)
358         addBytes(convertShort(24));
359         addBytes(convertShort(24));
360 
361         // LM Resp Offset
362         addBytes(convertShort(finalLength - 24));
363         addByte((byte) 0);
364         addByte((byte) 0);
365 
366         // NT Resp Length (twice)
367         addBytes(convertShort(0));
368         addBytes(convertShort(0));
369 
370         // NT Resp Offset
371         addBytes(convertShort(finalLength));
372         addByte((byte) 0);
373         addByte((byte) 0);
374 
375         // Domain length (twice)
376         addBytes(convertShort(domainLen));
377         addBytes(convertShort(domainLen));
378         
379         // Domain offset.
380         addBytes(convertShort(64));
381         addByte((byte) 0);
382         addByte((byte) 0);
383 
384         // User Length (twice)
385         addBytes(convertShort(userLen));
386         addBytes(convertShort(userLen));
387 
388         // User offset
389         addBytes(convertShort(64 + domainLen));
390         addByte((byte) 0);
391         addByte((byte) 0);
392 
393         // Host length (twice)
394         addBytes(convertShort(hostLen));
395         addBytes(convertShort(hostLen));
396 
397         // Host offset
398         addBytes(convertShort(64 + domainLen + userLen));
399 
400         for (int i = 0; i < 6; i++) {
401             addByte((byte) 0);
402         }
403 
404         // Message length
405         addBytes(convertShort(finalLength));
406         addByte((byte) 0);
407         addByte((byte) 0);
408 
409         // Flags
410         addByte((byte) 6);
411         addByte((byte) 82);
412         addByte((byte) 0);
413         addByte((byte) 0);
414 
415         addBytes(domainBytes);
416         addBytes(userBytes);
417         addBytes(hostBytes);
418         addBytes(hashPassword(password, nonce));
419         return getResponse();
420     }
421 
422     /** 
423      * Creates the LANManager and NT response for the given password using the
424      * given nonce.
425      * @param password the password to create a hash for.
426      * @param nonce the nonce sent by the server.
427      * @return The response.
428      * @throws HttpException If {@link #encrypt(byte[],byte[])} fails.
429      */
430     private byte[] hashPassword(String password, byte[] nonce)
431         throws AuthenticationException {
432         byte[] passw = EncodingUtil.getBytes(password.toUpperCase(), credentialCharset);
433         byte[] lmPw1 = new byte[7];
434         byte[] lmPw2 = new byte[7];
435 
436         int len = passw.length;
437         if (len > 7) {
438             len = 7;
439         }
440 
441         int idx;
442         for (idx = 0; idx < len; idx++) {
443             lmPw1[idx] = passw[idx];
444         }
445         for (; idx < 7; idx++) {
446             lmPw1[idx] = (byte) 0;
447         }
448 
449         len = passw.length;
450         if (len > 14) {
451             len = 14;
452         }
453         for (idx = 7; idx < len; idx++) {
454             lmPw2[idx - 7] = passw[idx];
455         }
456         for (; idx < 14; idx++) {
457             lmPw2[idx - 7] = (byte) 0;
458         }
459 
460         // Create LanManager hashed Password
461         byte[] magic = {
462             (byte) 0x4B, (byte) 0x47, (byte) 0x53, (byte) 0x21, 
463             (byte) 0x40, (byte) 0x23, (byte) 0x24, (byte) 0x25
464         };
465 
466         byte[] lmHpw1;
467         lmHpw1 = encrypt(lmPw1, magic);
468 
469         byte[] lmHpw2 = encrypt(lmPw2, magic);
470 
471         byte[] lmHpw = new byte[21];
472         for (int i = 0; i < lmHpw1.length; i++) {
473             lmHpw[i] = lmHpw1[i];
474         }
475         for (int i = 0; i < lmHpw2.length; i++) {
476             lmHpw[i + 8] = lmHpw2[i];
477         }
478         for (int i = 0; i < 5; i++) {
479             lmHpw[i + 16] = (byte) 0;
480         }
481 
482         // Create the responses.
483         byte[] lmResp = new byte[24];
484         calcResp(lmHpw, nonce, lmResp);
485 
486         return lmResp;
487     }
488 
489     /** 
490      * Takes a 21 byte array and treats it as 3 56-bit DES keys.  The 8 byte
491      * plaintext is encrypted with each key and the resulting 24 bytes are
492      * stored in the results array.
493      * 
494      * @param keys The keys.
495      * @param plaintext The plain text to encrypt.
496      * @param results Where the results are stored.
497      * @throws AuthenticationException If {@link #encrypt(byte[],byte[])} fails.
498      */
499     private void calcResp(byte[] keys, byte[] plaintext, byte[] results)
500         throws AuthenticationException {
501         byte[] keys1 = new byte[7];
502         byte[] keys2 = new byte[7];
503         byte[] keys3 = new byte[7];
504         for (int i = 0; i < 7; i++) {
505             keys1[i] = keys[i];
506         }
507 
508         for (int i = 0; i < 7; i++) {
509             keys2[i] = keys[i + 7];
510         }
511 
512         for (int i = 0; i < 7; i++) {
513             keys3[i] = keys[i + 14];
514         }
515         byte[] results1 = encrypt(keys1, plaintext);
516 
517         byte[] results2 = encrypt(keys2, plaintext);
518 
519         byte[] results3 = encrypt(keys3, plaintext);
520 
521         for (int i = 0; i < 8; i++) {
522             results[i] = results1[i];
523         }
524         for (int i = 0; i < 8; i++) {
525             results[i + 8] = results2[i];
526         }
527         for (int i = 0; i < 8; i++) {
528             results[i + 16] = results3[i];
529         }
530     }
531 
532     /** 
533      * Converts a given number to a two byte array in little endian order.
534      * @param num the number to convert.
535      * @return The byte representation of <i>num</i> in little endian order.
536      */
537     private byte[] convertShort(int num) {
538         byte[] val = new byte[2];
539         String hex = Integer.toString(num, 16);
540         while (hex.length() < 4) {
541             hex = "0" + hex;
542         }
543         String low = hex.substring(2, 4);
544         String high = hex.substring(0, 2);
545 
546         val[0] = (byte) Integer.parseInt(low, 16);
547         val[1] = (byte) Integer.parseInt(high, 16);
548         return val;
549     }
550     
551     /**
552      * @return Returns the credentialCharset.
553      */
554     public String getCredentialCharset() {
555         return credentialCharset;
556     }
557 
558     /**
559      * @param credentialCharset The credentialCharset to set.
560      */
561     public void setCredentialCharset(String credentialCharset) {
562         this.credentialCharset = credentialCharset;
563     }
564 
565 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/NTLMScheme.html100644 0 0 100301 10661532627 25661 0ustar 0 0 NTLMScheme xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/NTLMScheme.java,v 1.21 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import org.apache.commons.httpclient.Credentials;
34  import org.apache.commons.httpclient.HttpMethod;
35  import org.apache.commons.httpclient.NTCredentials;
36  import org.apache.commons.logging.Log;
37  import org.apache.commons.logging.LogFactory;
38  
39  /** An implementation of the Microsoft proprietary NTLM authentication scheme.  For a detailed
40   * explanation of the NTLM scheme please see <a href="http://davenport.sourceforge.net/ntlm.html">
41   * http://davenport.sourceforge.net/ntlm.html</a>.
42   * 
43   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
44   * @author Rodney Waldhoff
45   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
46   * @author Ortwin Gl???ck
47   * @author Sean C. Sullivan
48   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
49   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
50   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
51   */
52  public class NTLMScheme implements AuthScheme {
53  
54      /** Log object for this class. */
55      private static final Log LOG = LogFactory.getLog(NTLMScheme.class);
56  
57      /** NTLM challenge string. */
58      private String ntlmchallenge = null;
59  
60      private static final int UNINITIATED         = 0;
61      private static final int INITIATED           = 1;
62      private static final int TYPE1_MSG_GENERATED = 2;
63      private static final int TYPE2_MSG_RECEIVED  = 3;
64      private static final int TYPE3_MSG_GENERATED = 4;
65      private static final int FAILED              = Integer.MAX_VALUE;
66  
67      /** Authentication process state */
68      private int state;
69      
70      /**
71       * Default constructor for the NTLM authentication scheme.
72       * 
73       * @since 3.0
74       */
75      public NTLMScheme() {
76          super();
77          this.state = UNINITIATED;
78      }
79  
80      /**
81       * Constructor for the NTLM authentication scheme.
82       * 
83       * @param challenge The authentication challenge
84       * 
85       * @throws MalformedChallengeException is thrown if the authentication challenge
86       * is malformed
87       */
88      public NTLMScheme(final String challenge) throws MalformedChallengeException {
89          super();
90          processChallenge(challenge);
91      }
92  
93      /**
94       * Processes the NTLM challenge.
95       *  
96       * @param challenge the challenge string
97       * 
98       * @throws MalformedChallengeException is thrown if the authentication challenge
99       * is malformed
100      * 
101      * @since 3.0
102      */
103     public void processChallenge(final String challenge) throws MalformedChallengeException {
104         String s = AuthChallengeParser.extractScheme(challenge);
105         if (!s.equalsIgnoreCase(getSchemeName())) {
106             throw new MalformedChallengeException("Invalid NTLM challenge: " + challenge);
107         }
108         int i = challenge.indexOf(' ');
109         if (i != -1) {
110             s = challenge.substring(i, challenge.length());
111             this.ntlmchallenge = s.trim();
112             this.state = TYPE2_MSG_RECEIVED;
113         } else {
114             this.ntlmchallenge = "";
115             if (this.state == UNINITIATED) {
116                 this.state = INITIATED;
117             } else {
118                 this.state = FAILED;
119             }
120         }
121     }
122 
123     /**
124      * Tests if the NTLM authentication process has been completed.
125      * 
126      * @return <tt>true</tt> if Basic authorization has been processed,
127      *   <tt>false</tt> otherwise.
128      * 
129      * @since 3.0
130      */
131     public boolean isComplete() {
132         return this.state == TYPE3_MSG_GENERATED || this.state == FAILED;
133     }
134 
135     /**
136      * Returns textual designation of the NTLM authentication scheme.
137      * 
138      * @return <code>ntlm</code>
139      */
140     public String getSchemeName() {
141         return "ntlm";
142     }
143 
144     /**
145      * The concept of an authentication realm is not supported by the NTLM 
146      * authentication scheme. Always returns <code>null</code>.
147      * 
148      * @return <code>null</code>
149      */
150     public String getRealm() {
151         return null;
152     }
153     
154     /**
155      * Returns a String identifying the authentication challenge.  This is
156      * used, in combination with the host and port to determine if
157      * authorization has already been attempted or not.  Schemes which
158      * require multiple requests to complete the authentication should
159      * return a different value for each stage in the request.
160      * 
161      * <p>Additionally, the ID should take into account any changes to the
162      * authentication challenge and return a different value when appropriate.
163      * For example when the realm changes in basic authentication it should be
164      * considered a different authentication attempt and a different value should
165      * be returned.</p>
166      * 
167      * @return String a String identifying the authentication challenge.  The
168      * returned value may be null.
169      * 
170      * @deprecated no longer used
171      */
172     public String getID() {
173         return ntlmchallenge;
174     }
175     
176     /**
177      * Returns the authentication parameter with the given name, if available.
178      * 
179      * <p>There are no valid parameters for NTLM authentication so this method always returns
180      * <tt>null</tt>.</p>
181      * 
182      * @param name The name of the parameter to be returned
183      * 
184      * @return the parameter with the given name
185      */
186     public String getParameter(String name) {
187         if (name == null) {
188             throw new IllegalArgumentException("Parameter name may not be null"); 
189         }
190         return null;
191     }
192 
193     /**
194      * Returns <tt>true</tt>. NTLM authentication scheme is connection based.
195      * 
196      * @return <tt>true</tt>.
197      * 
198      * @since 3.0
199      */
200     public boolean isConnectionBased() {
201         return true;    
202     }
203 
204     /**
205      * Create a NTLM authorization string for the given
206      * challenge and NT credentials.
207      *
208      * @param challenge The challenge.
209      * @param credentials {@link NTCredentials}
210      *
211      * @return a ntlm authorization string
212      * @throws AuthenticationException is thrown if authentication fails
213      * 
214      * @deprecated Use non-static {@link #authenticate(Credentials, HttpMethod)}
215      */
216     public static String authenticate(
217      final NTCredentials credentials, final String challenge) 
218       throws AuthenticationException {
219 
220         LOG.trace("enter NTLMScheme.authenticate(NTCredentials, String)");
221 
222         if (credentials == null) {
223             throw new IllegalArgumentException("Credentials may not be null");
224         }
225         
226         NTLM ntlm = new NTLM();
227         String s = ntlm.getResponseFor(challenge,
228         credentials.getUserName(), credentials.getPassword(),
229         credentials.getHost(), credentials.getDomain());
230         return "NTLM " + s;
231     }
232 
233     /**
234      * Create a NTLM authorization string for the given
235      * challenge and NT credentials.
236      *
237      * @param challenge The challenge.
238      * @param credentials {@link NTCredentials}
239      * @param charset The charset to use for encoding the credentials
240      *
241      * @return a ntlm authorization string
242      * @throws AuthenticationException is thrown if authentication fails
243      * 
244      * @deprecated Use non-static {@link #authenticate(Credentials, HttpMethod)}
245      * 
246      * @since 3.0
247      */
248     public static String authenticate(
249         final NTCredentials credentials, 
250 		final String challenge,
251 		String charset
252     ) throws AuthenticationException {
253 
254         LOG.trace("enter NTLMScheme.authenticate(NTCredentials, String)");
255 
256         if (credentials == null) {
257             throw new IllegalArgumentException("Credentials may not be null");
258         }
259         
260         NTLM ntlm = new NTLM();
261         ntlm.setCredentialCharset(charset);
262         String s = ntlm.getResponseFor(
263             challenge,
264             credentials.getUserName(), 
265 			credentials.getPassword(),
266 			credentials.getHost(), 
267 			credentials.getDomain());
268         return "NTLM " + s;
269     }
270     
271     /**
272      * Produces NTLM authorization string for the given set of 
273      * {@link Credentials}.
274      * 
275      * @param credentials The set of credentials to be used for athentication
276      * @param method Method name is ignored by the NTLM authentication scheme
277      * @param uri URI is ignored by the NTLM authentication scheme
278      * @throws InvalidCredentialsException if authentication credentials
279      *         are not valid or not applicable for this authentication scheme
280      * @throws AuthenticationException if authorization string cannot 
281      *   be generated due to an authentication failure
282      * 
283      * @return an NTLM authorization string
284      * 
285      * @deprecated Use {@link #authenticate(Credentials, HttpMethod)}
286      */
287     public String authenticate(Credentials credentials, String method, String uri) 
288       throws AuthenticationException {
289         LOG.trace("enter NTLMScheme.authenticate(Credentials, String, String)");
290 
291         NTCredentials ntcredentials = null;
292         try {
293             ntcredentials = (NTCredentials) credentials;
294         } catch (ClassCastException e) {
295             throw new InvalidCredentialsException(
296              "Credentials cannot be used for NTLM authentication: " 
297               + credentials.getClass().getName());
298         }
299         return NTLMScheme.authenticate(ntcredentials, this.ntlmchallenge);
300     }
301     
302     /**
303      * Produces NTLM authorization string for the given set of 
304      * {@link Credentials}.
305      * 
306      * @param credentials The set of credentials to be used for athentication
307      * @param method The method being authenticated
308      * 
309      * @throws InvalidCredentialsException if authentication credentials
310      *         are not valid or not applicable for this authentication scheme
311      * @throws AuthenticationException if authorization string cannot 
312      *   be generated due to an authentication failure
313      * 
314      * @return an NTLM authorization string
315      * 
316      * @since 3.0
317      */
318     public String authenticate(
319         Credentials credentials, 
320         HttpMethod method
321     ) throws AuthenticationException {
322         LOG.trace("enter NTLMScheme.authenticate(Credentials, HttpMethod)");
323 
324         if (this.state == UNINITIATED) {
325             throw new IllegalStateException("NTLM authentication process has not been initiated");
326         }
327 
328         NTCredentials ntcredentials = null;
329         try {
330             ntcredentials = (NTCredentials) credentials;
331         } catch (ClassCastException e) {
332             throw new InvalidCredentialsException(
333                     "Credentials cannot be used for NTLM authentication: " 
334                     + credentials.getClass().getName());
335         }
336         NTLM ntlm = new NTLM();
337         ntlm.setCredentialCharset(method.getParams().getCredentialCharset());
338         String response = null;
339         if (this.state == INITIATED || this.state == FAILED) {
340             response = ntlm.getType1Message(
341                 ntcredentials.getHost(), 
342                 ntcredentials.getDomain());
343             this.state = TYPE1_MSG_GENERATED;
344         } else {
345             response = ntlm.getType3Message(
346                 ntcredentials.getUserName(), 
347                 ntcredentials.getPassword(),
348                 ntcredentials.getHost(), 
349                 ntcredentials.getDomain(),
350                 ntlm.parseType2Message(this.ntlmchallenge));
351             this.state = TYPE3_MSG_GENERATED;
352         }
353         return "NTLM " + response;
354     }    
355 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/RFC2617Scheme.html100644 0 0 33014 10661532627 26027 0ustar 0 0 RFC2617Scheme xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/RFC2617Scheme.java,v 1.10 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.auth;
32  
33  import java.util.Map;
34  
35  /**
36   * <p>
37   * Abstract authentication scheme class that lays foundation for all
38   * RFC 2617 compliant authetication schemes and provides capabilities common 
39   * to all authentication schemes defined in RFC 2617.
40   * </p>
41   *
42   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
43  */
44  public abstract class RFC2617Scheme implements AuthScheme {
45  
46      /**
47       * Authentication parameter map.
48       */
49      private Map params = null;
50  
51      /**
52       * Default constructor for RFC2617 compliant authetication schemes.
53       * 
54       * @since 3.0
55       */
56      public RFC2617Scheme() {
57          super();
58      }
59  
60      /**
61       * Default constructor for RFC2617 compliant authetication schemes.
62       * 
63       * @param challenge authentication challenge
64       * 
65       * @throws MalformedChallengeException is thrown if the authentication challenge
66       * is malformed
67       * 
68       * @deprecated Use parameterless constructor and {@link AuthScheme#processChallenge(String)} 
69       *             method
70       */
71      public RFC2617Scheme(final String challenge) throws MalformedChallengeException {
72          super();
73          processChallenge(challenge);
74      }
75  
76      /**
77       * Processes the given challenge token. Some authentication schemes
78       * may involve multiple challenge-response exchanges. Such schemes must be able 
79       * to maintain the state information when dealing with sequential challenges 
80       * 
81       * @param challenge the challenge string
82       * 
83       * @throws MalformedChallengeException is thrown if the authentication challenge
84       * is malformed
85       * 
86       * @since 3.0
87       */
88      public void processChallenge(final String challenge) throws MalformedChallengeException {
89          String s = AuthChallengeParser.extractScheme(challenge);
90          if (!s.equalsIgnoreCase(getSchemeName())) {
91              throw new MalformedChallengeException(
92                "Invalid " + getSchemeName() + " challenge: " + challenge); 
93          }
94          this.params = AuthChallengeParser.extractParams(challenge);
95      }
96  
97      /**
98       * Returns authentication parameters map. Keys in the map are lower-cased.
99       * 
100      * @return the map of authentication parameters
101      */
102     protected Map getParameters() {
103         return this.params;
104     }
105 
106     /**
107      * Returns authentication parameter with the given name, if available.
108      * 
109      * @param name The name of the parameter to be returned
110      * 
111      * @return the parameter with the given name
112      */
113     public String getParameter(String name) {
114         if (name == null) {
115             throw new IllegalArgumentException("Parameter name may not be null"); 
116         }
117         if (this.params == null) {
118             return null;
119         }
120         return (String) this.params.get(name.toLowerCase());
121     }
122 
123     /**
124      * Returns authentication realm. The realm may not be null.
125      * 
126      * @return the authentication realm
127      */
128     public String getRealm() {
129         return getParameter("realm");
130     }
131     
132     /**
133      * Returns a String identifying the authentication challenge.  This is
134      * used, in combination with the host and port to determine if
135      * authorization has already been attempted or not.  Schemes which
136      * require multiple requests to complete the authentication should
137      * return a different value for each stage in the request.
138      * 
139      * <p>Additionally, the ID should take into account any changes to the
140      * authentication challenge and return a different value when appropriate.
141      * For example when the realm changes in basic authentication it should be
142      * considered a different authentication attempt and a different value should
143      * be returned.</p>
144      * 
145      * <p>This method simply returns the realm for the challenge.</p>
146      * 
147      * @return String a String identifying the authentication challenge.  The
148      * returned value may be null.
149      * 
150      * @deprecated no longer used
151      */
152     public String getID() {
153         return getRealm();
154     }
155 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/package-frame.html100644 0 0 6213 10661532632 26410 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.auth

org.apache.commons.httpclient.auth

Classes

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/auth/package-summary.html100644 0 0 12324 10661532632 27033 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.auth

Package org.apache.commons.httpclient.auth

Class Summary
AuthChallengeException
AuthChallengeParser
AuthChallengeProcessor
AuthPolicy
AuthScheme
AuthSchemeBase
AuthScope
AuthState
AuthenticationException
BasicScheme
CredentialsNotAvailableException
CredentialsProvider
DigestScheme
HttpAuthRealm
HttpAuthenticator
InvalidCredentialsException
MalformedChallengeException
NTLM
NTLMScheme
RFC2617Scheme

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/Cookie2.html100644 0 0 62100 10661532627 25551 0ustar 0 0 Cookie2 xref

1   /*
2    * $Header: /cvsroot/httpc-cookie2/httpc-cookie2/httpcookie2SVN-patch.082805-2100.diff,v 1.1 2005/08/29 05:01:58 sjain700 Exp $
3    * $Revision:400312 $
4    * $Date:2006-05-06 14:49:41 +0200 (Sat, 06 May 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.cookie;
32  
33  import java.util.Date;
34  
35  import org.apache.commons.httpclient.Cookie;
36  
37  /**
38   * <p>
39   * Cookie class for {@link org.apache.commons.httpclient.cookie.RFC2965Spec}
40   * cookie specification. It extends {@link Cookie} class and adds newer cookie
41   * attributes and functions required for this specification.
42   * </p>
43   *
44   * @author Samit Jain (jain.samit@gmail.com)
45   * 
46   * @since 3.1
47   */
48  public class Cookie2 extends Cookie {
49  
50      // string constants for cookie attributes
51      public static final String DOMAIN = "domain";
52      public static final String PATH = "path";
53      public static final String PORT = "port";
54      public static final String VERSION = "version";
55      public static final String SECURE = "secure";
56      public static final String MAXAGE = "max-age";
57      public static final String COMMENT = "comment";
58      public static final String COMMENTURL = "commenturl";
59      public static final String DISCARD = "discard";
60  
61      /**
62       * Default constructor. Creates a blank cookie
63       */
64      public Cookie2() {
65          super(null, "noname", null, null, null, false);
66      }
67  
68      /**
69       * Creates a cookie with the given name, value and domain attribute.
70       *
71       * @param name    the cookie name
72       * @param value   the cookie value
73       * @param domain  the domain this cookie can be sent to
74       */
75      public Cookie2(String domain, String name, String value) {
76          super(domain, name, value);
77      }
78  
79      /**
80       * Creates a cookie with the given name, value, domain attribute,
81       * path attribute, expiration attribute, and secure attribute
82       *
83       * @param name    the cookie name
84       * @param value   the cookie value
85       * @param domain  the domain this cookie can be sent to
86       * @param path    the path prefix for which this cookie can be sent
87       * @param expires the {@link Date} at which this cookie expires,
88       *                or <tt>null</tt> if the cookie expires at the end
89       *                of the session
90       * @param secure if true this cookie can only be sent over secure
91       * connections
92       * @throws IllegalArgumentException If cookie name is null or blank,
93       *   cookie name contains a blank, or cookie name starts with character $
94       *
95       */
96      public Cookie2(String domain, String name, String value,
97                     String path, Date expires, boolean secure) {
98          super(domain, name, value, path, expires, secure);
99      }
100 
101     /**
102      * Creates a cookie with the given name, value, domain attribute,
103      * path attribute, expiration attribute, secure attribute, and ports
104      * attribute.
105      *
106      * @param name    the cookie name
107      * @param value   the cookie value
108      * @param domain  the domain this cookie can be sent to
109      * @param path    the path prefix for which this cookie can be sent
110      * @param expires the {@link Date} at which this cookie expires,
111      *                or <tt>null</tt> if the cookie expires at the end
112      *                of the session
113      * @param secure if true this cookie can only be sent over secure
114      * connections
115      * @param ports   the ports for which this cookie can be sent
116      * @throws IllegalArgumentException If cookie name is null or blank,
117      *   cookie name contains a blank, or cookie name starts with character $
118      *
119      */
120     public Cookie2(String domain, String name, String value,
121                    String path, Date expires, boolean secure, int[] ports) {
122         super(domain, name, value, path, expires, secure);
123         setPorts(ports);
124     }
125 
126    /**
127      * If a user agent (web browser) presents this cookie to a user, the
128      * cookie's purpose will be described by the information at this URL.
129      *
130      * @see #setCommentURL(String)
131      */
132     public String getCommentURL() {
133         return cookieCommentURL;
134     }
135 
136    /**
137      * If a user agent (web browser) presents this cookie to a user, the
138      * cookie's purpose will be described by the information at this URL.
139      *
140      * @param commentURL
141      *
142      * @see #getCommentURL()
143      */
144     public void setCommentURL(String commentURL) {
145         this.cookieCommentURL = commentURL;
146     }
147 
148     /**
149      * Get the Port attribute. It restricts the ports to which a cookie
150      * may be returned in a Cookie request header.
151      *
152      * @see #setPorts(int[])
153      */
154     public int[] getPorts() {
155         return cookiePorts;
156     }
157 
158    /**
159      * Set the Port attribute. It restricts the ports to which a cookie
160      * may be returned in a Cookie request header.
161      *
162      * @param ports
163      *
164      * @see #getPorts()
165      */
166     public void setPorts(int[] ports) {
167         this.cookiePorts = ports;
168     }
169 
170     /**
171      * Set the Discard attribute.
172      *
173      * Note: <tt>Discard</tt> attribute overrides <tt>Max-age</tt>.
174      *
175      * @see #isPersistent()
176      */
177     public void setDiscard(boolean toDiscard) {
178         discard = toDiscard;
179     }
180 
181     /**
182      * Returns <tt>false</tt> if the cookie should be discarded at the end
183      * of the "session"; <tt>true</tt> otherwise.
184      *
185      * @return <tt>false</tt> if the cookie should be discarded at the end
186      *         of the "session"; <tt>true</tt> otherwise
187      */
188     public boolean isPersistent() {
189         return (null != getExpiryDate()) && !discard;
190     }
191 
192     /**
193      * Indicates whether the cookie had a port attribute specified in the
194      * <tt>Set-Cookie2</tt> response header. 
195      *
196      * @param value <tt>true</tt> if port attribute is specified in response
197      * header.
198      *
199      * @see #isPortAttributeSpecified
200      */
201     public void setPortAttributeSpecified(boolean value) {
202         hasPortAttribute = value;
203     }
204 
205     /**
206      * @return <tt>true</tt> if cookie port attribute was specified in the
207      * <tt>Set-Cookie2</tt> header.
208      *
209      * @see #setPortAttributeSpecified
210      */
211     public boolean isPortAttributeSpecified() {
212         return hasPortAttribute;
213     }
214 
215     /**
216      * Indicates whether the Port attribute in <tt>Set-Cookie2</tt> header
217      * contains no value (is of the form Port="").
218      * <p>
219      * This value is required for generating
220      * the <tt>Cookie</tt> request header because the specification requires that if
221      * <tt>Set-Cookie2</tt> header contains a blank value for port attribute,
222      * the <tt>Cookie</tt> header should also contain a port attribute with no value.
223      *
224      * @param value <tt>true</tt> if port attribute is specified as blank in response
225      * header.
226      *
227      * @see #isPortAttributeBlank
228      */
229     public void setPortAttributeBlank(boolean value) {
230         isPortAttributeBlank = value;
231     }
232 
233     /**
234      * @return <tt>true</tt> if the port attribute in <tt>Set-Cookie2</tt> header
235      * had no value (was of the form Port="").
236      *
237      * @see #setPortAttributeBlank
238      */
239     public boolean isPortAttributeBlank() {
240         return isPortAttributeBlank;
241     }
242 
243     /**
244      * Indicates whether the cookie had a version attribute specified in the
245      * <tt>Set-Cookie2</tt> response header. 
246      *
247      * @param value <tt>true</tt> if version attribute is specified in response
248      * header.
249      * @see #isVersionAttributeSpecified()
250      */
251     public void setVersionAttributeSpecified(boolean value) {
252         hasVersionAttribute = value;
253     }
254 
255     /**
256      * @return <tt>true</tt> if cookie version attribute was specified in the
257      * <tt>Set-Cookie2</tt> header.
258      *
259      * @see #setVersionAttributeSpecified
260      */
261     public boolean isVersionAttributeSpecified() {
262         return hasVersionAttribute;
263     }
264 
265     /**
266      * Return a textual representation of the cookie.
267      *
268      * @return string.
269      */
270     public String toExternalForm() {
271         CookieSpec spec =
272                 CookiePolicy.getCookieSpec(CookiePolicy.RFC_2965);
273         return spec.formatCookie(this);
274     }
275 
276     /**
277      * Comment URL attribute
278      */
279     private String cookieCommentURL;
280 
281     /**
282      * Port attribute.
283      */
284     private int[] cookiePorts;
285 
286     /**
287      * Discard attribute.
288      */
289     private boolean discard = false;
290 
291     /**
292      * Indicates if the set-cookie2 header included a Port attribute for this
293      * cookie
294      */
295     private boolean hasPortAttribute = false;
296 
297     /**
298      * Indicates if the set-cookie2 header's Port attribute did not have
299      * any value.
300      */
301     private boolean isPortAttributeBlank = false;
302 
303     /**
304      * Indicates if the set-cookie2 header included a Version attribute
305      */
306     private boolean hasVersionAttribute = false;
307 
308 
309 }
310 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/CookieAttributeHandler.html100644 0 0 17733 10661532627 30665 0ustar 0 0 CookieAttributeHandler xref

1   /*
2    * $HeadURL:https://svn.apache.org/repos/asf/jakarta/commons/proper/httpclient/trunk/src/java/org/apache/commons/httpclient/cookie/CookieAttributeHandler.java $
3    * $Revision:400312 $
4    * $Date:2006-05-06 14:49:41 +0200 (Sat, 06 May 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient.cookie;
31  
32  import org.apache.commons.httpclient.Cookie;
33  
34  /**
35   * Ths interface represents a cookie attribute handler responsible
36   * for parsing, validating, and matching a specific cookie attribute, 
37   * such as path, domain, port, etc.
38   *
39   * Different cookie specifications can provide a specific
40   * implementation for this class based on their cookie handling
41   * rules.
42   *
43   * @author jain.samit@gmail.com (Samit Jain)
44   * 
45   * @since 3.1
46   */
47  public interface CookieAttributeHandler {
48  
49    /**
50     * Parse the given cookie attribute value and update the corresponding
51     * {@link org.apache.commons.httpclient.Cookie} property.
52     *
53     * @param cookie {@link org.apache.commons.httpclient.Cookie} to be updated
54     * @param value cookie attribute value from the cookie response header
55     */
56    void parse(Cookie cookie, String value)
57            throws MalformedCookieException;
58  
59    /**
60     * Peforms cookie validation for the given attribute value.
61     *
62     * @param cookie {@link org.apache.commons.httpclient.Cookie} to validate
63     * @param origin the cookie source to validate against
64     * @throws MalformedCookieException if cookie validation fails for this attribute
65     */
66    void validate(Cookie cookie, CookieOrigin origin)
67            throws MalformedCookieException;
68  
69    /**
70     * Matches the given value (property of the destination host where request is being
71     * submitted) with the corresponding cookie attribute.
72     *
73     * @param cookie {@link org.apache.commons.httpclient.Cookie} to match
74     * @param origin the cookie source to match against
75     * @return <tt>true</tt> if the match is successful; <tt>false</tt> otherwise
76     */
77    boolean match(Cookie cookie, CookieOrigin origin);
78  
79  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/CookieOrigin.html100644 0 0 20312 10661532627 26636 0ustar 0 0 CookieOrigin xref

1   /*
2    * $HeadURL:https://svn.apache.org/repos/asf/jakarta/commons/proper/httpclient/trunk/src/java/org/apache/commons/httpclient/cookie/CookieOrigin.java $
3    * $Revision:400312 $
4    * $Date:2006-05-06 14:49:41 +0200 (Sat, 06 May 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient.cookie;
31  
32  /**
33   * CookieOrigin class incapsulates details of an origin server that 
34   * are relevant when parsing, validating or matching HTTP cookies.
35   * 
36   * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
37   * 
38   * @since 3.1
39   */
40  public final class CookieOrigin {
41  
42  	private final String host;
43  	private final int port;
44  	private final String path;
45  	private final boolean secure;
46  	
47  	public CookieOrigin(final String host, int port, final String path, boolean secure) {
48  		super();
49          if (host == null) {
50              throw new IllegalArgumentException(
51                      "Host of origin may not be null");
52          }
53          if (host.trim().equals("")) {
54              throw new IllegalArgumentException(
55                      "Host of origin may not be blank");
56          }
57          if (port < 0) {
58              throw new IllegalArgumentException("Invalid port: " + port);
59          }
60          if (path == null) {
61              throw new IllegalArgumentException(
62                      "Path of origin may not be null.");
63          }
64  		this.host = host;
65  		this.port = port;
66  		this.path = path;
67  		this.secure = secure;
68  	}
69  
70  	public String getHost() {
71  		return this.host;
72  	}
73  
74  	public String getPath() {
75  		return this.path;
76  	}
77  
78  	public int getPort() {
79  		return this.port;
80  	}
81  
82  	public boolean isSecure() {
83  		return this.secure;
84  	}
85  	
86  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/CookiePathComparator.html100644 0 0 17457 10661532627 30353 0ustar 0 0 CookiePathComparator xref

1   /*
2    * $Header$
3    * $Revision:400312 $
4    * $Date:2006-05-06 14:49:41 +0200 (Sat, 06 May 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.cookie;
32  
33  import java.util.Comparator;
34  
35  import org.apache.commons.httpclient.Cookie;
36  
37  /**
38   * This cookie comparator ensures that multiple cookies satisfying 
39   * a common criteria are ordered in the <tt>Cookie</tt> header such
40   * that those with more specific Path attributes precede those with
41   * less specific.
42   *  
43   * <p>
44   * This comparator assumes that Path attributes of two cookies 
45   * path-match a commmon request-URI. Otherwise, the result of the
46   * comparison is undefined.
47   * </p>
48   * 
49   * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
50   * 
51   * @since 3.1
52   */
53  public class CookiePathComparator implements Comparator {
54  
55      private String normalizePath(final Cookie cookie) {
56          String path = cookie.getPath();
57          if (path == null) {
58              path = "/";
59          }
60          if (!path.endsWith("/")) {
61              path = path + "/";
62          }
63          return path;
64      }
65      
66      public int compare(final Object o1, final Object o2) {
67          Cookie c1 = (Cookie) o1;
68          Cookie c2 = (Cookie) o2;
69          String path1 = normalizePath(c1);
70          String path2 = normalizePath(c2);
71          if (path1.equals(path2)) {
72              return 0;
73          } else if (path1.startsWith(path2)) {
74              return -1;
75          } else if (path2.startsWith(path1)) {
76              return 1;
77          } else {
78              // Does not really matter
79              return 0;
80          }
81      }
82  
83  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/CookiePolicy.html100644 0 0 71333 10661532627 26657 0ustar 0 0 CookiePolicy xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/CookiePolicy.java,v 1.15 2004/09/14 20:11:31 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.cookie;
32  
33  import java.util.Collections;
34  import java.util.HashMap;
35  import java.util.Map;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  
40  /**
41   * Cookie management policy class. The cookie policy provides corresponding
42   * cookie management interfrace for a given type or version of cookie. 
43   * <p>RFC 2109 specification is used per default. Other supported specification
44   * can be  chosen when appropriate or set default when desired
45   * <p>The following specifications are provided:
46   *  <ul>
47   *   <li><tt>BROWSER_COMPATIBILITY</tt>: compatible with the common cookie 
48   *   management practices (even if they are not 100% standards compliant)
49   *   <li><tt>NETSCAPE</tt>: Netscape cookie draft compliant
50   *   <li><tt>RFC_2109</tt>: RFC2109 compliant (default)
51   *   <li><tt>IGNORE_COOKIES</tt>: do not automcatically process cookies
52   *  </ul>
53   * 
54   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
55   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
56   *
57   * @since 2.0
58   */
59  public abstract class CookiePolicy {
60  
61      private static Map SPECS = Collections.synchronizedMap(new HashMap());
62      
63      /**
64       * The policy that provides high degree of compatibilty 
65       * with common cookie management of popular HTTP agents.
66       * 
67       * @since 3.0
68       */
69      public static final String BROWSER_COMPATIBILITY = "compatibility";
70      
71      /** 
72       * The Netscape cookie draft compliant policy. 
73       * 
74       * @since 3.0
75       */
76      public static final String NETSCAPE = "netscape";
77  
78      /** 
79       * The RFC 2109 compliant policy. 
80       * 
81       * @since 3.0
82       */
83      public static final String RFC_2109 = "rfc2109";
84  
85      /**
86       * The RFC 2965 compliant policy.
87       *
88       * @since 3.0
89       */
90      public static final String RFC_2965 = "rfc2965";
91  
92      /**
93       * The policy that ignores cookies. 
94       * 
95       * @since 3.0
96       */
97      public static final String IGNORE_COOKIES = "ignoreCookies";
98      
99      /** 
100      * The default cookie policy. 
101      * 
102      * @since 3.0
103      */
104     public static final String DEFAULT = "default";
105     
106     static {
107         CookiePolicy.registerCookieSpec(DEFAULT, RFC2109Spec.class);
108         CookiePolicy.registerCookieSpec(RFC_2109, RFC2109Spec.class);
109         CookiePolicy.registerCookieSpec(RFC_2965, RFC2965Spec.class);
110         CookiePolicy.registerCookieSpec(BROWSER_COMPATIBILITY, CookieSpecBase.class);
111         CookiePolicy.registerCookieSpec(NETSCAPE, NetscapeDraftSpec.class);
112         CookiePolicy.registerCookieSpec(IGNORE_COOKIES, IgnoreCookiesSpec.class);
113     }
114     
115     /**
116      * The <tt>COMPATIBILITY</tt> policy provides high compatibilty 
117      * with common cookie management of popular HTTP agents.
118      * 
119      * @deprecated Use {@link #BROWSER_COMPATIBILITY}
120      */
121     public static final int COMPATIBILITY = 0;
122 
123     /** 
124      * The <tt>NETSCAPE_DRAFT</tt> Netscape draft compliant policy.
125      * 
126      * @deprecated Use {@link #NETSCAPE} 
127      */
128     public static final int NETSCAPE_DRAFT = 1;
129 
130     /** 
131      * The <tt>RFC2109</tt> RFC 2109 compliant policy.
132      * 
133      * @deprecated Use {@link #RFC_2109} 
134      */
135     public static final int RFC2109 = 2;
136 
137     /**
138      * The <tt>RFC2965</tt> RFC 2965 compliant policy.
139      *
140      * @deprecated Use {@link #RFC_2965}
141      */
142     public static final int RFC2965 = 3;
143 
144     /**
145      * The default cookie policy.
146      *  
147      * @deprecated Use {@link #DEFAULT} 
148      */
149     private static int defaultPolicy = RFC2109;
150 
151     /** Log object. */
152     protected static final Log LOG = LogFactory.getLog(CookiePolicy.class);
153 
154     /**
155      * Registers a new {@link CookieSpec cookie specification} with the given identifier. 
156      * If a specification with the given ID already exists it will be overridden.  
157      * This ID is the same one used to retrieve the {@link CookieSpec cookie specification} 
158      * from {@link #getCookieSpec(String)}.
159      * 
160      * @param id the identifier for this specification
161      * @param clazz the {@link CookieSpec cookie specification} class to register
162      * 
163      * @see #getCookieSpec(String)
164      * 
165      * @since 3.0
166      */
167     public static void registerCookieSpec(final String id, final Class clazz) {
168          if (id == null) {
169              throw new IllegalArgumentException("Id may not be null");
170          }
171         if (clazz == null) {
172             throw new IllegalArgumentException("Cookie spec class may not be null");
173         }
174         SPECS.put(id.toLowerCase(), clazz);
175     }
176 
177     /**
178      * Unregisters the {@link CookieSpec cookie specification} with the given ID.
179      * 
180      * @param id the ID of the {@link CookieSpec cookie specification} to unregister
181      * 
182      * @since 3.0
183      */
184     public static void unregisterCookieSpec(final String id) {
185          if (id == null) {
186              throw new IllegalArgumentException("Id may not be null");
187          }
188          SPECS.remove(id.toLowerCase());
189     }
190 
191     /**
192      * Gets the {@link CookieSpec cookie specification} with the given ID.
193      * 
194      * @param id the {@link CookieSpec cookie specification} ID
195      * 
196      * @return {@link CookieSpec cookie specification}
197      * 
198      * @throws IllegalStateException if a policy with the ID cannot be found
199      * 
200      * @since 3.0
201      */
202     public static CookieSpec getCookieSpec(final String id) 
203         throws IllegalStateException {
204 
205         if (id == null) {
206             throw new IllegalArgumentException("Id may not be null");
207         }
208         Class clazz = (Class)SPECS.get(id.toLowerCase());
209 
210         if (clazz != null) {
211             try {
212                 return (CookieSpec)clazz.newInstance();
213             } catch (Exception e) {
214                 LOG.error("Error initializing cookie spec: " + id, e);
215                 throw new IllegalStateException(id + 
216                     " cookie spec implemented by " +
217                     clazz.getName() + " could not be initialized");
218             }
219         } else {
220             throw new IllegalStateException("Unsupported cookie spec " + id);
221         }
222     } 
223 
224     /**
225      * @return default cookie policy
226      * 
227      * @deprecated Use {@link #getDefaultSpec()}
228      * 
229      * @see #getDefaultSpec()
230      */
231     public static int getDefaultPolicy() {
232         return defaultPolicy;
233     }
234     
235 
236     /**
237      * @param policy new default cookie policy
238      * 
239      * @deprecated Use {@link CookiePolicy#registerCookieSpec(String, Class)}
240      * @see #DEFAULT 
241      */
242     public static void setDefaultPolicy(int policy) {
243         defaultPolicy = policy;
244     }
245     
246     /**
247      * @param policy cookie policy to get the CookieSpec for
248      * @return cookie specification interface for the given policy
249      * 
250      * @deprecated Use {@link CookiePolicy#getCookieSpec(String)} 
251      */
252     public static CookieSpec getSpecByPolicy(int policy) {
253         switch(policy) {
254             case COMPATIBILITY: 
255                 return new CookieSpecBase(); 
256             case NETSCAPE_DRAFT: 
257                 return new NetscapeDraftSpec(); 
258             case RFC2109:
259                 return new RFC2109Spec();
260             case RFC2965:
261                 return new RFC2965Spec();
262             default:
263                 return getDefaultSpec(); 
264         }
265     }
266 
267 
268     /**
269      * Returns {@link CookieSpec cookie specification} registered as {@link #DEFAULT}. 
270      * If no default {@link CookieSpec cookie specification} has been registered, 
271      * {@link RFC2109Spec RFC2109 specification} is returned.
272      *  
273      * @return default {@link CookieSpec cookie specification}
274      * 
275      * @see #DEFAULT
276      */
277     public static CookieSpec getDefaultSpec() {
278         try {
279             return getCookieSpec(DEFAULT);
280         } catch (IllegalStateException e) {
281             LOG.warn("Default cookie policy is not registered");
282             return new RFC2109Spec();
283         }
284     }
285     
286 
287     /**
288      * Gets the CookieSpec for a particular cookie version.
289      * 
290      * <p>Supported versions:
291      * <ul>
292      *  <li><tt>version 0</tt> corresponds to the Netscape draft
293      *  <li><tt>version 1</tt> corresponds to the RFC 2109
294      *  <li>Any other cookie value coresponds to the default spec
295      * <ul>
296      *
297      * @param ver the cookie version to get the spec for
298      * @return cookie specification interface intended for processing 
299      *  cookies with the given version
300      * 
301      * @deprecated Use {@link CookiePolicy#getCookieSpec(String)}
302      */
303     public static CookieSpec getSpecByVersion(int ver) {
304         switch(ver) {
305             case 0: 
306                 return new NetscapeDraftSpec(); 
307             case 1:
308                 return new RFC2109Spec();
309             default:
310                 return getDefaultSpec(); 
311         }
312     }
313 
314     /**
315      * @return cookie specification interface that provides high compatibilty 
316      * with common cookie management of popular HTTP agents
317      * 
318      * @deprecated Use {@link CookiePolicy#getCookieSpec(String)}
319      */
320     public static CookieSpec getCompatibilitySpec() {
321         return getSpecByPolicy(COMPATIBILITY);
322     }
323 
324     /**
325      * Obtains the currently registered cookie policy names.
326      * 
327      * Note that the DEFAULT policy (if present) is likely to be the same
328      * as one of the other policies, but does not have to be.
329      * 
330      * @return array of registered cookie policy names
331      * 
332      * @since 3.1
333      */
334     public static String[] getRegisteredCookieSpecs(){
335             return (String[]) SPECS.keySet().toArray(new String [SPECS.size()]); 
336     }
337     
338 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/CookieSpec.html100644 0 0 54133 10661532627 26311 0ustar 0 0 CookieSpec xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/CookieSpec.java,v 1.11 2004/09/14 20:11:31 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.cookie;
32  
33  import java.util.Collection;
34  
35  import org.apache.commons.httpclient.Header;
36  import org.apache.commons.httpclient.NameValuePair;
37  import org.apache.commons.httpclient.Cookie;
38  
39  /**
40   * Defines the cookie management specification.
41   * <p>Cookie management specification must define
42   * <ul>
43   *   <li> rules of parsing "Set-Cookie" header
44   *   <li> rules of validation of parsed cookies
45   *   <li>  formatting of "Cookie" header 
46   * </ul>
47   * for a given host, port and path of origin
48   * 
49   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
50   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
51   *
52   * @since 2.0
53   */
54  public interface CookieSpec {    
55  
56      /** Path delimiter */
57      static final String PATH_DELIM = "/";
58  
59      /** Path delimiting charachter */
60      static final char PATH_DELIM_CHAR = PATH_DELIM.charAt(0);
61  
62      /**
63        * Parse the <tt>"Set-Cookie"</tt> header value into Cookie array.
64        * 
65        * <p>This method will not perform the validation of the resultant
66        * {@link Cookie}s</p> 
67        *
68        * @see #validate(String, int, String, boolean, Cookie)
69        *
70        * @param host the host which sent the <tt>Set-Cookie</tt> header
71        * @param port the port which sent the <tt>Set-Cookie</tt> header
72        * @param path the path which sent the <tt>Set-Cookie</tt> header
73        * @param secure <tt>true</tt> when the <tt>Set-Cookie</tt> header 
74        *  was received over secure conection
75        * @param header the <tt>Set-Cookie</tt> received from the server
76        * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie value
77        * @throws MalformedCookieException if an exception occurs during parsing
78        * @throws IllegalArgumentException if an input parameter is illegal
79        */
80      Cookie[] parse(String host, int port, String path, boolean secure,
81        final String header)
82        throws MalformedCookieException, IllegalArgumentException;
83  
84      /**
85        * Parse the <tt>"Set-Cookie"</tt> Header into an array of Cookies.
86        *
87        * <p>This method will not perform the validation of the resultant
88        * {@link Cookie}s</p> 
89        *
90        * @see #validate(String, int, String, boolean, Cookie)
91        *
92        * @param host the host which sent the <tt>Set-Cookie</tt> header
93        * @param port the port which sent the <tt>Set-Cookie</tt> header
94        * @param path the path which sent the <tt>Set-Cookie</tt> header
95        * @param secure <tt>true</tt> when the <tt>Set-Cookie</tt> header 
96        *  was received over secure conection
97        * @param header the <tt>Set-Cookie</tt> received from the server
98        * @return an array of <tt>Cookie</tt>s parsed from the header
99        * @throws MalformedCookieException if an exception occurs during parsing
100       * @throws IllegalArgumentException if an input parameter is illegal
101       */
102     Cookie[] parse(String host, int port, String path, boolean secure, 
103       final Header header)
104       throws MalformedCookieException, IllegalArgumentException;
105 
106     /**
107       * Parse the cookie attribute and update the corresponsing Cookie 
108       *  properties.
109       *
110       * @param attribute cookie attribute from the <tt>Set-Cookie</tt>
111       * @param cookie the to be updated
112       * @throws MalformedCookieException if an exception occurs during parsing
113       * @throws IllegalArgumentException if an input parameter is illegal
114       */
115     void parseAttribute(NameValuePair attribute, Cookie cookie)
116       throws MalformedCookieException, IllegalArgumentException;
117 
118     /**
119       * Validate the cookie according to validation rules defined by the 
120       *  cookie specification.
121       *
122       * @param host the host from which the {@link Cookie} was received
123       * @param port the port from which the {@link Cookie} was received
124       * @param path the path from which the {@link Cookie} was received
125       * @param secure <tt>true</tt> when the {@link Cookie} was received 
126       *  using a secure connection
127       * @param cookie the Cookie to validate
128       * @throws MalformedCookieException if the cookie is invalid
129       * @throws IllegalArgumentException if an input parameter is illegal
130       */
131     void validate(String host, int port, String path, boolean secure, 
132       final Cookie cookie) 
133       throws MalformedCookieException, IllegalArgumentException;
134     
135     
136     /**
137      * Sets the {@link Collection} of date patterns used for parsing. The String patterns must be 
138      * compatible with {@link java.text.SimpleDateFormat}.
139      *
140      * @param datepatterns collection of date patterns
141      */
142     void setValidDateFormats(Collection datepatterns);
143     
144     /**
145      * Returns the {@link Collection} of date patterns used for parsing. The String patterns are compatible 
146      * with the {@link java.text.SimpleDateFormat}.
147      *
148      * @return collection of date patterns
149      */
150     Collection getValidDateFormats();
151     
152     /**
153      * Determines if a Cookie matches a location.
154      *
155      * @param host the host to which the request is being submitted
156      * @param port the port to which the request is being submitted
157      * @param path the path to which the request is being submitted
158      * @param secure <tt>true</tt> if the request is using a secure connection
159      * @param cookie the Cookie to be matched
160      *
161      * @return <tt>true</tt> if the cookie should be submitted with a request 
162      *  with given attributes, <tt>false</tt> otherwise.
163      */
164     boolean match(String host, int port, String path, boolean secure,
165         final Cookie cookie);
166 
167     /**
168      * Determines which of an array of Cookies matches a location.
169      *
170      * @param host the host to which the request is being submitted
171      * @param port the port to which the request is being submitted 
172      *  (currenlty ignored)
173      * @param path the path to which the request is being submitted
174      * @param secure <tt>true</tt> if the request is using a secure protocol
175      * @param cookies an array of <tt>Cookie</tt>s to be matched
176      *
177      * @return <tt>true</tt> if the cookie should be submitted with a request 
178      *  with given attributes, <tt>false</tt> otherwise.
179      */
180     Cookie[] match(String host, int port, String path, boolean secure, 
181         final Cookie cookies[]);
182 
183     /**
184      * Performs domain-match as defined by the cookie specification.
185      * @param host The target host.
186      * @param domain The cookie domain attribute.
187      * @return true if the specified host matches the given domain.
188      * 
189      * @since 3.0
190      */
191     boolean domainMatch(String host, String domain);
192 
193     /**
194      * Performs path-match as defined by the cookie specification.
195      * @param path The target path.
196      * @param topmostPath The cookie path attribute.
197      * @return true if the paths match
198      * 
199      * @since 3.0
200      */
201     boolean pathMatch(String path, String topmostPath);
202 
203     /**
204      * Create a <tt>"Cookie"</tt> header value for an array of cookies.
205      *
206      * @param cookie the cookie to be formatted as string
207      * @return a string suitable for sending in a <tt>"Cookie"</tt> header.
208      */
209     String formatCookie(Cookie cookie);
210 
211     /**
212      * Create a <tt>"Cookie"</tt> header value for an array of cookies.
213      *
214      * @param cookies the Cookies to be formatted
215      * @return a string suitable for sending in a Cookie header.
216      * @throws IllegalArgumentException if an input parameter is illegal
217      */
218     String formatCookies(Cookie[] cookies) throws IllegalArgumentException;
219     
220     /**
221      * Create a <tt>"Cookie"</tt> Header for an array of Cookies.
222      *
223      * @param cookies the Cookies format into a Cookie header
224      * @return a Header for the given Cookies.
225      * @throws IllegalArgumentException if an input parameter is illegal
226      */
227     Header formatCookieHeader(Cookie[] cookies) throws IllegalArgumentException;
228 
229     /**
230      * Create a <tt>"Cookie"</tt> Header for single Cookie.
231      *
232      * @param cookie the Cookie format as a <tt>Cookie</tt> header
233      * @return a Cookie header.
234      * @throws IllegalArgumentException if an input parameter is illegal
235      */
236     Header formatCookieHeader(Cookie cookie) throws IllegalArgumentException;
237 
238 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/CookieSpecBase.html100644 0 0 171026 10661532627 27125 0ustar 0 0 CookieSpecBase xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java,v 1.28 2004/11/06 19:15:42 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */ 
30  
31  package org.apache.commons.httpclient.cookie;
32  
33  import java.util.Collection;
34  import java.util.Date;
35  import java.util.LinkedList;
36  import java.util.List;
37  
38  import org.apache.commons.httpclient.Cookie;
39  import org.apache.commons.httpclient.Header;
40  import org.apache.commons.httpclient.HeaderElement;
41  import org.apache.commons.httpclient.NameValuePair;
42  import org.apache.commons.httpclient.util.DateParseException;
43  import org.apache.commons.httpclient.util.DateUtil;
44  import org.apache.commons.logging.Log;
45  import org.apache.commons.logging.LogFactory;
46  
47  /**
48   * 
49   * Cookie management functions shared by all specification.
50   *
51   * @author  B.C. Holmes
52   * @author <a href="mailto:jericho@thinkfree.com">Park, Sung-Gu</a>
53   * @author <a href="mailto:dsale@us.britannica.com">Doug Sale</a>
54   * @author Rod Waldhoff
55   * @author dIon Gillard
56   * @author Sean C. Sullivan
57   * @author <a href="mailto:JEvans@Cyveillance.com">John Evans</a>
58   * @author Marc A. Saegesser
59   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
60   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
61   * 
62   * @since 2.0 
63   */
64  public class CookieSpecBase implements CookieSpec {
65      
66      /** Log object */
67      protected static final Log LOG = LogFactory.getLog(CookieSpec.class);
68  
69      /** Valid date patterns */
70      private Collection datepatterns = null;
71      
72      /** Default constructor */
73      public CookieSpecBase() {
74          super();
75      }
76  
77  
78      /**
79        * Parses the Set-Cookie value into an array of <tt>Cookie</tt>s.
80        *
81        * <P>The syntax for the Set-Cookie response header is:
82        *
83        * <PRE>
84        * set-cookie      =    "Set-Cookie:" cookies
85        * cookies         =    1#cookie
86        * cookie          =    NAME "=" VALUE * (";" cookie-av)
87        * NAME            =    attr
88        * VALUE           =    value
89        * cookie-av       =    "Comment" "=" value
90        *                 |    "Domain" "=" value
91        *                 |    "Max-Age" "=" value
92        *                 |    "Path" "=" value
93        *                 |    "Secure"
94        *                 |    "Version" "=" 1*DIGIT
95        * </PRE>
96        *
97        * @param host the host from which the <tt>Set-Cookie</tt> value was
98        * received
99        * @param port the port from which the <tt>Set-Cookie</tt> value was
100       * received
101       * @param path the path from which the <tt>Set-Cookie</tt> value was
102       * received
103       * @param secure <tt>true</tt> when the <tt>Set-Cookie</tt> value was
104       * received over secure conection
105       * @param header the <tt>Set-Cookie</tt> received from the server
106       * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie value
107       * @throws MalformedCookieException if an exception occurs during parsing
108       */
109     public Cookie[] parse(String host, int port, String path, 
110         boolean secure, final String header) 
111         throws MalformedCookieException {
112             
113         LOG.trace("enter CookieSpecBase.parse(" 
114             + "String, port, path, boolean, Header)");
115 
116         if (host == null) {
117             throw new IllegalArgumentException(
118                 "Host of origin may not be null");
119         }
120         if (host.trim().equals("")) {
121             throw new IllegalArgumentException(
122                 "Host of origin may not be blank");
123         }
124         if (port < 0) {
125             throw new IllegalArgumentException("Invalid port: " + port);
126         }
127         if (path == null) {
128             throw new IllegalArgumentException(
129                 "Path of origin may not be null.");
130         }
131         if (header == null) {
132             throw new IllegalArgumentException("Header may not be null.");
133         }
134 
135         if (path.trim().equals("")) {
136             path = PATH_DELIM;
137         }
138         host = host.toLowerCase();
139 
140         String defaultPath = path;    
141         int lastSlashIndex = defaultPath.lastIndexOf(PATH_DELIM);
142         if (lastSlashIndex >= 0) {
143             if (lastSlashIndex == 0) {
144                 //Do not remove the very first slash
145                 lastSlashIndex = 1;
146             }
147             defaultPath = defaultPath.substring(0, lastSlashIndex);
148         }
149 
150         HeaderElement[] headerElements = null;
151 
152         boolean isNetscapeCookie = false; 
153         int i1 = header.toLowerCase().indexOf("expires=");
154         if (i1 != -1) {
155             i1 += "expires=".length();
156             int i2 = header.indexOf(";", i1);
157             if (i2 == -1) {
158                 i2 = header.length(); 
159             }
160             try {
161                 DateUtil.parseDate(header.substring(i1, i2), this.datepatterns);
162                 isNetscapeCookie = true; 
163             } catch (DateParseException e) {
164                 // Does not look like a valid expiry date
165             }
166         }
167         if (isNetscapeCookie) {
168             headerElements = new HeaderElement[] {
169                     new HeaderElement(header.toCharArray())
170             };
171         } else {
172             headerElements = HeaderElement.parseElements(header.toCharArray());
173         }
174         
175         Cookie[] cookies = new Cookie[headerElements.length];
176 
177         for (int i = 0; i < headerElements.length; i++) {
178 
179             HeaderElement headerelement = headerElements[i];
180             Cookie cookie = null;
181             try {
182                 cookie = new Cookie(host,
183                                     headerelement.getName(),
184                                     headerelement.getValue(),
185                                     defaultPath, 
186                                     null,
187                                     false);
188             } catch (IllegalArgumentException e) {
189                 throw new MalformedCookieException(e.getMessage()); 
190             }
191             // cycle through the parameters
192             NameValuePair[] parameters = headerelement.getParameters();
193             // could be null. In case only a header element and no parameters.
194             if (parameters != null) {
195 
196                 for (int j = 0; j < parameters.length; j++) {
197                     parseAttribute(parameters[j], cookie);
198                 }
199             }
200             cookies[i] = cookie;
201         }
202         return cookies;
203     }
204 
205 
206     /**
207       * Parse the <tt>"Set-Cookie"</tt> {@link Header} into an array of {@link
208       * Cookie}s.
209       *
210       * <P>The syntax for the Set-Cookie response header is:
211       *
212       * <PRE>
213       * set-cookie      =    "Set-Cookie:" cookies
214       * cookies         =    1#cookie
215       * cookie          =    NAME "=" VALUE * (";" cookie-av)
216       * NAME            =    attr
217       * VALUE           =    value
218       * cookie-av       =    "Comment" "=" value
219       *                 |    "Domain" "=" value
220       *                 |    "Max-Age" "=" value
221       *                 |    "Path" "=" value
222       *                 |    "Secure"
223       *                 |    "Version" "=" 1*DIGIT
224       * </PRE>
225       *
226       * @param host the host from which the <tt>Set-Cookie</tt> header was
227       * received
228       * @param port the port from which the <tt>Set-Cookie</tt> header was
229       * received
230       * @param path the path from which the <tt>Set-Cookie</tt> header was
231       * received
232       * @param secure <tt>true</tt> when the <tt>Set-Cookie</tt> header was
233       * received over secure conection
234       * @param header the <tt>Set-Cookie</tt> received from the server
235       * @return an array of <tt>Cookie</tt>s parsed from the <tt>"Set-Cookie"
236       * </tt> header
237       * @throws MalformedCookieException if an exception occurs during parsing
238       */
239     public Cookie[] parse(
240         String host, int port, String path, boolean secure, final Header header)
241         throws MalformedCookieException {
242             
243         LOG.trace("enter CookieSpecBase.parse("
244             + "String, port, path, boolean, String)");
245         if (header == null) {
246             throw new IllegalArgumentException("Header may not be null.");
247         }
248         return parse(host, port, path, secure, header.getValue());
249     }
250 
251 
252     /**
253       * Parse the cookie attribute and update the corresponsing {@link Cookie}
254       * properties.
255       *
256       * @param attribute {@link HeaderElement} cookie attribute from the
257       * <tt>Set- Cookie</tt>
258       * @param cookie {@link Cookie} to be updated
259       * @throws MalformedCookieException if an exception occurs during parsing
260       */
261 
262     public void parseAttribute(
263         final NameValuePair attribute, final Cookie cookie)
264         throws MalformedCookieException {
265             
266         if (attribute == null) {
267             throw new IllegalArgumentException("Attribute may not be null.");
268         }
269         if (cookie == null) {
270             throw new IllegalArgumentException("Cookie may not be null.");
271         }
272         final String paramName = attribute.getName().toLowerCase();
273         String paramValue = attribute.getValue();
274 
275         if (paramName.equals("path")) {
276 
277             if ((paramValue == null) || (paramValue.trim().equals(""))) {
278                 paramValue = "/";
279             }
280             cookie.setPath(paramValue);
281             cookie.setPathAttributeSpecified(true);
282 
283         } else if (paramName.equals("domain")) {
284 
285             if (paramValue == null) {
286                 throw new MalformedCookieException(
287                     "Missing value for domain attribute");
288             }
289             if (paramValue.trim().equals("")) {
290                 throw new MalformedCookieException(
291                     "Blank value for domain attribute");
292             }
293             cookie.setDomain(paramValue);
294             cookie.setDomainAttributeSpecified(true);
295 
296         } else if (paramName.equals("max-age")) {
297 
298             if (paramValue == null) {
299                 throw new MalformedCookieException(
300                     "Missing value for max-age attribute");
301             }
302             int age;
303             try {
304                 age = Integer.parseInt(paramValue);
305             } catch (NumberFormatException e) {
306                 throw new MalformedCookieException ("Invalid max-age "
307                     + "attribute: " + e.getMessage());
308             }
309             cookie.setExpiryDate(
310                 new Date(System.currentTimeMillis() + age * 1000L));
311 
312         } else if (paramName.equals("secure")) {
313 
314             cookie.setSecure(true);
315 
316         } else if (paramName.equals("comment")) {
317 
318             cookie.setComment(paramValue);
319 
320         } else if (paramName.equals("expires")) {
321 
322             if (paramValue == null) {
323                 throw new MalformedCookieException(
324                     "Missing value for expires attribute");
325             }
326 
327             try {
328                 cookie.setExpiryDate(DateUtil.parseDate(paramValue, this.datepatterns));
329             } catch (DateParseException dpe) {
330                 LOG.debug("Error parsing cookie date", dpe);
331                 throw new MalformedCookieException(
332                     "Unable to parse expiration date parameter: " 
333                     + paramValue);
334             }
335         } else {
336             if (LOG.isDebugEnabled()) {
337                 LOG.debug("Unrecognized cookie attribute: " 
338                     + attribute.toString());
339             }
340         }
341     }
342 
343     
344 	public Collection getValidDateFormats() {
345 		return this.datepatterns;
346 	}
347 
348 	public void setValidDateFormats(final Collection datepatterns) {
349 		this.datepatterns = datepatterns;
350 	}
351 
352 	/**
353       * Performs most common {@link Cookie} validation
354       *
355       * @param host the host from which the {@link Cookie} was received
356       * @param port the port from which the {@link Cookie} was received
357       * @param path the path from which the {@link Cookie} was received
358       * @param secure <tt>true</tt> when the {@link Cookie} was received using a
359       * secure connection
360       * @param cookie The cookie to validate.
361       * @throws MalformedCookieException if an exception occurs during
362       * validation
363       */
364     
365     public void validate(String host, int port, String path, 
366         boolean secure, final Cookie cookie) 
367         throws MalformedCookieException {
368             
369         LOG.trace("enter CookieSpecBase.validate("
370             + "String, port, path, boolean, Cookie)");
371         if (host == null) {
372             throw new IllegalArgumentException(
373                 "Host of origin may not be null");
374         }
375         if (host.trim().equals("")) {
376             throw new IllegalArgumentException(
377                 "Host of origin may not be blank");
378         }
379         if (port < 0) {
380             throw new IllegalArgumentException("Invalid port: " + port);
381         }
382         if (path == null) {
383             throw new IllegalArgumentException(
384                 "Path of origin may not be null.");
385         }
386         if (path.trim().equals("")) {
387             path = PATH_DELIM;
388         }
389         host = host.toLowerCase();
390         // check version
391         if (cookie.getVersion() < 0) {
392             throw new MalformedCookieException ("Illegal version number " 
393                 + cookie.getValue());
394         }
395 
396         // security check... we musn't allow the server to give us an
397         // invalid domain scope
398 
399         // Validate the cookies domain attribute.  NOTE:  Domains without 
400         // any dots are allowed to support hosts on private LANs that don't 
401         // have DNS names.  Since they have no dots, to domain-match the 
402         // request-host and domain must be identical for the cookie to sent 
403         // back to the origin-server.
404         if (host.indexOf(".") >= 0) {
405             // Not required to have at least two dots.  RFC 2965.
406             // A Set-Cookie2 with Domain=ajax.com will be accepted.
407 
408             // domain must match host
409             if (!host.endsWith(cookie.getDomain())) {
410                 String s = cookie.getDomain();
411                 if (s.startsWith(".")) {
412                     s = s.substring(1, s.length());
413                 }
414                 if (!host.equals(s)) { 
415                     throw new MalformedCookieException(
416                         "Illegal domain attribute \"" + cookie.getDomain() 
417                         + "\". Domain of origin: \"" + host + "\"");
418                 }
419             }
420         } else {
421             if (!host.equals(cookie.getDomain())) {
422                 throw new MalformedCookieException(
423                     "Illegal domain attribute \"" + cookie.getDomain() 
424                     + "\". Domain of origin: \"" + host + "\"");
425             }
426         }
427 
428         // another security check... we musn't allow the server to give us a
429         // cookie that doesn't match this path
430 
431         if (!path.startsWith(cookie.getPath())) {
432             throw new MalformedCookieException(
433                 "Illegal path attribute \"" + cookie.getPath() 
434                 + "\". Path of origin: \"" + path + "\"");
435         }
436     }
437 
438 
439     /**
440      * Return <tt>true</tt> if the cookie should be submitted with a request
441      * with given attributes, <tt>false</tt> otherwise.
442      * @param host the host to which the request is being submitted
443      * @param port the port to which the request is being submitted (ignored)
444      * @param path the path to which the request is being submitted
445      * @param secure <tt>true</tt> if the request is using a secure connection
446      * @param cookie {@link Cookie} to be matched
447      * @return true if the cookie matches the criterium
448      */
449 
450     public boolean match(String host, int port, String path, 
451         boolean secure, final Cookie cookie) {
452             
453         LOG.trace("enter CookieSpecBase.match("
454             + "String, int, String, boolean, Cookie");
455             
456         if (host == null) {
457             throw new IllegalArgumentException(
458                 "Host of origin may not be null");
459         }
460         if (host.trim().equals("")) {
461             throw new IllegalArgumentException(
462                 "Host of origin may not be blank");
463         }
464         if (port < 0) {
465             throw new IllegalArgumentException("Invalid port: " + port);
466         }
467         if (path == null) {
468             throw new IllegalArgumentException(
469                 "Path of origin may not be null.");
470         }
471         if (cookie == null) {
472             throw new IllegalArgumentException("Cookie may not be null");
473         }
474         if (path.trim().equals("")) {
475             path = PATH_DELIM;
476         }
477         host = host.toLowerCase();
478         if (cookie.getDomain() == null) {
479             LOG.warn("Invalid cookie state: domain not specified");
480             return false;
481         }
482         if (cookie.getPath() == null) {
483             LOG.warn("Invalid cookie state: path not specified");
484             return false;
485         }
486         
487         return
488             // only add the cookie if it hasn't yet expired 
489             (cookie.getExpiryDate() == null 
490                 || cookie.getExpiryDate().after(new Date()))
491             // and the domain pattern matches 
492             && (domainMatch(host, cookie.getDomain()))
493             // and the path is null or matching
494             && (pathMatch(path, cookie.getPath()))
495             // and if the secure flag is set, only if the request is 
496             // actually secure 
497             && (cookie.getSecure() ? secure : true);      
498     }
499 
500     /**
501      * Performs domain-match as implemented in common browsers.
502      * @param host The target host.
503      * @param domain The cookie domain attribute.
504      * @return true if the specified host matches the given domain.
505      */
506     public boolean domainMatch(final String host, String domain) {
507         if (host.equals(domain)) {
508             return true;
509         }
510         if (!domain.startsWith(".")) {
511             domain = "." + domain;
512         }
513         return host.endsWith(domain) || host.equals(domain.substring(1));
514     }
515 
516     /**
517      * Performs path-match as implemented in common browsers.
518      * @param path The target path.
519      * @param topmostPath The cookie path attribute.
520      * @return true if the paths match
521      */
522     public boolean pathMatch(final String path, final String topmostPath) {
523         boolean match = path.startsWith (topmostPath);
524         // if there is a match and these values are not exactly the same we have
525         // to make sure we're not matcing "/foobar" and "/foo"
526         if (match && path.length() != topmostPath.length()) {
527             if (!topmostPath.endsWith(PATH_DELIM)) {
528                 match = (path.charAt(topmostPath.length()) == PATH_DELIM_CHAR);
529             }
530         }
531         return match;
532     }
533 
534     /**
535      * Return an array of {@link Cookie}s that should be submitted with a
536      * request with given attributes, <tt>false</tt> otherwise.
537      * @param host the host to which the request is being submitted
538      * @param port the port to which the request is being submitted (currently
539      * ignored)
540      * @param path the path to which the request is being submitted
541      * @param secure <tt>true</tt> if the request is using a secure protocol
542      * @param cookies an array of <tt>Cookie</tt>s to be matched
543      * @return an array of <tt>Cookie</tt>s matching the criterium
544      */
545 
546     public Cookie[] match(String host, int port, String path, 
547         boolean secure, final Cookie cookies[]) {
548             
549         LOG.trace("enter CookieSpecBase.match("
550             + "String, int, String, boolean, Cookie[])");
551 
552         if (cookies == null) {
553             return null;
554         }
555         List matching = new LinkedList();
556         for (int i = 0; i < cookies.length; i++) {
557             if (match(host, port, path, secure, cookies[i])) {
558                 addInPathOrder(matching, cookies[i]);
559             }
560         }
561         return (Cookie[]) matching.toArray(new Cookie[matching.size()]);
562     }
563 
564 
565     /**
566      * Adds the given cookie into the given list in descending path order. That
567      * is, more specific path to least specific paths.  This may not be the
568      * fastest algorythm, but it'll work OK for the small number of cookies
569      * we're generally dealing with.
570      *
571      * @param list - the list to add the cookie to
572      * @param addCookie - the Cookie to add to list
573      */
574     private static void addInPathOrder(List list, Cookie addCookie) {
575         int i = 0;
576 
577         for (i = 0; i < list.size(); i++) {
578             Cookie c = (Cookie) list.get(i);
579             if (addCookie.compare(addCookie, c) > 0) {
580                 break;
581             }
582         }
583         list.add(i, addCookie);
584     }
585 
586     /**
587      * Return a string suitable for sending in a <tt>"Cookie"</tt> header
588      * @param cookie a {@link Cookie} to be formatted as string
589      * @return a string suitable for sending in a <tt>"Cookie"</tt> header.
590      */
591     public String formatCookie(Cookie cookie) {
592         LOG.trace("enter CookieSpecBase.formatCookie(Cookie)");
593         if (cookie == null) {
594             throw new IllegalArgumentException("Cookie may not be null");
595         }
596         StringBuffer buf = new StringBuffer();
597         buf.append(cookie.getName());
598         buf.append("=");
599         String s = cookie.getValue();
600         if (s != null) {
601             buf.append(s);
602         }
603         return buf.toString();
604     }
605 
606     /**
607      * Create a <tt>"Cookie"</tt> header value containing all {@link Cookie}s in
608      * <i>cookies</i> suitable for sending in a <tt>"Cookie"</tt> header
609      * @param cookies an array of {@link Cookie}s to be formatted
610      * @return a string suitable for sending in a Cookie header.
611      * @throws IllegalArgumentException if an input parameter is illegal
612      */
613 
614     public String formatCookies(Cookie[] cookies)
615       throws IllegalArgumentException {
616         LOG.trace("enter CookieSpecBase.formatCookies(Cookie[])");
617         if (cookies == null) {
618             throw new IllegalArgumentException("Cookie array may not be null");
619         }
620         if (cookies.length == 0) {
621             throw new IllegalArgumentException("Cookie array may not be empty");
622         }
623 
624         StringBuffer buffer = new StringBuffer();
625         for (int i = 0; i < cookies.length; i++) {
626             if (i > 0) {
627                 buffer.append("; ");
628             }
629             buffer.append(formatCookie(cookies[i]));
630         }
631         return buffer.toString();
632     }
633 
634 
635     /**
636      * Create a <tt>"Cookie"</tt> {@link Header} containing all {@link Cookie}s
637      * in <i>cookies</i>.
638      * @param cookies an array of {@link Cookie}s to be formatted as a <tt>"
639      * Cookie"</tt> header
640      * @return a <tt>"Cookie"</tt> {@link Header}.
641      */
642     public Header formatCookieHeader(Cookie[] cookies) {
643         LOG.trace("enter CookieSpecBase.formatCookieHeader(Cookie[])");
644         return new Header("Cookie", formatCookies(cookies));
645     }
646 
647 
648     /**
649      * Create a <tt>"Cookie"</tt> {@link Header} containing the {@link Cookie}.
650      * @param cookie <tt>Cookie</tt>s to be formatted as a <tt>Cookie</tt>
651      * header
652      * @return a Cookie header.
653      */
654     public Header formatCookieHeader(Cookie cookie) {
655         LOG.trace("enter CookieSpecBase.formatCookieHeader(Cookie)");
656         return new Header("Cookie", formatCookie(cookie));
657     }
658 
659 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/CookieVersionSupport.html100644 0 0 11740 10661532627 30436 0ustar 0 0 CookieVersionSupport xref

1   /*
2    * $Header: $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.cookie;
32  
33  import org.apache.commons.httpclient.Header;
34  
35  /**
36   * Defines cookie specification specific capabilities
37   * 
38   * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
39   *
40   * @since 3.1
41   */
42  public interface CookieVersionSupport {    
43  
44      int getVersion();
45      
46      Header getVersionHeader();
47  
48  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.html100644 0 0 33664 10661532627 27646 0ustar 0 0 IgnoreCookiesSpec xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.java,v 1.6 2004/09/14 20:11:31 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */ 
30  
31  package org.apache.commons.httpclient.cookie;
32  
33  import java.util.Collection;
34  
35  import org.apache.commons.httpclient.Cookie;
36  import org.apache.commons.httpclient.Header;
37  import org.apache.commons.httpclient.NameValuePair;
38  
39  /**
40   * A cookie spec that does nothing.  Cookies are neither parsed, formatted nor matched.
41   * It can be used to effectively disable cookies altogether. 
42   * 
43   * @since 3.0
44   */
45  public class IgnoreCookiesSpec implements CookieSpec {
46  
47      /**
48       * 
49       */
50      public IgnoreCookiesSpec() {
51          super();
52      }
53  
54      /**
55       * Returns an empty {@link Cookie cookie} array.  All parameters are ignored.
56       */
57      public Cookie[] parse(String host, int port, String path, boolean secure, String header)
58          throws MalformedCookieException {
59          return new Cookie[0];
60      }
61  
62      /**
63       * @return <code>null</code>
64       */
65  	public Collection getValidDateFormats() {
66  		return null;
67  	}
68  	
69      /**
70       * Does nothing.
71       */
72  	public void setValidDateFormats(Collection datepatterns) {
73  	}
74  	
75      /**
76       * @return <code>null</code>
77       */
78      public String formatCookie(Cookie cookie) {
79          return null;
80      }
81  
82      /**
83       * @return <code>null</code>
84       */
85      public Header formatCookieHeader(Cookie cookie) throws IllegalArgumentException {
86          return null;
87      }
88  
89      /**
90       * @return <code>null</code>
91       */
92      public Header formatCookieHeader(Cookie[] cookies) throws IllegalArgumentException {
93          return null;
94      }
95  
96      /**
97       * @return <code>null</code>
98       */
99      public String formatCookies(Cookie[] cookies) throws IllegalArgumentException {
100         return null;
101     }
102 
103     /**
104      * @return <code>false</code>
105      */
106     public boolean match(String host, int port, String path, boolean secure, Cookie cookie) {
107         return false;
108     }
109 
110     /**
111      * Returns an empty {@link Cookie cookie} array.  All parameters are ignored.
112      */
113     public Cookie[] match(String host, int port, String path, boolean secure, Cookie[] cookies) {
114         return new Cookie[0];
115     }
116 
117     /**
118      * Returns an empty {@link Cookie cookie} array.  All parameters are ignored.
119      */
120     public Cookie[] parse(String host, int port, String path, boolean secure, Header header)
121         throws MalformedCookieException, IllegalArgumentException {
122         return new Cookie[0];
123     }
124 
125     /**
126      * Does nothing.
127      */
128     public void parseAttribute(NameValuePair attribute, Cookie cookie)
129         throws MalformedCookieException, IllegalArgumentException {
130     }
131 
132     /**
133      * Does nothing.
134      */
135     public void validate(String host, int port, String path, boolean secure, Cookie cookie)
136         throws MalformedCookieException, IllegalArgumentException {
137     }
138 
139     /**
140      * @return <code>false</code>
141      */
142     public boolean domainMatch(final String host, final String domain) {
143         return false;
144     }
145 
146     /**
147      * @return <code>false</code>
148      */
149     public boolean pathMatch(final String path, final String topmostPath) {
150         return false;
151     }
152 
153 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/MalformedCookieException.html100644 0 0 16623 10661532627 31206 0ustar 0 0 MalformedCookieException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/MalformedCookieException.java,v 1.8 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.cookie;
32  
33  import org.apache.commons.httpclient.ProtocolException;
34  
35  /**
36   * Signals that a cookie is in some way invalid or illegal in a given
37   * context
38   *
39   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
40   * 
41   * @since 2.0
42   */
43  public class MalformedCookieException extends ProtocolException {
44  
45      /**
46       * Creates a new MalformedCookieException with a <tt>null</tt> detail message.
47       */
48      public MalformedCookieException() {
49          super();
50      }
51       
52      /** 
53       * Creates a new MalformedCookieException with a specified message string.
54       * 
55       * @param message The exception detail message
56       */
57      public MalformedCookieException(String message) {
58          super(message);
59      }
60  
61      /**
62       * Creates a new MalformedCookieException with the specified detail message and cause.
63       * 
64       * @param message the exception detail message
65       * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
66       * if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
67       * 
68       * @since 3.0
69       */
70      public MalformedCookieException(String message, Throwable cause) {
71          super(message, cause);
72      }
73  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/NetscapeDraftSpec.html100644 0 0 64644 10661532627 27633 0ustar 0 0 NetscapeDraftSpec xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/NetscapeDraftSpec.java,v 1.11 2004/05/13 04:02:00 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.cookie;
32  
33  import java.util.StringTokenizer;
34  import java.util.Date;
35  import java.util.Locale;   
36  import java.text.DateFormat; 
37  import java.text.SimpleDateFormat;  
38  import java.text.ParseException; 
39  
40  import org.apache.commons.httpclient.HeaderElement;
41  import org.apache.commons.httpclient.NameValuePair;
42  import org.apache.commons.httpclient.Cookie;
43  
44  /**
45   * <P>Netscape cookie draft specific cookie management functions
46   *
47   * @author  B.C. Holmes
48   * @author <a href="mailto:jericho@thinkfree.com">Park, Sung-Gu</a>
49   * @author <a href="mailto:dsale@us.britannica.com">Doug Sale</a>
50   * @author Rod Waldhoff
51   * @author dIon Gillard
52   * @author Sean C. Sullivan
53   * @author <a href="mailto:JEvans@Cyveillance.com">John Evans</a>
54   * @author Marc A. Saegesser
55   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
56   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
57   * 
58   * @since 2.0 
59   */
60  
61  public class NetscapeDraftSpec extends CookieSpecBase {
62  
63      /** Default constructor */
64      public NetscapeDraftSpec() {
65          super();
66      }
67  
68      /**
69        * Parses the Set-Cookie value into an array of <tt>Cookie</tt>s.
70        *
71        * <p>Syntax of the Set-Cookie HTTP Response Header:</p>
72        * 
73        * <p>This is the format a CGI script would use to add to 
74        * the HTTP headers a new piece of data which is to be stored by 
75        * the client for later retrieval.</p>
76        *  
77        * <PRE>
78        *  Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
79        * </PRE>
80        *
81        * <p>Please note that Netscape draft specification does not fully 
82        * conform to the HTTP header format. Netscape draft does not specify 
83        * whether multiple cookies may be sent in one header. Hence, comma 
84        * character may be present in unquoted cookie value or unquoted 
85        * parameter value.</p>
86        * 
87        * @link http://wp.netscape.com/newsref/std/cookie_spec.html
88        * 
89        * @param host the host from which the <tt>Set-Cookie</tt> value was
90        * received
91        * @param port the port from which the <tt>Set-Cookie</tt> value was
92        * received
93        * @param path the path from which the <tt>Set-Cookie</tt> value was
94        * received
95        * @param secure <tt>true</tt> when the <tt>Set-Cookie</tt> value was
96        * received over secure conection
97        * @param header the <tt>Set-Cookie</tt> received from the server
98        * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie value
99        * @throws MalformedCookieException if an exception occurs during parsing
100       * 
101       * @since 3.0
102       */
103     public Cookie[] parse(String host, int port, String path, 
104         boolean secure, final String header) 
105         throws MalformedCookieException {
106             
107         LOG.trace("enter NetscapeDraftSpec.parse(String, port, path, boolean, Header)");
108 
109         if (host == null) {
110             throw new IllegalArgumentException("Host of origin may not be null");
111         }
112         if (host.trim().equals("")) {
113             throw new IllegalArgumentException("Host of origin may not be blank");
114         }
115         if (port < 0) {
116             throw new IllegalArgumentException("Invalid port: " + port);
117         }
118         if (path == null) {
119             throw new IllegalArgumentException("Path of origin may not be null.");
120         }
121         if (header == null) {
122             throw new IllegalArgumentException("Header may not be null.");
123         }
124 
125         if (path.trim().equals("")) {
126             path = PATH_DELIM;
127         }
128         host = host.toLowerCase();
129 
130         String defaultPath = path;    
131         int lastSlashIndex = defaultPath.lastIndexOf(PATH_DELIM);
132         if (lastSlashIndex >= 0) {
133             if (lastSlashIndex == 0) {
134                 //Do not remove the very first slash
135                 lastSlashIndex = 1;
136             }
137             defaultPath = defaultPath.substring(0, lastSlashIndex);
138         }
139         HeaderElement headerelement = new HeaderElement(header.toCharArray());
140         Cookie cookie = new Cookie(host,
141                        headerelement.getName(),
142                        headerelement.getValue(),
143                        defaultPath, 
144                        null,
145                        false);
146         // cycle through the parameters
147         NameValuePair[] parameters = headerelement.getParameters();
148         // could be null. In case only a header element and no parameters.
149         if (parameters != null) {
150             for (int j = 0; j < parameters.length; j++) {
151                 parseAttribute(parameters[j], cookie);
152             }
153         }
154         return new Cookie[] {cookie};
155     }
156 
157 
158     /**
159       * Parse the cookie attribute and update the corresponsing {@link Cookie}
160       * properties as defined by the Netscape draft specification
161       *
162       * @param attribute {@link NameValuePair} cookie attribute from the
163       * <tt>Set- Cookie</tt>
164       * @param cookie {@link Cookie} to be updated
165       * @throws MalformedCookieException if an exception occurs during parsing
166       */
167     public void parseAttribute(
168         final NameValuePair attribute, final Cookie cookie)
169         throws MalformedCookieException {
170             
171         if (attribute == null) {
172             throw new IllegalArgumentException("Attribute may not be null.");
173         }
174         if (cookie == null) {
175             throw new IllegalArgumentException("Cookie may not be null.");
176         }
177         final String paramName = attribute.getName().toLowerCase();
178         final String paramValue = attribute.getValue();
179 
180         if (paramName.equals("expires")) {
181 
182             if (paramValue == null) {
183                 throw new MalformedCookieException(
184                     "Missing value for expires attribute");
185             }
186             try {
187                 DateFormat expiryFormat = new SimpleDateFormat(
188                     "EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US);
189                 Date date = expiryFormat.parse(paramValue);
190                 cookie.setExpiryDate(date);
191             } catch (ParseException e) {
192                 throw new MalformedCookieException("Invalid expires "
193                     + "attribute: " + e.getMessage());
194             }
195         } else {
196             super.parseAttribute(attribute, cookie);
197         }
198     }
199 
200     /**
201      * Performs domain-match as described in the Netscape draft.
202      * @param host The target host.
203      * @param domain The cookie domain attribute.
204      * @return true if the specified host matches the given domain.
205      */
206     public boolean domainMatch(final String host, final String domain) {
207         return host.endsWith(domain);
208     }
209 
210     /**
211       * Performs Netscape draft compliant {@link Cookie} validation
212       *
213       * @param host the host from which the {@link Cookie} was received
214       * @param port the port from which the {@link Cookie} was received
215       * @param path the path from which the {@link Cookie} was received
216       * @param secure <tt>true</tt> when the {@link Cookie} was received 
217       * using a secure connection
218       * @param cookie The cookie to validate.
219       * @throws MalformedCookieException if an exception occurs during
220       * validation
221       */
222     public void validate(String host, int port, String path, 
223         boolean secure, final Cookie cookie) 
224         throws MalformedCookieException {
225             
226         LOG.trace("enterNetscapeDraftCookieProcessor "
227             + "RCF2109CookieProcessor.validate(Cookie)");
228         // Perform generic validation
229         super.validate(host, port, path, secure, cookie);
230         // Perform Netscape Cookie draft specific validation
231         if (host.indexOf(".") >= 0) {
232             int domainParts = new StringTokenizer(cookie.getDomain(), ".")
233                 .countTokens();
234 
235             if (isSpecialDomain(cookie.getDomain())) {
236                 if (domainParts < 2) {
237                     throw new MalformedCookieException("Domain attribute \""
238                         + cookie.getDomain() 
239                         + "\" violates the Netscape cookie specification for "
240                         + "special domains");
241                 }
242             } else {
243                 if (domainParts < 3) {
244                     throw new MalformedCookieException("Domain attribute \""
245                         + cookie.getDomain() 
246                         + "\" violates the Netscape cookie specification");
247                 }            
248             }
249         }
250     }
251     
252     /**
253      * Checks if the given domain is in one of the seven special
254      * top level domains defined by the Netscape cookie specification.
255      * @param domain The domain.
256      * @return True if the specified domain is "special"
257      */
258     private static boolean isSpecialDomain(final String domain) {
259         final String ucDomain = domain.toUpperCase();
260         if (ucDomain.endsWith(".COM") 
261            || ucDomain.endsWith(".EDU")
262            || ucDomain.endsWith(".NET")
263            || ucDomain.endsWith(".GOV")
264            || ucDomain.endsWith(".MIL")
265            || ucDomain.endsWith(".ORG")
266            || ucDomain.endsWith(".INT")) {
267             return true;
268         }
269         return false;
270     }
271 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/RFC2109Spec.html100644 0 0 72232 10661532627 26026 0ustar 0 0 RFC2109Spec xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/RFC2109Spec.java,v 1.21 2004/06/05 16:49:20 olegk Exp $
3    * $Revision: 507134 $
4    * $Date: 2007-02-13 19:18:05 +0100 (Tue, 13 Feb 2007) $
5    * 
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.cookie;
32  
33  import org.apache.commons.httpclient.NameValuePair;
34  import org.apache.commons.httpclient.Cookie;
35  import org.apache.commons.httpclient.util.ParameterFormatter;
36  
37  /**
38   * <p>RFC 2109 specific cookie management functions
39   *
40   * @author  B.C. Holmes
41   * @author <a href="mailto:jericho@thinkfree.com">Park, Sung-Gu</a>
42   * @author <a href="mailto:dsale@us.britannica.com">Doug Sale</a>
43   * @author Rod Waldhoff
44   * @author dIon Gillard
45   * @author Sean C. Sullivan
46   * @author <a href="mailto:JEvans@Cyveillance.com">John Evans</a>
47   * @author Marc A. Saegesser
48   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
49   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
50   * 
51   * @since 2.0 
52   */
53  
54  public class RFC2109Spec extends CookieSpecBase {
55  
56      private final ParameterFormatter formatter;
57  
58      /**
59       * Cookie Response Header  name for cookies processed
60       * by this spec.
61       */
62      public final static String SET_COOKIE_KEY = "set-cookie";
63  
64      /** Default constructor */
65      public RFC2109Spec() {
66          super();
67          this.formatter = new ParameterFormatter();
68          this.formatter.setAlwaysUseQuotes(true);
69      }
70  
71      /**
72        * Parse RFC 2109 specific cookie attribute and update the corresponsing
73        * {@link Cookie} properties.
74        *
75        * @param attribute {@link NameValuePair} cookie attribute from the
76        * <tt>Set- Cookie</tt>
77        * @param cookie {@link Cookie} to be updated
78        * @throws MalformedCookieException if an exception occurs during parsing
79        */
80      public void parseAttribute(
81          final NameValuePair attribute, final Cookie cookie)
82          throws MalformedCookieException {
83            
84          if (attribute == null) {
85              throw new IllegalArgumentException("Attribute may not be null.");
86          }
87          if (cookie == null) {
88              throw new IllegalArgumentException("Cookie may not be null.");
89          }
90          final String paramName = attribute.getName().toLowerCase();
91          final String paramValue = attribute.getValue();
92  
93          if (paramName.equals("path")) {
94              if (paramValue == null) {
95                  throw new MalformedCookieException(
96                      "Missing value for path attribute");
97              }
98              if (paramValue.trim().equals("")) {
99                  throw new MalformedCookieException(
100                     "Blank value for path attribute");
101             }
102             cookie.setPath(paramValue);
103             cookie.setPathAttributeSpecified(true);
104         } else if (paramName.equals("version")) {
105 
106             if (paramValue == null) {
107                 throw new MalformedCookieException(
108                     "Missing value for version attribute");
109             }
110             try {
111                cookie.setVersion(Integer.parseInt(paramValue));
112             } catch (NumberFormatException e) {
113                 throw new MalformedCookieException("Invalid version: " 
114                     + e.getMessage());
115             }
116 
117         } else {
118             super.parseAttribute(attribute, cookie);
119         }
120     }
121 
122     /**
123       * Performs RFC 2109 compliant {@link Cookie} validation
124       *
125       * @param host the host from which the {@link Cookie} was received
126       * @param port the port from which the {@link Cookie} was received
127       * @param path the path from which the {@link Cookie} was received
128       * @param secure <tt>true</tt> when the {@link Cookie} was received using a
129       * secure connection
130       * @param cookie The cookie to validate
131       * @throws MalformedCookieException if an exception occurs during
132       * validation
133       */
134     public void validate(String host, int port, String path, 
135         boolean secure, final Cookie cookie) throws MalformedCookieException {
136             
137         LOG.trace("enter RFC2109Spec.validate(String, int, String, "
138             + "boolean, Cookie)");
139             
140         // Perform generic validation
141         super.validate(host, port, path, secure, cookie);
142         // Perform RFC 2109 specific validation
143         
144         if (cookie.getName().indexOf(' ') != -1) {
145             throw new MalformedCookieException("Cookie name may not contain blanks");
146         }
147         if (cookie.getName().startsWith("$")) {
148             throw new MalformedCookieException("Cookie name may not start with $");
149         }
150         
151         if (cookie.isDomainAttributeSpecified() 
152             && (!cookie.getDomain().equals(host))) {
153                 
154             // domain must start with dot
155             if (!cookie.getDomain().startsWith(".")) {
156                 throw new MalformedCookieException("Domain attribute \"" 
157                     + cookie.getDomain() 
158                     + "\" violates RFC 2109: domain must start with a dot");
159             }
160             // domain must have at least one embedded dot
161             int dotIndex = cookie.getDomain().indexOf('.', 1);
162             if (dotIndex < 0 || dotIndex == cookie.getDomain().length() - 1) {
163                 throw new MalformedCookieException("Domain attribute \"" 
164                     + cookie.getDomain() 
165                     + "\" violates RFC 2109: domain must contain an embedded dot");
166             }
167             host = host.toLowerCase();
168             if (!host.endsWith(cookie.getDomain())) {
169                 throw new MalformedCookieException(
170                     "Illegal domain attribute \"" + cookie.getDomain() 
171                     + "\". Domain of origin: \"" + host + "\"");
172             }
173             // host minus domain may not contain any dots
174             String hostWithoutDomain = host.substring(0, host.length() 
175                 - cookie.getDomain().length());
176             if (hostWithoutDomain.indexOf('.') != -1) {
177                 throw new MalformedCookieException("Domain attribute \"" 
178                     + cookie.getDomain() 
179                     + "\" violates RFC 2109: host minus domain may not contain any dots");
180             }
181         }
182     }
183 
184     /**
185      * Performs domain-match as defined by the RFC2109.
186      * @param host The target host.
187      * @param domain The cookie domain attribute.
188      * @return true if the specified host matches the given domain.
189      * 
190      * @since 3.0
191      */
192     public boolean domainMatch(String host, String domain) {
193         boolean match = host.equals(domain) 
194             || (domain.startsWith(".") && host.endsWith(domain));
195 
196         return match;
197     }
198 
199     /**
200      * Return a name/value string suitable for sending in a <tt>"Cookie"</tt>
201      * header as defined in RFC 2109 for backward compatibility with cookie
202      * version 0
203      * @param buffer The string buffer to use for output
204      * @param param The parameter.
205      * @param version The cookie version 
206      */
207     private void formatParam(final StringBuffer buffer, final NameValuePair param, int version) {
208         if (version < 1) {
209             buffer.append(param.getName());
210             buffer.append("=");
211             if (param.getValue() != null) {
212                 buffer.append(param.getValue());   
213             }
214         } else {
215             this.formatter.format(buffer, param);
216         }
217     }
218 
219     /**
220      * Return a string suitable for sending in a <tt>"Cookie"</tt> header 
221      * as defined in RFC 2109 for backward compatibility with cookie version 0
222      * @param buffer The string buffer to use for output
223      * @param cookie The {@link Cookie} to be formatted as string
224      * @param version The version to use.
225      */
226     private void formatCookieAsVer(final StringBuffer buffer, final Cookie cookie, int version) {
227         String value = cookie.getValue();
228         if (value == null) {
229             value = "";
230         }
231         formatParam(buffer, new NameValuePair(cookie.getName(), value), version);
232         if ((cookie.getPath() != null) && cookie.isPathAttributeSpecified()) {
233           buffer.append("; ");
234           formatParam(buffer, new NameValuePair("$Path", cookie.getPath()), version);
235         }
236         if ((cookie.getDomain() != null) 
237             && cookie.isDomainAttributeSpecified()) {
238             buffer.append("; ");
239             formatParam(buffer, new NameValuePair("$Domain", cookie.getDomain()), version);
240         }
241     }
242 
243     /**
244      * Return a string suitable for sending in a <tt>"Cookie"</tt> header as
245      * defined in RFC 2109
246      * @param cookie a {@link Cookie} to be formatted as string
247      * @return a string suitable for sending in a <tt>"Cookie"</tt> header.
248      */
249     public String formatCookie(Cookie cookie) {
250         LOG.trace("enter RFC2109Spec.formatCookie(Cookie)");
251         if (cookie == null) {
252             throw new IllegalArgumentException("Cookie may not be null");
253         }
254         int version = cookie.getVersion();
255         StringBuffer buffer = new StringBuffer();
256         formatParam(buffer, 
257                 new NameValuePair("$Version", Integer.toString(version)), 
258                 version);
259         buffer.append("; ");
260         formatCookieAsVer(buffer, cookie, version);
261         return buffer.toString();
262     }
263 
264     /**
265      * Create a RFC 2109 compliant <tt>"Cookie"</tt> header value containing all
266      * {@link Cookie}s in <i>cookies</i> suitable for sending in a <tt>"Cookie"
267      * </tt> header
268      * @param cookies an array of {@link Cookie}s to be formatted
269      * @return a string suitable for sending in a Cookie header.
270      */
271     public String formatCookies(Cookie[] cookies) {
272         LOG.trace("enter RFC2109Spec.formatCookieHeader(Cookie[])");
273         int version = Integer.MAX_VALUE;
274         // Pick the lowerest common denominator
275         for (int i = 0; i < cookies.length; i++) {
276             Cookie cookie = cookies[i];
277             if (cookie.getVersion() < version) {
278                 version = cookie.getVersion();
279             }
280         }
281         final StringBuffer buffer = new StringBuffer();
282         formatParam(buffer, 
283                 new NameValuePair("$Version", Integer.toString(version)), 
284                 version);
285         for (int i = 0; i < cookies.length; i++) {
286             buffer.append("; ");
287             formatCookieAsVer(buffer, cookies[i], version);
288         }
289         return buffer.toString();
290     }
291 
292 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/RFC2965Spec.html100644 0 0 336613 10661532627 26066 0ustar 0 0 RFC2965Spec xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/cookie/RFC2965Spec.java $
3    * $Revision: 507134 $
4    * $Date: 2007-02-13 19:18:05 +0100 (Tue, 13 Feb 2007) $
5    * 
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.cookie;
32  
33  import java.util.ArrayList;
34  import java.util.Arrays;
35  import java.util.Comparator;
36  import java.util.Date;
37  import java.util.HashMap;
38  import java.util.Iterator;
39  import java.util.LinkedList;
40  import java.util.List;
41  import java.util.Map;
42  import java.util.StringTokenizer;
43  
44  import org.apache.commons.httpclient.Cookie;
45  import org.apache.commons.httpclient.Header;
46  import org.apache.commons.httpclient.HeaderElement;
47  import org.apache.commons.httpclient.NameValuePair;
48  import org.apache.commons.httpclient.util.ParameterFormatter;
49  
50  /**
51   * <p>RFC 2965 specific cookie management functions.</p>
52   * 
53   * @author jain.samit@gmail.com (Samit Jain)
54   *
55   * @since 3.1
56   */
57  public class RFC2965Spec extends CookieSpecBase implements CookieVersionSupport {
58  
59      private static final Comparator PATH_COMPOARATOR = new CookiePathComparator();
60      
61      /**
62      * Cookie Response Header  name for cookies processed
63      * by this spec.
64      */
65      public final static String SET_COOKIE2_KEY = "set-cookie2";
66      
67      /**
68      * used for formatting RFC 2956 style cookies
69      */
70      private final ParameterFormatter formatter;
71       
72      /**
73       * Stores the list of attribute handlers
74       */
75      private final List attribHandlerList;
76      
77      /**
78      * Stores attribute name -> attribute handler mappings
79      */
80      private final Map attribHandlerMap;
81  
82      /**
83       * Fallback cookie spec (RFC 2109)
84       */
85      private final CookieSpec rfc2109;
86      
87      /** 
88       * Default constructor 
89       * */
90      public RFC2965Spec() {
91          super();
92          this.formatter = new ParameterFormatter();
93          this.formatter.setAlwaysUseQuotes(true);
94          this.attribHandlerMap = new HashMap(10);        
95          this.attribHandlerList = new ArrayList(10);
96          this.rfc2109 = new RFC2109Spec();
97          
98          registerAttribHandler(Cookie2.PATH, new Cookie2PathAttributeHandler());
99          registerAttribHandler(Cookie2.DOMAIN, new Cookie2DomainAttributeHandler());
100         registerAttribHandler(Cookie2.PORT, new Cookie2PortAttributeHandler());
101         registerAttribHandler(Cookie2.MAXAGE, new Cookie2MaxageAttributeHandler());
102         registerAttribHandler(Cookie2.SECURE, new CookieSecureAttributeHandler());
103         registerAttribHandler(Cookie2.COMMENT, new CookieCommentAttributeHandler());
104         registerAttribHandler(Cookie2.COMMENTURL, new CookieCommentUrlAttributeHandler());
105         registerAttribHandler(Cookie2.DISCARD, new CookieDiscardAttributeHandler());
106         registerAttribHandler(Cookie2.VERSION, new Cookie2VersionAttributeHandler());
107     }
108 
109     protected void registerAttribHandler(
110             final String name, final CookieAttributeHandler handler) {
111         if (name == null) {
112             throw new IllegalArgumentException("Attribute name may not be null");
113         }
114         if (handler == null) {
115             throw new IllegalArgumentException("Attribute handler may not be null");
116         }
117         if (!this.attribHandlerList.contains(handler)) {
118             this.attribHandlerList.add(handler);
119         }
120         this.attribHandlerMap.put(name, handler);
121     }
122     
123     /**
124      * Finds an attribute handler {@link CookieAttributeHandler} for the
125      * given attribute. Returns <tt>null</tt> if no attribute handler is
126      * found for the specified attribute.
127      *
128      * @param name attribute name. e.g. Domain, Path, etc.
129      * @return an attribute handler or <tt>null</tt>
130      */
131     protected CookieAttributeHandler findAttribHandler(final String name) {
132         return (CookieAttributeHandler) this.attribHandlerMap.get(name);
133     }
134     
135     /**
136      * Gets attribute handler {@link CookieAttributeHandler} for the
137      * given attribute.
138      *
139      * @param name attribute name. e.g. Domain, Path, etc.
140      * @throws IllegalStateException if handler not found for the
141      *          specified attribute.
142      */
143     protected CookieAttributeHandler getAttribHandler(final String name) {
144         CookieAttributeHandler handler = findAttribHandler(name);
145         if (handler == null) {
146             throw new IllegalStateException("Handler not registered for " +
147                                             name + " attribute.");
148         } else {
149             return handler;
150         }
151     }
152 
153     protected Iterator getAttribHandlerIterator() {
154         return this.attribHandlerList.iterator();
155     }
156     
157     /**
158      * Parses the Set-Cookie2 value into an array of <tt>Cookie</tt>s.
159      *
160      * <P>The syntax for the Set-Cookie2 response header is:
161      *
162      * <PRE>
163      * set-cookie      =    "Set-Cookie2:" cookies
164      * cookies         =    1#cookie
165      * cookie          =    NAME "=" VALUE * (";" cookie-av)
166      * NAME            =    attr
167      * VALUE           =    value
168      * cookie-av       =    "Comment" "=" value
169      *                 |    "CommentURL" "=" <"> http_URL <">
170      *                 |    "Discard"
171      *                 |    "Domain" "=" value
172      *                 |    "Max-Age" "=" value
173      *                 |    "Path" "=" value
174      *                 |    "Port" [ "=" <"> portlist <"> ]
175      *                 |    "Secure"
176      *                 |    "Version" "=" 1*DIGIT
177      * portlist        =       1#portnum
178      * portnum         =       1*DIGIT
179      * </PRE>
180      *
181      * @param host the host from which the <tt>Set-Cookie2</tt> value was
182      * received
183      * @param port the port from which the <tt>Set-Cookie2</tt> value was
184      * received
185      * @param path the path from which the <tt>Set-Cookie2</tt> value was
186      * received
187      * @param secure <tt>true</tt> when the <tt>Set-Cookie2</tt> value was
188      * received over secure conection
189      * @param header the <tt>Set-Cookie2</tt> <tt>Header</tt> received from the server
190      * @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie2 value
191      * @throws MalformedCookieException if an exception occurs during parsing
192      */
193     public Cookie[] parse(
194             String host, int port, String path, boolean secure, final Header header)
195             throws MalformedCookieException {
196         LOG.trace("enter RFC2965.parse("
197                   + "String, int, String, boolean, Header)");
198 
199         if (header == null) {
200             throw new IllegalArgumentException("Header may not be null.");
201         }
202         if (header.getName() == null) {
203             throw new IllegalArgumentException("Header name may not be null.");
204         }
205 
206         if (header.getName().equalsIgnoreCase(SET_COOKIE2_KEY)) {
207             // parse cookie2 cookies
208             return parse(host, port, path, secure, header.getValue());
209         } else if (header.getName().equalsIgnoreCase(RFC2109Spec.SET_COOKIE_KEY)) {
210             // delegate parsing of old-style cookies to rfc2109Spec
211             return this.rfc2109.parse(host, port, path, secure, header.getValue());
212         } else {
213             throw new MalformedCookieException("Header name is not valid. " +
214                                                "RFC 2965 supports \"set-cookie\" " +
215                                                "and \"set-cookie2\" headers.");
216         }
217     }
218 
219     /**
220      * @see #parse(String, int, String, boolean, org.apache.commons.httpclient.Header)
221      */
222     public Cookie[] parse(String host, int port, String path,
223                           boolean secure, final String header)
224             throws MalformedCookieException {
225         LOG.trace("enter RFC2965Spec.parse("
226                   + "String, int, String, boolean, String)");
227 
228         // before we do anything, lets check validity of arguments
229         if (host == null) {
230             throw new IllegalArgumentException(
231                     "Host of origin may not be null");
232         }
233         if (host.trim().equals("")) {
234             throw new IllegalArgumentException(
235                     "Host of origin may not be blank");
236         }
237         if (port < 0) {
238             throw new IllegalArgumentException("Invalid port: " + port);
239         }
240         if (path == null) {
241             throw new IllegalArgumentException(
242                     "Path of origin may not be null.");
243         }
244         if (header == null) {
245             throw new IllegalArgumentException("Header may not be null.");
246         }
247 
248         if (path.trim().equals("")) {
249             path = PATH_DELIM;
250         }
251         host = getEffectiveHost(host);
252 
253         HeaderElement[] headerElements =
254                 HeaderElement.parseElements(header.toCharArray());
255 
256         List cookies = new LinkedList();
257         for (int i = 0; i < headerElements.length; i++) {
258             HeaderElement headerelement = headerElements[i];
259             Cookie2 cookie = null;
260             try {
261                 cookie = new Cookie2(host,
262                                     headerelement.getName(),
263                                     headerelement.getValue(),
264                                     path,
265                                     null,
266                                     false,
267                                     new int[] {port});
268             } catch (IllegalArgumentException ex) {
269                 throw new MalformedCookieException(ex.getMessage());
270             }
271             NameValuePair[] parameters = headerelement.getParameters();
272             // could be null. In case only a header element and no parameters.
273             if (parameters != null) {
274                 // Eliminate duplicate attribues. The first occurence takes precedence
275                 Map attribmap = new HashMap(parameters.length); 
276                 for (int j = parameters.length - 1; j >= 0; j--) {
277                     NameValuePair param = parameters[j];
278                     attribmap.put(param.getName().toLowerCase(), param);
279                 }
280                 for (Iterator it = attribmap.entrySet().iterator(); it.hasNext(); ) {
281                     Map.Entry entry = (Map.Entry) it.next();
282                     parseAttribute((NameValuePair) entry.getValue(), cookie);
283                 }
284             }
285             cookies.add(cookie);
286             // cycle through the parameters
287         }
288         return (Cookie[]) cookies.toArray(new Cookie[cookies.size()]);
289     }
290 
291     /**
292      * Parse RFC 2965 specific cookie attribute and update the corresponsing
293      * {@link org.apache.commons.httpclient.Cookie} properties.
294      *
295      * @param attribute {@link org.apache.commons.httpclient.NameValuePair} cookie attribute from the
296      * <tt>Set-Cookie2</tt> header.
297      * @param cookie {@link org.apache.commons.httpclient.Cookie} to be updated
298      * @throws MalformedCookieException if an exception occurs during parsing
299      */
300     public void parseAttribute(
301             final NameValuePair attribute, final Cookie cookie)
302             throws MalformedCookieException {
303         if (attribute == null) {
304             throw new IllegalArgumentException("Attribute may not be null.");
305         }
306         if (attribute.getName() == null) {
307             throw new IllegalArgumentException("Attribute Name may not be null.");
308         }
309         if (cookie == null) {
310             throw new IllegalArgumentException("Cookie may not be null.");
311         }
312         final String paramName = attribute.getName().toLowerCase();
313         final String paramValue = attribute.getValue();
314 
315         CookieAttributeHandler handler = findAttribHandler(paramName);
316         if (handler == null) {
317             // ignore unknown attribute-value pairs
318             if (LOG.isDebugEnabled())
319                 LOG.debug("Unrecognized cookie attribute: " +
320                           attribute.toString());
321         } else {
322             handler.parse(cookie, paramValue);
323         }
324     }
325 
326     /**
327      * Performs RFC 2965 compliant {@link org.apache.commons.httpclient.Cookie} validation
328      *
329      * @param host the host from which the {@link org.apache.commons.httpclient.Cookie} was received
330      * @param port the port from which the {@link org.apache.commons.httpclient.Cookie} was received
331      * @param path the path from which the {@link org.apache.commons.httpclient.Cookie} was received
332      * @param secure <tt>true</tt> when the {@link org.apache.commons.httpclient.Cookie} was received using a
333      * secure connection
334      * @param cookie The cookie to validate
335      * @throws MalformedCookieException if an exception occurs during
336      * validation
337      */
338     public void validate(final String host, int port, final String path,
339                          boolean secure, final Cookie cookie)
340             throws MalformedCookieException {
341 
342         LOG.trace("enter RFC2965Spec.validate(String, int, String, "
343                   + "boolean, Cookie)");
344 
345         if (cookie instanceof Cookie2) {
346             if (cookie.getName().indexOf(' ') != -1) {
347                 throw new MalformedCookieException("Cookie name may not contain blanks");
348             }
349             if (cookie.getName().startsWith("$")) {
350                 throw new MalformedCookieException("Cookie name may not start with $");
351             }
352             CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure); 
353             for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) {
354               CookieAttributeHandler handler = (CookieAttributeHandler) i.next();
355               handler.validate(cookie, origin);
356             }
357         } else {
358             // old-style cookies are validated according to the old rules
359             this.rfc2109.validate(host, port, path, secure, cookie);
360         }
361     }
362 
363     /**
364      * Return <tt>true</tt> if the cookie should be submitted with a request
365      * with given attributes, <tt>false</tt> otherwise.
366      * @param host the host to which the request is being submitted
367      * @param port the port to which the request is being submitted (ignored)
368      * @param path the path to which the request is being submitted
369      * @param secure <tt>true</tt> if the request is using a secure connection
370      * @return true if the cookie matches the criterium
371      */
372     public boolean match(String host, int port, String path,
373                          boolean secure, final Cookie cookie) {
374 
375         LOG.trace("enter RFC2965.match("
376                   + "String, int, String, boolean, Cookie");
377         if (cookie == null) {
378             throw new IllegalArgumentException("Cookie may not be null");
379         }
380         if (cookie instanceof Cookie2) {
381             // check if cookie has expired
382             if (cookie.isPersistent() && cookie.isExpired()) {
383                 return false;
384             }
385             CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure); 
386             for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) {
387                 CookieAttributeHandler handler = (CookieAttributeHandler) i.next();
388                 if (!handler.match(cookie, origin)) {
389                     return false;
390                 }
391             }
392             return true;
393         } else {
394             // old-style cookies are matched according to the old rules
395             return this.rfc2109.match(host, port, path, secure, cookie);
396         }
397     }
398 
399     private void doFormatCookie2(final Cookie2 cookie, final StringBuffer buffer) {
400         String name = cookie.getName();
401         String value = cookie.getValue();
402         if (value == null) {
403             value = "";
404         }
405         this.formatter.format(buffer, new NameValuePair(name, value));
406         // format domain attribute
407         if (cookie.getDomain() != null && cookie.isDomainAttributeSpecified()) {
408             buffer.append("; ");
409             this.formatter.format(buffer, new NameValuePair("$Domain", cookie.getDomain()));
410         }
411         // format path attribute
412         if ((cookie.getPath() != null) && (cookie.isPathAttributeSpecified())) {
413             buffer.append("; ");
414             this.formatter.format(buffer, new NameValuePair("$Path", cookie.getPath()));
415         }
416         // format port attribute
417         if (cookie.isPortAttributeSpecified()) {
418             String portValue = "";
419             if (!cookie.isPortAttributeBlank()) {
420                 portValue = createPortAttribute(cookie.getPorts());
421             }
422             buffer.append("; ");
423             this.formatter.format(buffer, new NameValuePair("$Port", portValue));
424         }
425     }
426     
427     /**
428      * Return a string suitable for sending in a <tt>"Cookie"</tt> header as
429      * defined in RFC 2965
430      * @param cookie a {@link org.apache.commons.httpclient.Cookie} to be formatted as string
431      * @return a string suitable for sending in a <tt>"Cookie"</tt> header.
432      */
433     public String formatCookie(final Cookie cookie) {
434         LOG.trace("enter RFC2965Spec.formatCookie(Cookie)");
435 
436         if (cookie == null) {
437             throw new IllegalArgumentException("Cookie may not be null");
438         }
439         if (cookie instanceof Cookie2) {
440             Cookie2 cookie2 = (Cookie2) cookie;
441             int version = cookie2.getVersion();
442             final StringBuffer buffer = new StringBuffer();
443             this.formatter.format(buffer, new NameValuePair("$Version", Integer.toString(version)));
444             buffer.append("; ");
445             doFormatCookie2(cookie2, buffer);
446             return buffer.toString();
447         } else {
448             // old-style cookies are formatted according to the old rules
449             return this.rfc2109.formatCookie(cookie);
450         }
451     }
452 
453     /**
454      * Create a RFC 2965 compliant <tt>"Cookie"</tt> header value containing all
455      * {@link org.apache.commons.httpclient.Cookie}s suitable for
456      * sending in a <tt>"Cookie"</tt> header
457      * @param cookies an array of {@link org.apache.commons.httpclient.Cookie}s to be formatted
458      * @return a string suitable for sending in a Cookie header.
459      */
460     public String formatCookies(final Cookie[] cookies) {
461         LOG.trace("enter RFC2965Spec.formatCookieHeader(Cookie[])");
462 
463         if (cookies == null) {
464             throw new IllegalArgumentException("Cookies may not be null");
465         }
466         // check if cookies array contains a set-cookie (old style) cookie
467         boolean hasOldStyleCookie = false;
468         int version = -1;
469         for (int i = 0; i < cookies.length; i++) {
470             Cookie cookie = cookies[i];
471             if (!(cookie instanceof Cookie2)) {
472                 hasOldStyleCookie = true;
473                 break;
474             }
475             if (cookie.getVersion() > version) {
476                 version = cookie.getVersion();
477             }
478         }
479         if (version < 0) {
480             version = 0;
481         }
482         if (hasOldStyleCookie || version < 1) {
483             // delegate old-style cookie formatting to rfc2109Spec
484             return this.rfc2109.formatCookies(cookies);
485         }
486         // Arrange cookies by path
487         Arrays.sort(cookies, PATH_COMPOARATOR);
488         
489         final StringBuffer buffer = new StringBuffer();
490         // format cookie version
491         this.formatter.format(buffer, new NameValuePair("$Version", Integer.toString(version)));
492         for (int i = 0; i < cookies.length; i++) {
493             buffer.append("; ");
494             Cookie2 cookie = (Cookie2) cookies[i];
495             // format cookie attributes
496             doFormatCookie2(cookie, buffer);
497         }
498         return buffer.toString();
499     }
500 
501     /**
502      * Retrieves valid Port attribute value for the given ports array.
503      * e.g. "8000,8001,8002"
504      *
505      * @param ports int array of ports
506      */
507     private String createPortAttribute(int[] ports) {
508         StringBuffer portValue = new StringBuffer();
509         for (int i = 0, len = ports.length; i < len; i++) {
510             if (i > 0) {
511                 portValue.append(",");
512             }
513             portValue.append(ports[i]);
514         }
515         return portValue.toString();
516     }
517 
518     /**
519      * Parses the given Port attribute value (e.g. "8000,8001,8002")
520      * into an array of ports.
521      *
522      * @param portValue port attribute value
523      * @return parsed array of ports
524      * @throws MalformedCookieException if there is a problem in
525      *          parsing due to invalid portValue.
526      */
527     private int[] parsePortAttribute(final String portValue)
528             throws MalformedCookieException {
529         StringTokenizer st = new StringTokenizer(portValue, ",");
530         int[] ports = new int[st.countTokens()];
531         try {
532             int i = 0;
533             while(st.hasMoreTokens()) {
534                 ports[i] = Integer.parseInt(st.nextToken().trim());
535                 if (ports[i] < 0) {
536                   throw new MalformedCookieException ("Invalid Port attribute.");
537                 }
538                 ++i;
539             }
540         } catch (NumberFormatException e) {
541             throw new MalformedCookieException ("Invalid Port "
542                                                 + "attribute: " + e.getMessage());
543         }
544         return ports;
545     }
546 
547     /**
548      * Gets 'effective host name' as defined in RFC 2965.
549      * <p>
550      * If a host name contains no dots, the effective host name is
551      * that name with the string .local appended to it.  Otherwise
552      * the effective host name is the same as the host name.  Note
553      * that all effective host names contain at least one dot.
554      *
555      * @param host host name where cookie is received from or being sent to.
556      * @return
557      */
558     private static String getEffectiveHost(final String host) {
559         String effectiveHost = host.toLowerCase();
560         if (host.indexOf('.') < 0) {
561             effectiveHost += ".local";
562         }
563         return effectiveHost;
564     }
565 
566     /**
567      * Performs domain-match as defined by the RFC2965.
568      * <p>
569      * Host A's name domain-matches host B's if
570      * <ol>
571      *   <ul>their host name strings string-compare equal; or</ul>
572      *   <ul>A is a HDN string and has the form NB, where N is a non-empty
573      *       name string, B has the form .B', and B' is a HDN string.  (So,
574      *       x.y.com domain-matches .Y.com but not Y.com.)</ul>
575      * </ol>
576      *
577      * @param host host name where cookie is received from or being sent to.
578      * @param domain The cookie domain attribute.
579      * @return true if the specified host matches the given domain.
580      */
581     public boolean domainMatch(String host, String domain) {
582         boolean match = host.equals(domain)
583                         || (domain.startsWith(".") && host.endsWith(domain));
584 
585         return match;
586     }
587 
588     /**
589      * Returns <tt>true</tt> if the given port exists in the given
590      * ports list.
591      *
592      * @param port port of host where cookie was received from or being sent to.
593      * @param ports port list
594      * @return true returns <tt>true</tt> if the given port exists in
595      *         the given ports list; <tt>false</tt> otherwise.
596      */
597     private boolean portMatch(int port, int[] ports) {
598         boolean portInList = false;
599         for (int i = 0, len = ports.length; i < len; i++) {
600             if (port == ports[i]) {
601                 portInList = true;
602                 break;
603             }
604         }
605         return portInList;
606     }
607 
608     /**
609      * <tt>"Path"</tt> attribute handler for RFC 2965 cookie spec.
610      */
611     private class Cookie2PathAttributeHandler
612             implements CookieAttributeHandler {
613 
614         /**
615          * Parse cookie path attribute.
616          */
617         public void parse(final Cookie cookie, final String path)
618                 throws MalformedCookieException {
619             if (cookie == null) {
620                 throw new IllegalArgumentException("Cookie may not be null");
621             }
622             if (path == null) {
623                 throw new MalformedCookieException(
624                         "Missing value for path attribute");
625             }
626             if (path.trim().equals("")) {
627                 throw new MalformedCookieException(
628                         "Blank value for path attribute");
629             }
630             cookie.setPath(path);
631             cookie.setPathAttributeSpecified(true);
632         }
633 
634         /**
635          * Validate cookie path attribute. The value for the Path attribute must be a
636          * prefix of the request-URI (case-sensitive matching).
637          */
638         public void validate(final Cookie cookie, final CookieOrigin origin)
639                 throws MalformedCookieException {
640             if (cookie == null) {
641                 throw new IllegalArgumentException("Cookie may not be null");
642             }
643             if (origin == null) {
644                 throw new IllegalArgumentException("Cookie origin may not be null");
645             }
646             String path = origin.getPath();
647             if (path == null) {
648                 throw new IllegalArgumentException(
649                         "Path of origin host may not be null.");
650             }
651             if (cookie.getPath() == null) {
652                 throw new MalformedCookieException("Invalid cookie state: " +
653                                                    "path attribute is null.");
654             }
655             if (path.trim().equals("")) {
656                 path = PATH_DELIM;
657             }
658 
659             if (!pathMatch(path, cookie.getPath())) {
660                 throw new MalformedCookieException(
661                         "Illegal path attribute \"" + cookie.getPath()
662                         + "\". Path of origin: \"" + path + "\"");
663             }
664         }
665 
666         /**
667          * Match cookie path attribute. The value for the Path attribute must be a
668          * prefix of the request-URI (case-sensitive matching).
669          */
670         public boolean match(final Cookie cookie, final CookieOrigin origin) {
671             if (cookie == null) {
672                 throw new IllegalArgumentException("Cookie may not be null");
673             }
674             if (origin == null) {
675                 throw new IllegalArgumentException("Cookie origin may not be null");
676             }
677             String path = origin.getPath();
678             if (cookie.getPath() == null) {
679                 LOG.warn("Invalid cookie state: path attribute is null.");
680                 return false;
681             }
682             if (path.trim().equals("")) {
683                 path = PATH_DELIM;
684             }
685 
686             if (!pathMatch(path, cookie.getPath())) {
687                 return false;
688             }
689             return true;
690         }
691     }
692 
693     /**
694      * <tt>"Domain"</tt> cookie attribute handler for RFC 2965 cookie spec.
695      */
696     private class Cookie2DomainAttributeHandler
697             implements CookieAttributeHandler {
698 
699         /**
700          * Parse cookie domain attribute.
701          */
702         public void parse(final Cookie cookie, String domain)
703                 throws MalformedCookieException {
704             if (cookie == null) {
705                 throw new IllegalArgumentException("Cookie may not be null");
706             }
707             if (domain == null) {
708                 throw new MalformedCookieException(
709                         "Missing value for domain attribute");
710             }
711             if (domain.trim().equals("")) {
712                 throw new MalformedCookieException(
713                         "Blank value for domain attribute");
714             }
715             domain = domain.toLowerCase();
716             if (!domain.startsWith(".")) {
717                 // Per RFC 2965 section 3.2.2
718                 // "... If an explicitly specified value does not start with
719                 // a dot, the user agent supplies a leading dot ..."
720                 // That effectively implies that the domain attribute 
721                 // MAY NOT be an IP address of a host name
722                 domain = "." + domain;
723             }
724             cookie.setDomain(domain);
725             cookie.setDomainAttributeSpecified(true);
726         }
727 
728         /**
729          * Validate cookie domain attribute.
730          */
731         public void validate(final Cookie cookie, final CookieOrigin origin)
732                 throws MalformedCookieException {
733             if (cookie == null) {
734                 throw new IllegalArgumentException("Cookie may not be null");
735             }
736             if (origin == null) {
737                 throw new IllegalArgumentException("Cookie origin may not be null");
738             }
739             String host = origin.getHost().toLowerCase();
740             if (cookie.getDomain() == null) {
741                 throw new MalformedCookieException("Invalid cookie state: " +
742                                                    "domain not specified");
743             }
744             String cookieDomain = cookie.getDomain().toLowerCase();
745 
746             if (cookie.isDomainAttributeSpecified()) {
747                 // Domain attribute must start with a dot
748                 if (!cookieDomain.startsWith(".")) {
749                     throw new MalformedCookieException("Domain attribute \"" +
750                         cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot");
751                 }
752 
753                 // Domain attribute must contain atleast one embedded dot,
754                 // or the value must be equal to .local.
755                 int dotIndex = cookieDomain.indexOf('.', 1);
756                 if (((dotIndex < 0) || (dotIndex == cookieDomain.length() - 1))
757                     && (!cookieDomain.equals(".local"))) {
758                     throw new MalformedCookieException(
759                             "Domain attribute \"" + cookie.getDomain()
760                             + "\" violates RFC 2965: the value contains no embedded dots "
761                             + "and the value is not .local");
762                 }
763 
764                 // The effective host name must domain-match domain attribute.
765                 if (!domainMatch(host, cookieDomain)) {
766                     throw new MalformedCookieException(
767                             "Domain attribute \"" + cookie.getDomain()
768                             + "\" violates RFC 2965: effective host name does not "
769                             + "domain-match domain attribute.");
770                 }
771 
772                 // effective host name minus domain must not contain any dots
773                 String effectiveHostWithoutDomain = host.substring(
774                         0, host.length() - cookieDomain.length());
775                 if (effectiveHostWithoutDomain.indexOf('.') != -1) {
776                     throw new MalformedCookieException("Domain attribute \""
777                                                        + cookie.getDomain() + "\" violates RFC 2965: "
778                                                        + "effective host minus domain may not contain any dots");
779                 }
780             } else {
781                 // Domain was not specified in header. In this case, domain must
782                 // string match request host (case-insensitive).
783                 if (!cookie.getDomain().equals(host)) {
784                     throw new MalformedCookieException("Illegal domain attribute: \""
785                                                        + cookie.getDomain() + "\"."
786                                                        + "Domain of origin: \""
787                                                        + host + "\"");
788                 }
789             }
790         }
791 
792         /**
793          * Match cookie domain attribute.
794          */
795         public boolean match(final Cookie cookie, final CookieOrigin origin) {
796             if (cookie == null) {
797                 throw new IllegalArgumentException("Cookie may not be null");
798             }
799             if (origin == null) {
800                 throw new IllegalArgumentException("Cookie origin may not be null");
801             }
802             String host = origin.getHost().toLowerCase();
803             String cookieDomain = cookie.getDomain();
804 
805             // The effective host name MUST domain-match the Domain
806             // attribute of the cookie.
807             if (!domainMatch(host, cookieDomain)) {
808                 return false;
809             }
810             // effective host name minus domain must not contain any dots
811             String effectiveHostWithoutDomain = host.substring(
812                     0, host.length() - cookieDomain.length());
813             if (effectiveHostWithoutDomain.indexOf('.') != -1) {
814                 return false;
815             }
816             return true;
817         }
818 
819     }
820 
821     /**
822      * <tt>"Port"</tt> cookie attribute handler for RFC 2965 cookie spec.
823      */
824     private class Cookie2PortAttributeHandler
825             implements CookieAttributeHandler {
826 
827         /**
828          * Parse cookie port attribute.
829          */
830         public void parse(final Cookie cookie, final String portValue)
831                 throws MalformedCookieException {
832             if (cookie == null) {
833                 throw new IllegalArgumentException("Cookie may not be null");
834             }
835             if (cookie instanceof Cookie2) {
836                 Cookie2 cookie2 = (Cookie2) cookie;
837                 if ((portValue == null) || (portValue.trim().equals(""))) {
838                     // If the Port attribute is present but has no value, the
839                     // cookie can only be sent to the request-port.
840                     // Since the default port list contains only request-port, we don't
841                     // need to do anything here.
842                     cookie2.setPortAttributeBlank(true);
843                 } else {
844                     int[] ports = parsePortAttribute(portValue);
845                     cookie2.setPorts(ports);
846                 }
847                 cookie2.setPortAttributeSpecified(true);
848             }
849         }
850 
851         /**
852          * Validate cookie port attribute. If the Port attribute was specified
853          * in header, the request port must be in cookie's port list.
854          */
855         public void validate(final Cookie cookie, final CookieOrigin origin)
856                 throws MalformedCookieException {
857             if (cookie == null) {
858                 throw new IllegalArgumentException("Cookie may not be null");
859             }
860             if (origin == null) {
861                 throw new IllegalArgumentException("Cookie origin may not be null");
862             }
863             if (cookie instanceof Cookie2) {
864                 Cookie2 cookie2 = (Cookie2) cookie;
865                 int port = origin.getPort();
866                 if (cookie2.isPortAttributeSpecified()) {
867                     if (!portMatch(port, cookie2.getPorts())) {
868                         throw new MalformedCookieException(
869                                 "Port attribute violates RFC 2965: "
870                                 + "Request port not found in cookie's port list.");
871                     }
872                 }
873             }
874         }
875 
876         /**
877          * Match cookie port attribute. If the Port attribute is not specified
878          * in header, the cookie can be sent to any port. Otherwise, the request port
879          * must be in the cookie's port list.
880          */
881         public boolean match(final Cookie cookie, final CookieOrigin origin) {
882             if (cookie == null) {
883                 throw new IllegalArgumentException("Cookie may not be null");
884             }
885             if (origin == null) {
886                 throw new IllegalArgumentException("Cookie origin may not be null");
887             }
888             if (cookie instanceof Cookie2) {
889                 Cookie2 cookie2 = (Cookie2) cookie;
890                 int port = origin.getPort();
891                 if (cookie2.isPortAttributeSpecified()) {
892                     if (cookie2.getPorts() == null) {
893                         LOG.warn("Invalid cookie state: port not specified");
894                         return false;
895                     }
896                     if (!portMatch(port, cookie2.getPorts())) {
897                         return false;
898                     }
899                 }
900                 return true;
901             } else {
902                 return false;
903             }
904         }
905     }
906 
907   /**
908    * <tt>"Max-age"</tt> cookie attribute handler for RFC 2965 cookie spec.
909    */
910   private class Cookie2MaxageAttributeHandler
911           implements CookieAttributeHandler {
912 
913       /**
914        * Parse cookie max-age attribute.
915        */
916       public void parse(final Cookie cookie, final String value)
917               throws MalformedCookieException {
918           if (cookie == null) {
919               throw new IllegalArgumentException("Cookie may not be null");
920           }
921           if (value == null) {
922               throw new MalformedCookieException(
923                       "Missing value for max-age attribute");
924           }
925           int age = -1;
926           try {
927               age = Integer.parseInt(value);
928           } catch (NumberFormatException e) {
929               age = -1;
930           }
931           if (age < 0) {
932               throw new MalformedCookieException ("Invalid max-age attribute.");
933           }
934           cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L));
935       }
936 
937       /**
938        * validate cookie max-age attribute.
939        */
940       public void validate(final Cookie cookie, final CookieOrigin origin) {
941       }
942 
943       /**
944        * @see CookieAttributeHandler#match(org.apache.commons.httpclient.Cookie, String)
945        */
946       public boolean match(final Cookie cookie, final CookieOrigin origin) {
947           return true;
948       }
949 
950   }
951 
952   /**
953    * <tt>"Secure"</tt> cookie attribute handler for RFC 2965 cookie spec.
954    */
955   private class CookieSecureAttributeHandler
956           implements CookieAttributeHandler {
957 
958       public void parse(final Cookie cookie, final String secure)
959               throws MalformedCookieException {
960           cookie.setSecure(true);
961       }
962 
963       public void validate(final Cookie cookie, final CookieOrigin origin)
964               throws MalformedCookieException {
965       }
966 
967       public boolean match(final Cookie cookie, final CookieOrigin origin) {
968           if (cookie == null) {
969               throw new IllegalArgumentException("Cookie may not be null");
970           }
971           if (origin == null) {
972               throw new IllegalArgumentException("Cookie origin may not be null");
973           }
974           return cookie.getSecure() == origin.isSecure();
975       }
976       
977   }
978 
979   /**
980    * <tt>"Commant"</tt> cookie attribute handler for RFC 2965 cookie spec.
981    */
982   private class CookieCommentAttributeHandler
983           implements CookieAttributeHandler {
984 
985       public void parse(final Cookie cookie, final String comment)
986               throws MalformedCookieException {
987           cookie.setComment(comment);
988       }
989 
990       public void validate(final Cookie cookie, final CookieOrigin origin)
991               throws MalformedCookieException {
992       }
993 
994       public boolean match(final Cookie cookie, final CookieOrigin origin) {
995           return true;
996       }
997       
998   }
999 
1000   /**
1001    * <tt>"CommantURL"</tt> cookie attribute handler for RFC 2965 cookie spec.
1002    */
1003   private class CookieCommentUrlAttributeHandler
1004           implements CookieAttributeHandler {
1005 
1006       public void parse(final Cookie cookie, final String commenturl)
1007               throws MalformedCookieException {
1008           if (cookie instanceof Cookie2) {
1009               Cookie2 cookie2 = (Cookie2) cookie;
1010               cookie2.setCommentURL(commenturl);
1011           }
1012       }
1013 
1014       public void validate(final Cookie cookie, final CookieOrigin origin)
1015               throws MalformedCookieException {
1016       }
1017 
1018       public boolean match(final Cookie cookie, final CookieOrigin origin) {
1019           return true;
1020       }
1021       
1022   }
1023 
1024   /**
1025    * <tt>"Discard"</tt> cookie attribute handler for RFC 2965 cookie spec.
1026    */
1027   private class CookieDiscardAttributeHandler
1028           implements CookieAttributeHandler {
1029 
1030       public void parse(final Cookie cookie, final String commenturl)
1031               throws MalformedCookieException {
1032           if (cookie instanceof Cookie2) {
1033               Cookie2 cookie2 = (Cookie2) cookie;
1034               cookie2.setDiscard(true);
1035           }
1036       }
1037 
1038       public void validate(final Cookie cookie, final CookieOrigin origin)
1039               throws MalformedCookieException {
1040       }
1041 
1042       public boolean match(final Cookie cookie, final CookieOrigin origin) {
1043           return true;
1044       }
1045       
1046   }
1047 
1048   /**
1049      * <tt>"Version"</tt> cookie attribute handler for RFC 2965 cookie spec.
1050      */
1051     private class Cookie2VersionAttributeHandler
1052             implements CookieAttributeHandler {
1053 
1054         /**
1055          * Parse cookie version attribute.
1056          */
1057         public void parse(final Cookie cookie, final String value)
1058                 throws MalformedCookieException {
1059             if (cookie == null) {
1060                 throw new IllegalArgumentException("Cookie may not be null");
1061             }
1062             if (cookie instanceof Cookie2) {
1063                 Cookie2 cookie2 = (Cookie2) cookie;
1064                 if (value == null) {
1065                     throw new MalformedCookieException(
1066                             "Missing value for version attribute");
1067                 }
1068                 int version = -1;
1069                 try {
1070                     version = Integer.parseInt(value);
1071                 } catch (NumberFormatException e) {
1072                     version = -1;
1073                 }
1074                 if (version < 0) {
1075                     throw new MalformedCookieException("Invalid cookie version.");
1076                 }
1077                 cookie2.setVersion(version);
1078                 cookie2.setVersionAttributeSpecified(true);
1079             }
1080         }
1081 
1082         /**
1083          * validate cookie version attribute. Version attribute is REQUIRED.
1084          */
1085         public void validate(final Cookie cookie, final CookieOrigin origin)
1086                 throws MalformedCookieException {
1087             if (cookie == null) {
1088                 throw new IllegalArgumentException("Cookie may not be null");
1089             }
1090             if (cookie instanceof Cookie2) {
1091                 Cookie2 cookie2 = (Cookie2) cookie;
1092                 if (!cookie2.isVersionAttributeSpecified()) {
1093                     throw new MalformedCookieException(
1094                             "Violates RFC 2965. Version attribute is required.");
1095                 }
1096             }
1097         }
1098 
1099         public boolean match(final Cookie cookie, final CookieOrigin origin) {
1100             return true;
1101         }
1102 
1103     }
1104 
1105     public int getVersion() {
1106         return 1;
1107     }
1108 
1109     public Header getVersionHeader() {
1110         ParameterFormatter formatter = new ParameterFormatter();
1111         StringBuffer buffer = new StringBuffer();
1112         formatter.format(buffer, new NameValuePair("$Version",
1113                 Integer.toString(getVersion())));
1114         return new Header("Cookie2", buffer.toString(), true);
1115     }
1116     
1117 }
1118 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/package-frame.html100644 0 0 4345 10661532632 26724 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.cookie

org.apache.commons.httpclient.cookie

Classes

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/cookie/package-summary.html100644 0 0 7763 10661532632 27336 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.cookie

Package org.apache.commons.httpclient.cookie

Class Summary
Cookie2
CookieAttributeHandler
CookieOrigin
CookiePathComparator
CookiePolicy
CookieSpec
CookieSpecBase
CookieVersionSupport
IgnoreCookiesSpec
MalformedCookieException
NetscapeDraftSpec
RFC2109Spec
RFC2965Spec

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/ByteArrayRequestEntity.html100644 0 0 23117 10661532627 31125 0ustar 0 0 ByteArrayRequestEntity xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/ByteArrayRequestEntity.java,v 1.3 2004/05/13 02:26:08 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32  package org.apache.commons.httpclient.methods;
33  
34  import java.io.IOException;
35  import java.io.OutputStream;
36  
37  /**
38   * A RequestEntity that contains an array of bytes.
39   * 
40   * @since 3.0
41   */
42  public class ByteArrayRequestEntity implements RequestEntity {
43  
44      /** The content */
45      private byte[] content;
46      
47      /** The content type */
48      private String contentType;
49  
50      /**
51       * Creates a new entity with the given content.
52       * @param content The content to set.
53       */
54      public ByteArrayRequestEntity(byte[] content) {
55          this(content, null);
56      }
57      
58      /**
59       * Creates a new entity with the given content and content type.
60       * @param content The content to set.
61       * @param contentType The content type to set or <code>null</code>.
62       */
63      public ByteArrayRequestEntity(byte[] content, String contentType) {
64          super();
65          if (content == null) {
66              throw new IllegalArgumentException("The content cannot be null");
67          }
68          this.content = content;
69          this.contentType = contentType;
70      }
71  
72      /**
73       * @return <code>true</code>
74       */
75      public boolean isRepeatable() {
76          return true;
77      }
78  
79      /* (non-Javadoc)
80       * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType()
81       */
82      public String getContentType() {
83          return contentType;
84      }
85      
86      /* (non-Javadoc)
87       * @see org.apache.commons.httpclient.RequestEntity#writeRequest(java.io.OutputStream)
88       */
89      public void writeRequest(OutputStream out) throws IOException {
90          out.write(content);
91      }
92  
93      /**
94       * @return The length of the content.
95       */
96      public long getContentLength() {
97          return content.length;
98      }
99  
100     /**
101      * @return Returns the content.
102      */
103     public byte[] getContent() {
104         return content;
105     }
106 
107 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/DeleteMethod.html100644 0 0 21102 10661532627 27010 0ustar 0 0 DeleteMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/DeleteMethod.java,v 1.14 2004/04/18 23:51:37 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods;
32  
33  import org.apache.commons.httpclient.HttpMethodBase;
34  
35  
36  /**
37   * Implements the HTTP DELETE method.
38   * <p>
39   * The HTTP DELETE method is defined in section 9.7 of 
40   * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
41   * <blockquote>
42   * The DELETE method requests that the origin server delete the resource
43   * identified by the Request-URI. This method MAY be overridden by human
44   * intervention (or other means) on the origin server.
45   * </blockquote>
46   * </p>
47   *
48   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
49   * @author <a href="mailto:bcholmes@apache.org">B.C. Holmes</a>
50   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
51   *
52   * @version $Revision: 480424 $
53   * @since 1.0
54   */
55  public class DeleteMethod
56      extends HttpMethodBase {
57  
58  
59      // ----------------------------------------------------------- Constructors
60  
61  
62      /**
63       * No-arg constructor.
64       *
65       * @since 1.0
66       */
67      public DeleteMethod() {
68      }
69  
70  
71      /**
72       * Constructor specifying a URI.
73       *
74       * @param uri either an absolute or relative URI
75       *
76       * @since 1.0
77       */
78      public DeleteMethod(String uri) {
79          super(uri);
80      }
81  
82  
83      // ----------------------------------------------------- HttpMethod Methods
84  
85      /**
86       * Returns <tt>"DELETE"</tt>.
87       * @return <tt>"DELETE"</tt>
88       *
89       * @since 2.0
90       */
91      public String getName() {
92          return "DELETE";
93      }
94  
95  
96  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/EntityEnclosingMethod.html100644 0 0 140526 10661532627 30760 0ustar 0 0 EntityEnclosingMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/EntityEnclosingMethod.java,v 1.39 2004/07/03 14:27:03 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.io.OutputStream;
36  import java.io.UnsupportedEncodingException;
37  
38  import org.apache.commons.httpclient.ChunkedOutputStream;
39  import org.apache.commons.httpclient.Header;
40  import org.apache.commons.httpclient.HttpConnection;
41  import org.apache.commons.httpclient.HttpException;
42  import org.apache.commons.httpclient.HttpState;
43  import org.apache.commons.httpclient.HttpVersion;
44  import org.apache.commons.httpclient.ProtocolException;
45  import org.apache.commons.logging.Log;
46  import org.apache.commons.logging.LogFactory;
47  
48  /**
49   * This abstract class serves as a foundation for all HTTP methods 
50   * that can enclose an entity within requests 
51   *
52   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
53   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
54   *
55   * @since 2.0beta1
56   * @version $Revision: 480424 $
57   */
58  public abstract class EntityEnclosingMethod extends ExpectContinueMethod {
59  
60      // ----------------------------------------- Static variables/initializers
61  
62      /**
63       * The content length will be calculated automatically. This implies
64       * buffering of the content.
65       * @deprecated Use {@link InputStreamRequestEntity#CONTENT_LENGTH_AUTO}.
66       */
67      public static final long CONTENT_LENGTH_AUTO = InputStreamRequestEntity.CONTENT_LENGTH_AUTO;
68  
69      /**
70       * The request will use chunked transfer encoding. Content length is not
71       * calculated and the content is not buffered.<br>
72       * @deprecated Use {@link #setContentChunked(boolean)}.
73       */
74      public static final long CONTENT_LENGTH_CHUNKED = -1;
75  
76      /** LOG object for this class. */
77      private static final Log LOG = LogFactory.getLog(EntityEnclosingMethod.class);
78  
79      /** The unbuffered request body, if any. */
80      private InputStream requestStream = null;
81  
82      /** The request body as string, if any. */
83      private String requestString = null;
84  
85      private RequestEntity requestEntity;
86      
87      /** Counts how often the request was sent to the server. */
88      private int repeatCount = 0;
89  
90      /** The content length of the <code>requestBodyStream</code> or one of
91       *  <code>CONTENT_LENGTH_AUTO</code> and <code>CONTENT_LENGTH_CHUNKED</code>.
92       * 
93       * @deprecated
94       */
95      private long requestContentLength = InputStreamRequestEntity.CONTENT_LENGTH_AUTO;
96      
97      private boolean chunked = false;
98  
99      // ----------------------------------------------------------- Constructors
100 
101     /**
102      * No-arg constructor.
103      *
104      * @since 2.0
105      */
106     public EntityEnclosingMethod() {
107         super();
108         setFollowRedirects(false);
109     }
110 
111     /**
112      * Constructor specifying a URI.
113      *
114      * @param uri either an absolute or relative URI
115      *
116      * @since 2.0
117      */
118     public EntityEnclosingMethod(String uri) {
119         super(uri);
120         setFollowRedirects(false);
121     }
122 
123     /**
124      * Returns <tt>true</tt> if there is a request body to be sent.
125      * 
126      * <P>This method must be overridden by sub-classes that implement
127      * alternative request content input methods
128      * </p>
129      * 
130      * @return boolean
131      * 
132      * @since 2.0beta1
133      */
134     protected boolean hasRequestContent() {
135         LOG.trace("enter EntityEnclosingMethod.hasRequestContent()");
136         return (this.requestEntity != null) 
137             || (this.requestStream != null) 
138             || (this.requestString != null);
139     }
140 
141     /**
142      * Clears the request body.
143      * 
144      * <p>This method must be overridden by sub-classes that implement
145      * alternative request content input methods.</p>
146      * 
147      * @since 2.0beta1
148      */
149     protected void clearRequestBody() {
150         LOG.trace("enter EntityEnclosingMethod.clearRequestBody()");
151         this.requestStream = null;
152         this.requestString = null;
153         this.requestEntity = null;
154     }
155 
156     /**
157      * Generates the request body.   
158      * 
159      * <p>This method must be overridden by sub-classes that implement
160      * alternative request content input methods.</p>
161      * 
162      * @return request body as an array of bytes. If the request content 
163      *          has not been set, returns <tt>null</tt>.
164      * 
165      * @since 2.0beta1
166      */
167     protected byte[] generateRequestBody() {
168         LOG.trace("enter EntityEnclosingMethod.renerateRequestBody()");
169         return null;
170     }
171 
172     protected RequestEntity generateRequestEntity() {
173         
174         byte[] requestBody = generateRequestBody();
175         if (requestBody != null) {
176             // use the request body, if it exists.
177             // this is just for backwards compatability
178             this.requestEntity = new ByteArrayRequestEntity(requestBody);
179         } else if (this.requestStream != null) {
180             this.requestEntity = new InputStreamRequestEntity(
181                 requestStream, 
182                 requestContentLength);
183             this.requestStream = null;
184         } else if (this.requestString != null) {
185             String charset = getRequestCharSet(); 
186             try {
187                 this.requestEntity = new StringRequestEntity(
188                         requestString, null, charset);
189             } catch (UnsupportedEncodingException e) {
190                 if (LOG.isWarnEnabled()) {
191                     LOG.warn(charset + " not supported");
192                 }
193                 try {
194                     this.requestEntity = new StringRequestEntity(
195                             requestString, null, null);
196                 } catch (UnsupportedEncodingException ignore) {
197                 }
198             }
199         }
200 
201         return this.requestEntity;
202     }
203     
204     /**
205      * Entity enclosing requests cannot be redirected without user intervention
206      * according to RFC 2616.
207      *
208      * @return <code>false</code>.
209      *
210      * @since 2.0
211      */
212     public boolean getFollowRedirects() {
213         return false;
214     }
215 
216 
217     /**
218      * Entity enclosing requests cannot be redirected without user intervention 
219      * according to RFC 2616.
220      *
221      * @param followRedirects must always be <code>false</code>
222      */
223     public void setFollowRedirects(boolean followRedirects) {
224         if (followRedirects == true) {
225             throw new IllegalArgumentException("Entity enclosing requests cannot be redirected without user intervention");
226         }
227         super.setFollowRedirects(false);
228     }
229 
230     /**
231      * Sets length information about the request body.
232      *
233      * <p>
234      * Note: If you specify a content length the request is unbuffered. This
235      * prevents redirection and automatic retry if a request fails the first
236      * time. This means that the HttpClient can not perform authorization
237      * automatically but will throw an Exception. You will have to set the
238      * necessary 'Authorization' or 'Proxy-Authorization' headers manually.
239      * </p>
240      *
241      * @param length size in bytes or any of CONTENT_LENGTH_AUTO,
242      *        CONTENT_LENGTH_CHUNKED. If number of bytes or CONTENT_LENGTH_CHUNKED
243      *        is specified the content will not be buffered internally and the
244      *        Content-Length header of the request will be used. In this case
245      *        the user is responsible to supply the correct content length.
246      *        If CONTENT_LENGTH_AUTO is specified the request will be buffered
247      *        before it is sent over the network.
248      * 
249      * @deprecated Use {@link #setContentChunked(boolean)} or 
250      * {@link #setRequestEntity(RequestEntity)}
251      */
252     public void setRequestContentLength(int length) {
253         LOG.trace("enter EntityEnclosingMethod.setRequestContentLength(int)");
254         this.requestContentLength = length;
255     }
256 
257     /**
258      * Returns the request's charset.  The charset is parsed from the request entity's 
259      * content type, unless the content type header has been set manually. 
260      * 
261      * @see RequestEntity#getContentType()
262      * 
263      * @since 3.0
264      */
265     public String getRequestCharSet() {
266         if (getRequestHeader("Content-Type") == null) {
267             // check the content type from request entity
268             // We can't call getRequestEntity() since it will probably call
269             // this method.
270             if (this.requestEntity != null) {
271                 return getContentCharSet(
272                     new Header("Content-Type", requestEntity.getContentType()));
273             } else {
274                 return super.getRequestCharSet();
275             }
276         } else {
277             return super.getRequestCharSet();
278         }
279     }
280 
281     /**
282      * Sets length information about the request body.
283      *
284      * <p>
285      * Note: If you specify a content length the request is unbuffered. This
286      * prevents redirection and automatic retry if a request fails the first
287      * time. This means that the HttpClient can not perform authorization
288      * automatically but will throw an Exception. You will have to set the
289      * necessary 'Authorization' or 'Proxy-Authorization' headers manually.
290      * </p>
291      *
292      * @param length size in bytes or any of CONTENT_LENGTH_AUTO,
293      *        CONTENT_LENGTH_CHUNKED. If number of bytes or CONTENT_LENGTH_CHUNKED
294      *        is specified the content will not be buffered internally and the
295      *        Content-Length header of the request will be used. In this case
296      *        the user is responsible to supply the correct content length.
297      *        If CONTENT_LENGTH_AUTO is specified the request will be buffered
298      *        before it is sent over the network.
299      * 
300      * @deprecated Use {@link #setContentChunked(boolean)} or 
301      * {@link #setRequestEntity(RequestEntity)}
302      */
303     public void setRequestContentLength(long length) {
304         LOG.trace("enter EntityEnclosingMethod.setRequestContentLength(int)");
305         this.requestContentLength = length;
306     }
307 
308     /**
309      * Sets whether or not the content should be chunked.
310      * 
311      * @param chunked <code>true</code> if the content should be chunked
312      * 
313      * @since 3.0
314      */
315     public void setContentChunked(boolean chunked) {
316         this.chunked = chunked;
317     }
318     
319     /**
320      * Returns the length of the request body.
321      *
322      * @return number of bytes in the request body
323      */
324     protected long getRequestContentLength() {
325         LOG.trace("enter EntityEnclosingMethod.getRequestContentLength()");
326 
327         if (!hasRequestContent()) {
328             return 0;
329         }
330         if (this.chunked) {
331             return -1;
332         }
333         if (this.requestEntity == null) {
334             this.requestEntity = generateRequestEntity(); 
335         }
336         return (this.requestEntity == null) ? 0 : this.requestEntity.getContentLength();
337     }
338 
339     /**
340      * Populates the request headers map to with additional 
341      * {@link org.apache.commons.httpclient.Header headers} to be submitted to 
342      * the given {@link HttpConnection}.
343      *
344      * <p>
345      * This implementation adds tt>Content-Length</tt> or <tt>Transfer-Encoding</tt>
346      * headers.
347      * </p>
348      *
349      * <p>
350      * Subclasses may want to override this method to to add additional
351      * headers, and may choose to invoke this implementation (via
352      * <tt>super</tt>) to add the "standard" headers.
353      * </p>
354      *
355      * @param state the {@link HttpState state} information associated with this method
356      * @param conn the {@link HttpConnection connection} used to execute
357      *        this HTTP method
358      *
359      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
360      *                     can be recovered from.
361      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
362      *                    cannot be recovered from.
363      *
364      * @see #writeRequestHeaders
365      * 
366      * @since 3.0
367      */
368     protected void addRequestHeaders(HttpState state, HttpConnection conn)
369     throws IOException, HttpException {
370         LOG.trace("enter EntityEnclosingMethod.addRequestHeaders(HttpState, "
371             + "HttpConnection)");
372 
373         super.addRequestHeaders(state, conn);
374         addContentLengthRequestHeader(state, conn);
375 
376         // only use the content type of the request entity if it has not already been
377         // set manually
378         if (getRequestHeader("Content-Type") == null) {
379             RequestEntity requestEntity = getRequestEntity();
380             if (requestEntity != null && requestEntity.getContentType() != null) {
381                 setRequestHeader("Content-Type", requestEntity.getContentType());
382             }
383         }
384     }
385     
386     /**
387      * Generates <tt>Content-Length</tt> or <tt>Transfer-Encoding: Chunked</tt>
388      * request header, as long as no <tt>Content-Length</tt> request header
389      * already exists.
390      *
391      * @param state current state of http requests
392      * @param conn the connection to use for I/O
393      *
394      * @throws IOException when errors occur reading or writing to/from the
395      *         connection
396      * @throws HttpException when a recoverable error occurs
397      */
398     protected void addContentLengthRequestHeader(HttpState state,
399                                                  HttpConnection conn)
400     throws IOException, HttpException {
401         LOG.trace("enter EntityEnclosingMethod.addContentLengthRequestHeader("
402                   + "HttpState, HttpConnection)");
403 
404         if ((getRequestHeader("content-length") == null) 
405             && (getRequestHeader("Transfer-Encoding") == null)) {
406             long len = getRequestContentLength();
407             if (len < 0) {
408                 if (getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
409                     addRequestHeader("Transfer-Encoding", "chunked");
410                 } else {
411                     throw new ProtocolException(getEffectiveVersion() + 
412                         " does not support chunk encoding");
413                 }
414             } else {
415                 addRequestHeader("Content-Length", String.valueOf(len));
416             }
417         }
418     }
419 
420     /**
421      * Sets the request body to be the specified inputstream.
422      *
423      * @param body Request body content as {@link java.io.InputStream}
424      * 
425      * @deprecated use {@link #setRequestEntity(RequestEntity)}
426      */
427     public void setRequestBody(InputStream body) {
428         LOG.trace("enter EntityEnclosingMethod.setRequestBody(InputStream)");
429         clearRequestBody();
430         this.requestStream = body;
431     }
432 
433     /**
434      * Sets the request body to be the specified string.
435      * The string will be submitted, using the encoding
436      * specified in the Content-Type request header.<br>
437      * Example: <code>setRequestHeader("Content-type", "text/xml; charset=UTF-8");</code><br>
438      * Would use the UTF-8 encoding.
439      * If no charset is specified, the 
440      * {@link org.apache.commons.httpclient.HttpConstants#DEFAULT_CONTENT_CHARSET default}
441      * content encoding is used (ISO-8859-1).
442      *
443      * @param body Request body content as a string
444      * 
445      * @deprecated use {@link #setRequestEntity(RequestEntity)}
446      */
447     public void setRequestBody(String body) {
448         LOG.trace("enter EntityEnclosingMethod.setRequestBody(String)");
449         clearRequestBody();
450         this.requestString = body;
451     }
452 
453     /**
454      * Writes the request body to the given {@link HttpConnection connection}.
455      *
456      * @param state the {@link HttpState state} information associated with this method
457      * @param conn the {@link HttpConnection connection} used to execute
458      *        this HTTP method
459      *
460      * @return <tt>true</tt>
461      *
462      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
463      *                     can be recovered from.
464      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
465      *                    cannot be recovered from.
466      */
467     protected boolean writeRequestBody(HttpState state, HttpConnection conn)
468     throws IOException, HttpException {
469         LOG.trace(
470             "enter EntityEnclosingMethod.writeRequestBody(HttpState, HttpConnection)");
471         
472         if (!hasRequestContent()) {
473             LOG.debug("Request body has not been specified");
474             return true;
475         }
476         if (this.requestEntity == null) {
477             this.requestEntity = generateRequestEntity(); 
478         }
479         if (requestEntity == null) {
480             LOG.debug("Request body is empty");
481             return true;
482         }
483 
484         long contentLength = getRequestContentLength();
485 
486         if ((this.repeatCount > 0) && !requestEntity.isRepeatable()) {
487             throw new ProtocolException(
488                 "Unbuffered entity enclosing request can not be repeated.");
489         }
490 
491         this.repeatCount++;
492 
493         OutputStream outstream = conn.getRequestOutputStream();
494         
495         if (contentLength < 0) {
496             outstream = new ChunkedOutputStream(outstream);
497         }
498         
499         requestEntity.writeRequest(outstream);
500         
501         // This is hardly the most elegant solution to closing chunked stream
502         if (outstream instanceof ChunkedOutputStream) {
503             ((ChunkedOutputStream) outstream).finish();
504         }
505         
506         outstream.flush();
507         
508         LOG.debug("Request body sent");
509         return true;
510     }
511 
512     /**
513      * Recycles the HTTP method so that it can be used again.
514      * Note that all of the instance variables will be reset
515      * once this method has been called. This method will also
516      * release the connection being used by this HTTP method.
517      * 
518      * @see #releaseConnection()
519      * 
520      * @deprecated no longer supported and will be removed in the future
521      *             version of HttpClient
522      */
523     public void recycle() {
524         LOG.trace("enter EntityEnclosingMethod.recycle()");
525         clearRequestBody();
526         this.requestContentLength = InputStreamRequestEntity.CONTENT_LENGTH_AUTO;
527         this.repeatCount = 0;
528         this.chunked = false;
529         super.recycle();
530     }
531 
532     /**
533      * @return Returns the requestEntity.
534      * 
535      * @since 3.0
536      */
537     public RequestEntity getRequestEntity() {
538         return generateRequestEntity();
539     }
540 
541     /**
542      * @param requestEntity The requestEntity to set.
543      * 
544      * @since 3.0
545      */
546     public void setRequestEntity(RequestEntity requestEntity) {
547         clearRequestBody();
548         this.requestEntity = requestEntity;
549     }
550 
551 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/ExpectContinueMethod.html100644 0 0 44056 10661532627 30560 0ustar 0 0 ExpectContinueMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/ExpectContinueMethod.java,v 1.13 2004/05/08 10:12:08 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods;
32  
33  import java.io.IOException;
34  import org.apache.commons.httpclient.HttpConnection;
35  import org.apache.commons.httpclient.HttpException;
36  import org.apache.commons.httpclient.HttpMethodBase;
37  import org.apache.commons.httpclient.HttpState;
38  import org.apache.commons.httpclient.HttpVersion;
39  import org.apache.commons.httpclient.params.HttpMethodParams;
40  import org.apache.commons.logging.Log;
41  import org.apache.commons.logging.LogFactory;
42  
43  /**
44   * <p>
45   * This abstract class serves as a foundation for all HTTP methods 
46   * that support 'Expect: 100-continue' handshake.
47   * </p>
48   * 
49   * <p>
50   * The purpose of the 100 (Continue) status (refer to section 10.1.1 
51   * of the RFC 2616 for more details) is to allow a client that is 
52   * sending a request message with a request body to determine if the 
53   * origin server is willing to accept the request (based on the request 
54   * headers) before the client sends the request body. In some cases,
55   * it might either be inappropriate or highly inefficient for the 
56   * client to send the body if the server will reject the message 
57   * without looking at the body.
58   * </p>
59   * 
60   * <p>
61   * 'Expect: 100-continue' handshake should be used with caution,
62   * as it may cause problems with HTTP servers and proxies that
63   * do not support HTTP/1.1 protocol.
64   * </p>
65   * 
66   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
67   *
68   * @since 2.0beta1
69   */
70  
71  public abstract class ExpectContinueMethod extends HttpMethodBase {
72      
73      /** LOG object for this class. */
74      private static final Log LOG = LogFactory.getLog(ExpectContinueMethod.class);
75  
76      /**
77       * No-arg constructor.
78       *
79       * @since 2.0
80       */
81      public ExpectContinueMethod() {
82          super();
83      }
84  
85      /**
86       * Constructor specifying a URI.
87       *
88       * @param uri either an absolute or relative URI
89       *
90       * @since 2.0
91       */
92      public ExpectContinueMethod(String uri) {
93          super(uri);
94      }
95  
96      /**
97       * <p>
98       * Returns <tt>true</tt> if the 'Expect: 100-Continue' handshake
99       * is activated. The purpose of the 'Expect: 100-Continue' 
100      * handshake to allow a client that is sending a request message 
101      * with a request body to determine if the origin server is 
102      * willing to accept the request (based on the request headers) 
103      * before the client sends the request body.
104      * </p>
105      * 
106      * @return <tt>true</tt> if 'Expect: 100-Continue' handshake is to
107      * be used, <tt>false</tt> otherwise.
108      * 
109      * @since 2.0beta1
110      * 
111      * @deprecated Use {@link HttpMethodParams}
112      * 
113      * @see #getParams()
114      * @see HttpMethodParams
115      * @see HttpMethodParams#USE_EXPECT_CONTINUE
116      */
117     public boolean getUseExpectHeader() {
118         return getParams().getBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
119     }
120 
121     /**
122      * <p>
123      * Activates 'Expect: 100-Continue' handshake. The purpose of 
124      * the 'Expect: 100-Continue' handshake to allow a client that is 
125      * sending a request message with a request body to determine if 
126      * the origin server is willing to accept the request (based on 
127      * the request headers) before the client sends the request body.
128      * </p>
129      * 
130      * <p>
131      * The use of the 'Expect: 100-continue' handshake can result in 
132      * noticable peformance improvement for entity enclosing requests
133      * (such as POST and PUT) that require the target server's 
134      * authentication.
135      * </p>
136      * 
137      * <p>
138      * 'Expect: 100-continue' handshake should be used with 
139      * caution, as it may cause problems with HTTP servers and 
140      * proxies that do not support HTTP/1.1 protocol.
141      * </p>
142      * 
143      * @param value boolean value
144      * 
145      * @since 2.0beta1
146      * 
147      * @deprecated Use {@link HttpMethodParams}
148      * 
149      * @see #getParams()
150      * @see HttpMethodParams
151      * @see HttpMethodParams#USE_EXPECT_CONTINUE
152      */
153     public void setUseExpectHeader(boolean value) {
154         getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, value);
155     }
156 
157     /**
158      * Returns <tt>true</tt> if there is a request body to be sent.
159      * 'Expect: 100-continue' handshake may not be used if request
160      * body is not present
161      * 
162      * @return boolean
163      * 
164      * @since 2.0beta1
165      */
166     protected abstract boolean hasRequestContent();
167 
168     /**
169      * Sets the <tt>Expect</tt> header if it has not already been set, 
170      * in addition to the "standard" set of headers.
171      *
172      * @param state the {@link HttpState state} information associated with this method
173      * @param conn the {@link HttpConnection connection} used to execute
174      *        this HTTP method
175      *
176      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
177      *                     can be recovered from.
178      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
179      *                    cannot be recovered from.
180      */
181     protected void addRequestHeaders(HttpState state, HttpConnection conn)
182     throws IOException, HttpException {
183         LOG.trace("enter ExpectContinueMethod.addRequestHeaders(HttpState, HttpConnection)");
184         
185         super.addRequestHeaders(state, conn);
186         // If the request is being retried, the header may already be present
187         boolean headerPresent = (getRequestHeader("Expect") != null);
188         // See if the expect header should be sent
189         // = HTTP/1.1 or higher
190         // = request body present
191 
192         if (getParams().isParameterTrue(HttpMethodParams.USE_EXPECT_CONTINUE) 
193         && getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1) 
194         && hasRequestContent())
195         {
196             if (!headerPresent) {
197                 setRequestHeader("Expect", "100-continue");
198             }
199         } else {
200             if (headerPresent) {
201                 removeRequestHeader("Expect");
202             }
203         }
204     }
205 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/FileRequestEntity.html100644 0 0 17521 10661532627 30104 0ustar 0 0 FileRequestEntity xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/methods/FileRequestEntity.java $
3    * $Revision: 486665 $
4    * $Date: 2006-12-13 15:19:07 +0100 (Wed, 13 Dec 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient.methods;
31  
32  import java.io.File;
33  import java.io.FileInputStream;
34  import java.io.IOException;
35  import java.io.InputStream;
36  import java.io.OutputStream;
37  
38  import org.apache.commons.httpclient.methods.RequestEntity;
39  
40  /**
41   * A RequestEntity that represents a File.
42   * 
43   * @since 3.1
44   */
45  public class FileRequestEntity implements RequestEntity {
46  
47      final File file;
48      final String contentType;
49      
50      public FileRequestEntity(final File file, final String contentType) {
51          super();
52          if (file == null) {
53              throw new IllegalArgumentException("File may not be null");
54          }
55          this.file = file;
56          this.contentType = contentType;
57      }
58      public long getContentLength() {
59          return this.file.length();
60      }
61  
62      public String getContentType() {
63          return this.contentType;
64      }
65  
66      public boolean isRepeatable() {
67          return true;
68      }
69  
70      public void writeRequest(final OutputStream out) throws IOException {
71          byte[] tmp = new byte[4096];
72          int i = 0;
73          InputStream instream = new FileInputStream(this.file);
74          try {
75              while ((i = instream.read(tmp)) >= 0) {
76                  out.write(tmp, 0, i);
77              }        
78          } finally {
79              instream.close();
80          }
81      }    
82      
83  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/GetMethod.html100644 0 0 27053 10661532627 26340 0ustar 0 0 GetMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/GetMethod.java,v 1.29 2004/06/13 20:22:19 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods;
32  
33  import org.apache.commons.httpclient.HttpMethodBase;
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  
37  /**
38   * Implements the HTTP GET method.
39   * <p>
40   * The HTTP GET method is defined in section 9.3 of
41   * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
42   * <blockquote>
43   * The GET method means retrieve whatever information (in the form of an
44   * entity) is identified by the Request-URI. If the Request-URI refers
45   * to a data-producing process, it is the produced data which shall be
46   * returned as the entity in the response and not the source text of the
47   * process, unless that text happens to be the output of the process.
48   * </blockquote>
49   * </p>
50   * <p>
51   * GetMethods will follow redirect requests from the http server by default.
52   * This behavour can be disabled by calling setFollowRedirects(false).</p>
53   *
54   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
55   * @author Sung-Gu Park
56   * @author Sean C. Sullivan
57   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
58   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
59   * 
60   * @version $Revision: 480424 $
61   * @since 1.0
62   */
63  public class GetMethod extends HttpMethodBase {
64  
65      // -------------------------------------------------------------- Constants
66  
67      /** Log object for this class. */
68      private static final Log LOG = LogFactory.getLog(GetMethod.class);
69  
70      // ----------------------------------------------------------- Constructors
71  
72      /**
73       * No-arg constructor.
74       * 
75       * @since 1.0
76       */
77      public GetMethod() {
78          setFollowRedirects(true);
79      }
80  
81      /**
82       * Constructor specifying a URI.
83       *
84       * @param uri either an absolute or relative URI
85       * 
86       * @since 1.0
87       */
88      public GetMethod(String uri) {
89          super(uri);
90          LOG.trace("enter GetMethod(String)");
91          setFollowRedirects(true);
92      }
93  
94      // --------------------------------------------------------- Public Methods
95  
96      /**
97       * Returns <tt>"GET"</tt>.
98       * 
99       * @return <tt>"GET"</tt>
100      * 
101      * @since 2.0
102      */
103     public String getName() {
104         return "GET";
105     }
106 
107     // ------------------------------------------------------------- Properties
108 
109     /**
110      * Recycles the HTTP method so that it can be used again.
111      * Note that all of the instance variables will be reset
112      * once this method has been called. This method will also
113      * release the connection being used by this HTTP method.
114      * 
115      * @see #releaseConnection()
116      * 
117      * @since 1.0
118      * 
119      * @deprecated no longer supported and will be removed in the future
120      *             version of HttpClient
121      */
122     public void recycle() {
123         LOG.trace("enter GetMethod.recycle()");
124 
125         super.recycle();
126         setFollowRedirects(true);
127     }
128 
129 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/HeadMethod.html100644 0 0 46330 10661532627 26461 0ustar 0 0 HeadMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/HeadMethod.java,v 1.29 2004/06/13 20:22:19 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods;
32  
33  import java.io.IOException;
34  
35  import org.apache.commons.httpclient.HttpConnection;
36  import org.apache.commons.httpclient.HttpException;
37  import org.apache.commons.httpclient.HttpMethodBase;
38  import org.apache.commons.httpclient.HttpState;
39  import org.apache.commons.httpclient.ProtocolException;
40  import org.apache.commons.httpclient.params.HttpMethodParams;
41  import org.apache.commons.logging.Log;
42  import org.apache.commons.logging.LogFactory;
43  
44  /**
45   * Implements the HTTP HEAD method.
46   * <p>
47   * The HTTP HEAD method is defined in section 9.4 of 
48   * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
49   * <blockquote>
50   * The HEAD method is identical to GET except that the server MUST NOT
51   * return a message-body in the response. The metainformation contained
52   * in the HTTP headers in response to a HEAD request SHOULD be identical
53   * to the information sent in response to a GET request. This method can
54   * be used for obtaining metainformation about the entity implied by the
55   * request without transferring the entity-body itself. This method is
56   * often used for testing hypertext links for validity, accessibility,
57   * and recent modification.
58   * </blockquote>
59   * </p>
60   * 
61   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
62   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
63   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
64   * @author <a href="mailto:oleg@ural.ru">oleg Kalnichevski</a>
65   *
66   * @version $Revision: 480424 $
67   * @since 1.0
68   */
69  public class HeadMethod extends HttpMethodBase {
70      //~ Static variables/initializers
71  
72      /** Log object for this class. */
73      private static final Log LOG = LogFactory.getLog(HeadMethod.class);
74  
75      //~ Constructors
76  
77      /**
78       * No-arg constructor.
79       * 
80       * @since 1.0
81       */
82      public HeadMethod() {
83          setFollowRedirects(true);
84      }
85  
86      /**
87       * Constructor specifying a URI.
88       *
89       * @param uri either an absolute or relative URI
90       * 
91       * @since 1.0
92       */
93      public HeadMethod(String uri) {
94          super(uri);
95          setFollowRedirects(true);
96      }
97  
98      //~ Methods
99  
100     /**
101      * Returns <tt>"HEAD"</tt>.
102      * 
103      * @return <tt>"HEAD"</tt>
104      * 
105      * @since 2.0
106      */
107     public String getName() {
108         return "HEAD";
109     }
110 
111     /**
112      * Recycles the HTTP method so that it can be used again.
113      * Note that all of the instance variables will be reset
114      * once this method has been called. This method will also
115      * release the connection being used by this HTTP method.
116      * 
117      * @see #releaseConnection()
118      * 
119      * @since 1.0
120      * 
121      * @deprecated no longer supported and will be removed in the future
122      *             version of HttpClient
123      */
124     public void recycle() {
125         super.recycle();
126         setFollowRedirects(true);
127     }
128 
129     /**
130      * Overrides {@link HttpMethodBase} method to <i>not</i> read a response
131      * body, despite the presence of a <tt>Content-Length</tt> or
132      * <tt>Transfer-Encoding</tt> header.
133      * 
134      * @param state the {@link HttpState state} information associated with this method
135      * @param conn the {@link HttpConnection connection} used to execute
136      *        this HTTP method
137      *
138      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
139      *                     can be recovered from.
140      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
141      *                    cannot be recovered from.
142      *
143      * @see #readResponse
144      * @see #processResponseBody
145      * 
146      * @since 2.0
147      */
148     protected void readResponseBody(HttpState state, HttpConnection conn)
149     throws HttpException, IOException {
150         LOG.trace(
151             "enter HeadMethod.readResponseBody(HttpState, HttpConnection)");
152         
153         int bodyCheckTimeout = 
154             getParams().getIntParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, -1);
155 
156         if (bodyCheckTimeout < 0) {
157             responseBodyConsumed();
158         } else {
159             if (LOG.isDebugEnabled()) {
160                 LOG.debug("Check for non-compliant response body. Timeout in " 
161                  + bodyCheckTimeout + " ms");    
162             }
163             boolean responseAvailable = false;
164             try {
165                 responseAvailable = conn.isResponseAvailable(bodyCheckTimeout);
166             } catch (IOException e) {
167                 LOG.debug("An IOException occurred while testing if a response was available,"
168                     + " we will assume one is not.", 
169                     e);
170                 responseAvailable = false;
171             }
172             if (responseAvailable) {
173                 if (getParams().isParameterTrue(HttpMethodParams.REJECT_HEAD_BODY)) {
174                     throw new ProtocolException(
175                         "Body content may not be sent in response to HTTP HEAD request");
176                 } else {
177                     LOG.warn("Body content returned in response to HTTP HEAD");    
178                 }
179                 super.readResponseBody(state, conn);
180             }
181         }
182 
183     }
184     
185     /**
186      * Returns non-compliant response body check timeout.
187      * 
188      * @return The period of time in milliseconds to wait for a response 
189      *         body from a non-compliant server. <tt>-1</tt> returned when 
190      *         non-compliant response body check is disabled
191      * 
192      * @deprecated Use {@link HttpMethodParams}
193      * 
194      * @see #getParams()
195      * @see HttpMethodParams
196      * @see HttpMethodParams#HEAD_BODY_CHECK_TIMEOUT
197      */
198     public int getBodyCheckTimeout() {
199         return getParams().getIntParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, -1);
200     }
201 
202     /**
203      * Sets non-compliant response body check timeout.
204      * 
205      * @param timeout The period of time in milliseconds to wait for a response 
206      *         body from a non-compliant server. <tt>-1</tt> can be used to 
207      *         disable non-compliant response body check
208      *  
209      * @deprecated Use {@link HttpMethodParams}
210      * 
211      * @see #getParams()
212      * @see HttpMethodParams
213      * @see HttpMethodParams#HEAD_BODY_CHECK_TIMEOUT
214      */
215     public void setBodyCheckTimeout(int timeout) {
216         getParams().setIntParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, timeout);
217     }
218 
219 }

././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/InputStreamRequestEntity.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/InputStreamRequestEntity.html100644 0 0 43254 10661532627 31502 0ustar 0 0 InputStreamRequestEntity xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/InputStreamRequestEntity.java,v 1.4 2004/05/17 21:46:03 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32  package org.apache.commons.httpclient.methods;
33  
34  import java.io.ByteArrayOutputStream;
35  import java.io.IOException;
36  import java.io.InputStream;
37  import java.io.OutputStream;
38  
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  
42  /**
43   * A RequestEntity that contains an InputStream.
44   * 
45   * @since 3.0
46   */
47  public class InputStreamRequestEntity implements RequestEntity {
48  
49      /**
50       * The content length will be calculated automatically. This implies
51       * buffering of the content.
52       */
53      public static final int CONTENT_LENGTH_AUTO = -2;
54      
55      private static final Log LOG = LogFactory.getLog(InputStreamRequestEntity.class);
56      
57      private long contentLength;
58      
59      private InputStream content;
60  
61      /** The buffered request body, if any. */
62      private byte[] buffer = null;
63      
64      /** The content type */
65      private String contentType;
66  
67      /**
68       * Creates a new InputStreamRequestEntity with the given content and a content type of
69       * {@link #CONTENT_LENGTH_AUTO}.
70       * @param content The content to set.
71       */
72      public InputStreamRequestEntity(InputStream content) {
73          this(content, null);
74      }
75      
76      /**
77       * Creates a new InputStreamRequestEntity with the given content, content type, and a 
78       * content length of {@link #CONTENT_LENGTH_AUTO}.
79       * @param content The content to set.
80       * @param contentType The type of the content, or <code>null</code>.
81       */
82      public InputStreamRequestEntity(InputStream content, String contentType) {
83          this(content, CONTENT_LENGTH_AUTO, contentType);
84      }
85  
86      /**
87       * Creates a new InputStreamRequestEntity with the given content and content length.
88       * @param content The content to set.
89       * @param contentLength The content size in bytes or a negative number if not known.
90       *  If {@link #CONTENT_LENGTH_AUTO} is given the content will be buffered in order to 
91       *  determine its size when {@link #getContentLength()} is called.
92       */
93      public InputStreamRequestEntity(InputStream content, long contentLength) {
94          this(content, contentLength, null);
95      }
96      
97      /**
98       * Creates a new InputStreamRequestEntity with the given content, content length, and 
99       * content type.
100      * @param content The content to set.
101      * @param contentLength The content size in bytes or a negative number if not known.
102      *  If {@link #CONTENT_LENGTH_AUTO} is given the content will be buffered in order to 
103      *  determine its size when {@link #getContentLength()} is called.
104      * @param contentType The type of the content, or <code>null</code>.
105      */
106     public InputStreamRequestEntity(InputStream content, long contentLength, String contentType) {
107         if (content == null) {
108             throw new IllegalArgumentException("The content cannot be null");
109         }
110         this.content = content;
111         this.contentLength = contentLength;
112         this.contentType = contentType;
113     }
114 
115     /* (non-Javadoc)
116      * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType()
117      */
118     public String getContentType() {
119         return contentType;
120     }
121     
122     /**
123      * Buffers request body input stream.
124      */
125     private void bufferContent() {
126 
127         if (this.buffer != null) {
128             // Already been buffered
129             return;
130         }
131         if (this.content != null) {
132             try {
133                 ByteArrayOutputStream tmp = new ByteArrayOutputStream();
134                 byte[] data = new byte[4096];
135                 int l = 0;
136                 while ((l = this.content.read(data)) >= 0) {
137                     tmp.write(data, 0, l);
138                 }
139                 this.buffer = tmp.toByteArray();
140                 this.content = null;
141                 this.contentLength = buffer.length;
142             } catch (IOException e) {
143                 LOG.error(e.getMessage(), e);
144                 this.buffer = null;
145                 this.content = null;
146                 this.contentLength = 0;
147             }
148         }
149     }
150     
151     /**
152      * Tests if this method is repeatable.  Only <code>true</code> if the content has been
153      * buffered.
154      * 
155      * @see #getContentLength()
156      */
157     public boolean isRepeatable() {
158         return buffer != null;
159     }
160 
161     /* (non-Javadoc)
162      * @see org.apache.commons.httpclient.RequestEntity#writeRequest(java.io.OutputStream)
163      */
164     public void writeRequest(OutputStream out) throws IOException {
165         
166         if (content != null) {
167             byte[] tmp = new byte[4096];
168             int total = 0;
169             int i = 0;
170             while ((i = content.read(tmp)) >= 0) {
171                 out.write(tmp, 0, i);
172                 total += i;
173             }        
174         } else if (buffer != null) {
175             out.write(buffer);
176         } else {
177             throw new IllegalStateException("Content must be set before entity is written");
178         }
179     }
180 
181     /**
182      * Gets the content length.  If the content length has not been set, the content will be
183      * buffered to determine the actual content length.
184      */
185     public long getContentLength() {
186         if (contentLength == CONTENT_LENGTH_AUTO && buffer == null) {
187             bufferContent();
188         }
189         return contentLength;
190     }
191 
192     /**
193      * @return Returns the content.
194      */
195     public InputStream getContent() {
196         return content;
197     }
198 
199 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/MultipartPostMethod.html100644 0 0 74656 10661532627 30463 0ustar 0 0 MultipartPostMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/MultipartPostMethod.java,v 1.27 2004/10/06 03:39:59 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods;
32  
33  import java.io.File;
34  import java.io.FileNotFoundException;
35  import java.io.IOException;
36  import java.io.OutputStream;
37  import java.util.ArrayList;
38  import java.util.List;
39  
40  import org.apache.commons.httpclient.HttpConnection;
41  import org.apache.commons.httpclient.HttpException;
42  import org.apache.commons.httpclient.HttpState;
43  import org.apache.commons.httpclient.methods.multipart.FilePart;
44  import org.apache.commons.httpclient.methods.multipart.Part;
45  import org.apache.commons.httpclient.methods.multipart.StringPart;
46  import org.apache.commons.logging.Log;
47  import org.apache.commons.logging.LogFactory;
48  
49  /**
50   * Implements the HTTP multipart POST method.
51   * <p>
52   * The HTTP multipart POST method is defined in section 3.3 of
53   * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC1867</a>:
54   * <blockquote>
55   * The media-type multipart/form-data follows the rules of all multipart
56   * MIME data streams as outlined in RFC 1521. The multipart/form-data contains 
57   * a series of parts. Each part is expected to contain a content-disposition 
58   * header where the value is "form-data" and a name attribute specifies 
59   * the field name within the form, e.g., 'content-disposition: form-data; 
60   * name="xxxxx"', where xxxxx is the field name corresponding to that field.
61   * Field names originally in non-ASCII character sets may be encoded using 
62   * the method outlined in RFC 1522.
63   * </blockquote>
64   * </p>
65   * <p>
66   *
67   * @author <a href="mailto:mattalbright@yahoo.com">Matthew Albright</a>
68   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
69   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
70   * @author <a href="mailto:mdiggory@latte.harvard.edu">Mark Diggory</a>
71   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
72   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
73   *
74   * @since 2.0
75   * 
76   * @deprecated Use {@link org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity}
77   * in conjunction with {@link org.apache.commons.httpclient.methods.PostMethod} instead.
78   */
79  public class MultipartPostMethod extends ExpectContinueMethod {
80  
81      /** The Content-Type for multipart/form-data. */
82      public static final String MULTIPART_FORM_CONTENT_TYPE = 
83          "multipart/form-data";
84  
85      /** Log object for this class. */
86      private static final Log LOG = LogFactory.getLog(MultipartPostMethod.class);
87  
88      /** The parameters for this method */
89      private final List parameters = new ArrayList();
90  
91      /**
92       * No-arg constructor.
93       */
94      public MultipartPostMethod() {
95          super();
96      }
97  
98      /**
99       * Constructor specifying a URI.
100      *
101      * @param uri either an absolute or relative URI
102      */
103     public MultipartPostMethod(String uri) {
104         super(uri);
105     }
106 
107     /**
108      * Returns <tt>true</tt> 
109      * 
110      * @return <tt>true</tt>
111      * 
112      * @since 2.0beta1
113      */
114     protected boolean hasRequestContent() {
115         return true;
116     }
117 
118     /**
119      * Returns <tt>"POST"</tt>.
120      * @return <tt>"POST"</tt>
121      */
122     public String getName() {
123         return "POST";
124     }
125 
126     /**
127      * Adds a text field part
128      * 
129      * @param parameterName The name of the parameter.
130      * @param parameterValue The value of the parameter.
131      */
132     public void addParameter(String parameterName, String parameterValue) {
133         LOG.trace("enter addParameter(String parameterName, String parameterValue)");
134         Part param = new StringPart(parameterName, parameterValue);
135         parameters.add(param);
136     }
137 
138     /**
139      * Adds a binary file part
140      * 
141      * @param parameterName The name of the parameter
142      * @param parameterFile The name of the file.
143      * @throws FileNotFoundException If the file cannot be found.
144      */
145     public void addParameter(String parameterName, File parameterFile) 
146     throws FileNotFoundException {
147         LOG.trace("enter MultipartPostMethod.addParameter(String parameterName, "
148             + "File parameterFile)");
149         Part param = new FilePart(parameterName, parameterFile);
150         parameters.add(param);
151     }
152 
153     /**
154      * Adds a binary file part with the given file name
155      * 
156      * @param parameterName The name of the parameter
157      * @param fileName The file name
158      * @param parameterFile The file
159      * @throws FileNotFoundException If the file cannot be found.
160      */
161     public void addParameter(String parameterName, String fileName, File parameterFile) 
162     throws FileNotFoundException {
163         LOG.trace("enter MultipartPostMethod.addParameter(String parameterName, "
164             + "String fileName, File parameterFile)");
165         Part param = new FilePart(parameterName, fileName, parameterFile);
166         parameters.add(param);
167     }
168         
169     /**
170      * Adds a part.
171      * 
172      * @param part The part to add.
173      */
174     public void addPart (final Part part) {
175         LOG.trace("enter addPart(Part part)");
176         parameters.add(part);
177     }
178 
179     /**
180      * Returns all parts.
181      * 
182      * @return an array of containing all parts
183      */
184     public Part[] getParts() {
185         return (Part[]) parameters.toArray(new Part[parameters.size()]);
186     }
187 
188     /**
189      * Adds a <tt>Content-Length</tt> request header, as long as no 
190      * <tt>Content-Length</tt> request header already exists.
191      *
192      * @param state current state of http requests
193      * @param conn the connection to use for I/O
194      *
195      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
196      *                     can be recovered from.
197      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
198      *                    cannot be recovered from.
199      * 
200      * @since 3.0
201      */
202     protected void addContentLengthRequestHeader(HttpState state,
203                                                  HttpConnection conn)
204     throws IOException, HttpException {
205         LOG.trace("enter EntityEnclosingMethod.addContentLengthRequestHeader("
206                   + "HttpState, HttpConnection)");
207 
208         if (getRequestHeader("Content-Length") == null) { 
209             long len = getRequestContentLength();
210             addRequestHeader("Content-Length", String.valueOf(len));
211         }
212         removeRequestHeader("Transfer-Encoding");
213     }
214 
215     /**
216      * Adds a <tt>Content-Type</tt> request header.
217      *
218      * @param state current state of http requests
219      * @param conn the connection to use for I/O
220      *
221      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
222      *                     can be recovered from.
223      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
224      *                    cannot be recovered from.
225      * 
226      * @since 3.0
227      */
228     protected void addContentTypeRequestHeader(HttpState state,
229                                                  HttpConnection conn)
230     throws IOException, HttpException {
231         LOG.trace("enter EntityEnclosingMethod.addContentTypeRequestHeader("
232                   + "HttpState, HttpConnection)");
233 
234         if (!parameters.isEmpty()) {
235             StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
236             if (Part.getBoundary() != null) {
237                 buffer.append("; boundary=");
238                 buffer.append(Part.getBoundary());
239             }
240             setRequestHeader("Content-Type", buffer.toString());
241         }
242     }
243 
244     /**
245      * Populates the request headers map to with additional 
246      * {@link org.apache.commons.httpclient.Header headers} to be submitted to 
247      * the given {@link HttpConnection}.
248      *
249      * <p>
250      * This implementation adds tt>Content-Length</tt> and <tt>Content-Type</tt>
251      * headers, when appropriate.
252      * </p>
253      *
254      * <p>
255      * Subclasses may want to override this method to to add additional
256      * headers, and may choose to invoke this implementation (via
257      * <tt>super</tt>) to add the "standard" headers.
258      * </p>
259      *
260      * @param state the {@link HttpState state} information associated with this method
261      * @param conn the {@link HttpConnection connection} used to execute
262      *        this HTTP method
263      *
264      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
265      *                     can be recovered from.
266      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
267      *                    cannot be recovered from.
268      *
269      * @see #writeRequestHeaders
270      */
271     protected void addRequestHeaders(HttpState state, HttpConnection conn) 
272     throws IOException, HttpException {
273         LOG.trace("enter MultipartPostMethod.addRequestHeaders(HttpState state, "
274             + "HttpConnection conn)");
275         super.addRequestHeaders(state, conn);
276         addContentLengthRequestHeader(state, conn);
277         addContentTypeRequestHeader(state, conn);
278     }
279 
280     /**
281      * Writes the request body to the given {@link HttpConnection connection}.
282      *
283      * @param state the {@link HttpState state} information associated with this method
284      * @param conn the {@link HttpConnection connection} used to execute
285      *        this HTTP method
286      *
287      * @return <tt>true</tt>
288      *
289      * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
290      *                     can be recovered from.
291      * @throws HttpException  if a protocol exception occurs. Usually protocol exceptions 
292      *                    cannot be recovered from.
293      */
294     protected boolean writeRequestBody(HttpState state, HttpConnection conn) 
295     throws IOException, HttpException {
296         LOG.trace("enter MultipartPostMethod.writeRequestBody(HttpState state, "
297             + "HttpConnection conn)");
298         OutputStream out = conn.getRequestOutputStream();
299         Part.sendParts(out, getParts());
300         return true;
301     }
302 
303     /**
304      * <p>Return the length of the request body.</p>
305      *
306      * <p>Once this method has been invoked, the request parameters cannot be
307      * altered until the method is {@link #recycle recycled}.</p>
308      * 
309      * @return The request content length.
310      */
311     protected long getRequestContentLength() throws IOException {
312         LOG.trace("enter MultipartPostMethod.getRequestContentLength()");
313         return Part.getLengthOfParts(getParts());
314     }
315 
316 
317     /**
318      * Recycles the HTTP method so that it can be used again.
319      * Note that all of the instance variables will be reset
320      * once this method has been called. This method will also
321      * release the connection being used by this HTTP method.
322      * 
323      * @see #releaseConnection()
324      * 
325      * @deprecated no longer supported and will be removed in the future
326      *             version of HttpClient
327      */
328     public void recycle() {
329         LOG.trace("enter MultipartPostMethod.recycle()");
330         super.recycle();
331         parameters.clear();
332     }
333 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/OptionsMethod.html100644 0 0 37660 10661532627 27261 0ustar 0 0 OptionsMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/OptionsMethod.java,v 1.15 2004/04/18 23:51:37 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods;
32  
33  import org.apache.commons.httpclient.Header;
34  import org.apache.commons.httpclient.HttpConnection;
35  import org.apache.commons.httpclient.HttpMethodBase;
36  import org.apache.commons.httpclient.HttpState;
37  
38  import org.apache.commons.logging.LogFactory;
39  import org.apache.commons.logging.Log;
40  import java.util.Enumeration;
41  import java.util.StringTokenizer;
42  import java.util.Vector;
43  
44  
45  /**
46   * Implements the HTTP OPTIONS method.
47   * <p>
48   * The HTTP OPTIONS method is defined in section 9.2 of 
49   * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
50   * <blockquote>
51   *  The OPTIONS method represents a request for information about the
52   *  communication options available on the request/response chain
53   *  identified by the Request-URI. This method allows the client to
54   *  determine the options and/or requirements associated with a resource,
55   *  or the capabilities of a server, without implying a resource action
56   *  or initiating a resource retrieval.
57   * </blockquote>
58   * </p>
59   *
60   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
61   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
62   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
63   *
64   * @version $Revision: 480424 $
65   * @since 1.0
66   */
67  public class OptionsMethod
68      extends HttpMethodBase {
69  
70  
71      // --------------------------------------------------------- Class Variables
72  
73      /** Log object for this class. */
74      private static final Log LOG = LogFactory.getLog(OptionsMethod.class);
75  
76      // ----------------------------------------------------------- Constructors
77  
78  
79      /**
80       * Method constructor.
81       *
82       * @since 1.0
83       */
84      public OptionsMethod() {
85      }
86  
87  
88      /**
89       * Constructor specifying a URI.
90       *
91       * @param uri either an absolute or relative URI
92       *
93       * @since 1.0
94       */
95      public OptionsMethod(String uri) {
96          super(uri);
97      }
98  
99  
100     // ----------------------------------------------------- Instance Variables
101 
102 
103     /**
104      * Methods allowed.
105      */
106     private Vector methodsAllowed = new Vector();
107 
108 
109     // --------------------------------------------------------- Public Methods
110 
111     /**
112      * Get the name.
113      * @return "OPTIONS"
114      * @since 2.0
115      */
116     public String getName() {
117         return "OPTIONS";
118     }
119 
120 
121     /**
122      * Is the specified method allowed ?
123      * 
124      * @param method The method to check.
125      * @return true if the specified method is allowed.
126      * @since 1.0
127      */
128     public boolean isAllowed(String method) {
129         checkUsed();
130         return methodsAllowed.contains(method);
131     }
132 
133 
134     /**
135      * Get a list of allowed methods.
136      * @return An enumeration of all the allowed methods.
137      *
138      * @since 1.0
139      */
140     public Enumeration getAllowedMethods() {
141         checkUsed();
142         return methodsAllowed.elements();
143     }
144 
145 
146     // ----------------------------------------------------- HttpMethod Methods
147 
148     /**
149      * <p>
150      * This implementation will parse the <tt>Allow</tt> header to obtain 
151      * the set of methods supported by the resource identified by the Request-URI.
152      * </p>
153      *
154      * @param state the {@link HttpState state} information associated with this method
155      * @param conn the {@link HttpConnection connection} used to execute
156      *        this HTTP method
157      *
158      * @see #readResponse
159      * @see #readResponseHeaders
160      * @since 2.0
161      */
162     protected void processResponseHeaders(HttpState state, HttpConnection conn) {
163         LOG.trace("enter OptionsMethod.processResponseHeaders(HttpState, HttpConnection)");
164 
165         Header allowHeader = getResponseHeader("allow");
166         if (allowHeader != null) {
167             String allowHeaderValue = allowHeader.getValue();
168             StringTokenizer tokenizer =
169                 new StringTokenizer(allowHeaderValue, ",");
170             while (tokenizer.hasMoreElements()) {
171                 String methodAllowed =
172                     tokenizer.nextToken().trim().toUpperCase();
173                 methodsAllowed.addElement(methodAllowed);
174             }
175         }
176     }
177 
178     /**
179      * Return true if the method needs a content-length header in the request.
180      *
181      * @return true if a content-length header will be expected by the server
182      *
183      * @since 1.0
184      * 
185      * @deprecated only entity enclosing methods set content length header
186      */
187     public boolean needContentLength() {
188         return false;
189     }
190 
191 
192 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/PostMethod.html100644 0 0 105150 10661532627 26561 0ustar 0 0 PostMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/PostMethod.java,v 1.58 2004/08/08 12:50:09 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods;
32  
33  import java.util.Iterator;
34  import java.util.Vector;
35  
36  import org.apache.commons.httpclient.NameValuePair;
37  import org.apache.commons.httpclient.util.EncodingUtil;
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  
41  /**
42   * Implements the HTTP POST method.
43   * <p>
44   * The HTTP POST method is defined in section 9.5 of 
45   * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
46   * <blockquote>
47   * The POST method is used to request that the origin server accept the entity
48   * enclosed in the request as a new subordinate of the resource identified by
49   * the Request-URI in the Request-Line. POST is designed to allow a uniform
50   * method to cover the following functions:
51   * <ul>
52   *   <li>Annotation of existing resources</li>
53   *   <li>Posting a message to a bulletin board, newsgroup, mailing list, or 
54   *     similar group of articles</li>
55   *   <li>Providing a block of data, such as the result of submitting a form,
56   *     to a data-handling process</li>
57   *   <li>Extending a database through an append operation</li>
58   * </ul>
59   * </blockquote>
60   * </p>
61   *
62   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
63   * @author <a href="mailto:dsale@us.britannica.com">Doug Sale</a>
64   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
65   * @author Ortwin Gl???ck
66   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
67   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
68   *
69   * @version $Revision: 480424 $
70   * @since 1.0
71   */
72  public class PostMethod extends EntityEnclosingMethod {
73      // -------------------------------------------------------------- Constants
74  
75      /** Log object for this class. */
76      private static final Log LOG = LogFactory.getLog(PostMethod.class);
77  
78      /** The Content-Type for www-form-urlencoded. */
79      public static final String FORM_URL_ENCODED_CONTENT_TYPE = 
80          "application/x-www-form-urlencoded";
81  
82      /** 
83       * The buffered request body consisting of <code>NameValuePair</code>s. 
84       */
85      private Vector params = new Vector();
86  
87      // ----------------------------------------------------------- Constructors
88  
89      /**
90       * No-arg constructor.
91       *
92       * @since 1.0
93       */
94      public PostMethod() {
95          super();
96      }
97  
98      /**
99       * Constructor specifying a URI.
100      *
101      * @param uri either an absolute or relative URI
102      *
103      * @since 1.0
104      */
105     public PostMethod(String uri) {
106         super(uri);
107     }
108 
109     // ----------------------------------------------------- Instance Methods
110 
111     /**
112      * Returns <tt>"POST"</tt>.
113      *
114      * @return <tt>"POST"</tt>
115      *
116      * @since 2.0
117      */
118     public String getName() {
119         return "POST";
120     }
121 
122 
123     /**
124      * Returns <tt>true</tt> if there is a request body to be sent.
125      * 
126      * <P>This method must be overwritten by sub-classes that implement
127      * alternative request content input methods
128      * </p>
129      * 
130      * @return boolean
131      * 
132      * @since 2.0beta1
133      */
134     protected boolean hasRequestContent() {
135         LOG.trace("enter PostMethod.hasRequestContent()");
136         if (!this.params.isEmpty()) {
137             return true;
138         } else {
139             return super.hasRequestContent();
140         }
141     }
142 
143     /**
144      * Clears request body.
145      * 
146      * <p>This method must be overwritten by sub-classes that implement
147      * alternative request content input methods</p>
148      * 
149      * @since 2.0beta1
150      */
151     protected void clearRequestBody() {
152         LOG.trace("enter PostMethod.clearRequestBody()");
153         this.params.clear();
154         super.clearRequestBody();
155     }
156 
157     /**
158      * Generates a request entity from the post parameters, if present.  Calls
159      * {@link EntityEnclosingMethod#generateRequestBody()} if parameters have not been set.
160      * 
161      * @since 3.0
162      */
163     protected RequestEntity generateRequestEntity() {
164         if (!this.params.isEmpty()) {
165             // Use a ByteArrayRequestEntity instead of a StringRequestEntity.
166             // This is to avoid potential encoding issues.  Form url encoded strings
167             // are ASCII by definition but the content type may not be.  Treating the content
168             // as bytes allows us to keep the current charset without worrying about how
169             // this charset will effect the encoding of the form url encoded string.
170             String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet());
171             ByteArrayRequestEntity entity = new ByteArrayRequestEntity(
172                 EncodingUtil.getAsciiBytes(content),
173                 FORM_URL_ENCODED_CONTENT_TYPE
174             );
175             return entity;
176         } else {
177             return super.generateRequestEntity();
178         }
179     }
180     
181     /**
182      * Sets the value of parameter with parameterName to parameterValue. This method
183      * does not preserve the initial insertion order.
184      *
185      * @param parameterName name of the parameter
186      * @param parameterValue value of the parameter
187      *
188      * @since 2.0
189      */
190     public void setParameter(String parameterName, String parameterValue) {
191         LOG.trace("enter PostMethod.setParameter(String, String)");
192 
193         removeParameter(parameterName);
194         addParameter(parameterName, parameterValue);
195     }
196 
197     /**
198      * Gets the parameter of the specified name. If there exists more than one
199      * parameter with the name paramName, then only the first one is returned.
200      *
201      * @param paramName name of the parameter
202      *
203      * @return If a parameter exists with the name argument, the coresponding
204      *         NameValuePair is returned.  Otherwise null.
205      *
206      * @since 2.0
207      * 
208      */
209     public NameValuePair getParameter(String paramName) {
210         LOG.trace("enter PostMethod.getParameter(String)");
211 
212         if (paramName == null) {
213             return null;
214         }
215 
216         Iterator iter = this.params.iterator();
217 
218         while (iter.hasNext()) {
219             NameValuePair parameter = (NameValuePair) iter.next();
220 
221             if (paramName.equals(parameter.getName())) {
222                 return parameter;
223             }
224         }
225         return null;
226     }
227 
228     /**
229      * Gets the parameters currently added to the PostMethod. If there are no
230      * parameters, a valid array is returned with zero elements. The returned
231      * array object contains an array of pointers to  the internal data
232      * members.
233      *
234      * @return An array of the current parameters
235      *
236      * @since 2.0
237      * 
238      */
239     public NameValuePair[] getParameters() {
240         LOG.trace("enter PostMethod.getParameters()");
241 
242         int numPairs = this.params.size();
243         Object[] objectArr = this.params.toArray();
244         NameValuePair[] nvPairArr = new NameValuePair[numPairs];
245 
246         for (int i = 0; i < numPairs; i++) {
247             nvPairArr[i] = (NameValuePair) objectArr[i];
248         }
249 
250         return nvPairArr;
251     }
252 
253     /**
254      * Adds a new parameter to be used in the POST request body.
255      *
256      * @param paramName The parameter name to add.
257      * @param paramValue The parameter value to add.
258      *
259      * @throws IllegalArgumentException if either argument is null
260      *
261      * @since 1.0
262      */
263     public void addParameter(String paramName, String paramValue) 
264     throws IllegalArgumentException {
265         LOG.trace("enter PostMethod.addParameter(String, String)");
266 
267         if ((paramName == null) || (paramValue == null)) {
268             throw new IllegalArgumentException(
269                 "Arguments to addParameter(String, String) cannot be null");
270         }
271         super.clearRequestBody();
272         this.params.add(new NameValuePair(paramName, paramValue));
273     }
274 
275     /**
276      * Adds a new parameter to be used in the POST request body.
277      *
278      * @param param The parameter to add.
279      *
280      * @throws IllegalArgumentException if the argument is null or contains
281      *         null values
282      *
283      * @since 2.0
284      */
285     public void addParameter(NameValuePair param) 
286     throws IllegalArgumentException {
287         LOG.trace("enter PostMethod.addParameter(NameValuePair)");
288 
289         if (param == null) {
290             throw new IllegalArgumentException("NameValuePair may not be null");
291         }
292         addParameter(param.getName(), param.getValue());
293     }
294 
295     /**
296      * Adds an array of parameters to be used in the POST request body. Logs a
297      * warning if the parameters argument is null.
298      *
299      * @param parameters The array of parameters to add.
300      *
301      * @since 2.0
302      */
303     public void addParameters(NameValuePair[] parameters) {
304         LOG.trace("enter PostMethod.addParameters(NameValuePair[])");
305 
306         if (parameters == null) {
307             LOG.warn("Attempt to addParameters(null) ignored");
308         } else {
309             super.clearRequestBody();
310             for (int i = 0; i < parameters.length; i++) {
311                 this.params.add(parameters[i]);
312             }
313         }
314     }
315 
316     /**
317      * Removes all parameters with the given paramName. If there is more than
318      * one parameter with the given paramName, all of them are removed.  If
319      * there is just one, it is removed.  If there are none, then the request
320      * is ignored.
321      *
322      * @param paramName The parameter name to remove.
323      *
324      * @return true if at least one parameter was removed
325      *
326      * @throws IllegalArgumentException When the parameter name passed is null
327      *
328      * @since 2.0
329      */
330     public boolean removeParameter(String paramName) 
331     throws IllegalArgumentException {
332         LOG.trace("enter PostMethod.removeParameter(String)");
333 
334         if (paramName == null) {
335             throw new IllegalArgumentException(
336                 "Argument passed to removeParameter(String) cannot be null");
337         }
338         boolean removed = false;
339         Iterator iter = this.params.iterator();
340 
341         while (iter.hasNext()) {
342             NameValuePair pair = (NameValuePair) iter.next();
343 
344             if (paramName.equals(pair.getName())) {
345                 iter.remove();
346                 removed = true;
347             }
348         }
349         return removed;
350     }
351 
352     /**
353      * Removes all parameter with the given paramName and paramValue. If there
354      * is more than one parameter with the given paramName, only one is
355      * removed.  If there are none, then the request is ignored.
356      *
357      * @param paramName The parameter name to remove.
358      * @param paramValue The parameter value to remove.
359      *
360      * @return true if a parameter was removed.
361      *
362      * @throws IllegalArgumentException when param name or value are null
363      *
364      * @since 2.0
365      */
366     public boolean removeParameter(String paramName, String paramValue) 
367     throws IllegalArgumentException {
368         LOG.trace("enter PostMethod.removeParameter(String, String)");
369 
370         if (paramName == null) {
371             throw new IllegalArgumentException("Parameter name may not be null");
372         }
373         if (paramValue == null) {
374             throw new IllegalArgumentException("Parameter value may not be null");
375         }
376 
377         Iterator iter = this.params.iterator();
378 
379         while (iter.hasNext()) {
380             NameValuePair pair = (NameValuePair) iter.next();
381 
382             if (paramName.equals(pair.getName())
383                 && paramValue.equals(pair.getValue())) {
384                 iter.remove();
385                 return true;
386             }
387         }
388 
389         return false;
390     }
391 
392     /**
393      * Sets an array of parameters to be used in the POST request body
394      *
395      * @param parametersBody The array of parameters to add.
396      *
397      * @throws IllegalArgumentException when param parameters are null
398      * 
399      * @since 2.0beta1
400      */
401     public void setRequestBody(NameValuePair[] parametersBody)
402     throws IllegalArgumentException {
403         LOG.trace("enter PostMethod.setRequestBody(NameValuePair[])");
404 
405         if (parametersBody == null) {
406             throw new IllegalArgumentException("Array of parameters may not be null");
407         }
408         clearRequestBody();
409         addParameters(parametersBody);
410     }
411 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/PutMethod.html100644 0 0 21045 10661532627 26364 0ustar 0 0 PutMethod xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/PutMethod.java,v 1.26 2004/04/18 23:51:37 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods;
32  
33  /**
34   * Implements the HTTP PUT method.
35   * <p>
36   * The HTTP PUT method is defined in section 9.6 of 
37   * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
38   * <blockquote>
39   * The PUT method requests that the enclosed entity be stored under the
40   * supplied Request-URI. If the Request-URI refers to an already
41   * existing resource, the enclosed entity SHOULD be considered as a
42   * modified version of the one residing on the origin server. 
43   * </blockquote>
44   * </p>
45   * 
46   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
47   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
48   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
49   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
50   *
51   * @version $Revision: 480424 $
52   * @since 1.0
53   */
54  public class PutMethod extends EntityEnclosingMethod {
55  
56      // ----------------------------------------------------------- Constructors
57  
58      /**
59       * No-arg constructor.
60       *
61       * @since 1.0
62       */
63      public PutMethod() {
64          super();
65      }
66  
67  
68      /**
69       * Constructor specifying a URI.
70       *
71       * @param uri either an absolute or relative URI
72       *
73       * @since 1.0
74       */
75      public PutMethod(String uri) {
76          super(uri);
77      }
78  
79      // --------------------------------------------------------- Public Methods
80  
81      /**
82       * Return <tt>"PUT"</tt>.
83       * @return <tt>"PUT"</tt>
84       *
85       * @since 2.0
86       */
87      public String getName() {
88          return "PUT";
89      }
90  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/RequestEntity.html100644 0 0 16237 10661532627 27307 0ustar 0 0 RequestEntity xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/RequestEntity.java,v 1.4 2004/05/17 21:46:03 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods;
32  
33  import java.io.IOException;
34  import java.io.OutputStream;
35  
36  /**
37   * @since 3.0
38   */
39  public interface RequestEntity {
40  
41      /**
42       * Tests if {@link #writeRequest(OutputStream)} can be called more than once.
43       * 
44       * @return <tt>true</tt> if the entity can be written to {@link OutputStream} more than once, 
45       * <tt>false</tt> otherwise.
46       */
47      boolean isRepeatable();
48  
49      /**
50       * Writes the request entity to the given stream.
51       * @param out
52       * @throws IOException
53       */
54      void writeRequest(OutputStream out) throws IOException;
55      
56      /**
57       * Gets the request entity's length. This method should return a non-negative value if the content 
58       * length is known or a negative value if it is not. In the latter case the
59       * {@link org.apache.commons.httpclient.methods.EntityEnclosingMethod} will use chunk encoding to
60       * transmit the request entity.
61       *  
62       * @return a non-negative value when content length is known or a negative value when content length 
63       * is not known  
64       */
65      long getContentLength();
66      
67      /**
68       * Gets the entity's content type.  This content type will be used as the value for the
69       * "Content-Type" header.
70       * @return the entity's content type
71       * @see org.apache.commons.httpclient.HttpMethod#setRequestHeader(String, String)
72       */
73      String getContentType();
74      
75  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/StringRequestEntity.html100644 0 0 40437 10661532627 30475 0ustar 0 0 StringRequestEntity xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/methods/StringRequestEntity.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   * [Additional notices, if required by prior licensing conditions]
30   *
31   */
32  package org.apache.commons.httpclient.methods;
33  
34  import java.io.IOException;
35  import java.io.OutputStream;
36  import java.io.UnsupportedEncodingException;
37  
38  import org.apache.commons.httpclient.HeaderElement;
39  import org.apache.commons.httpclient.NameValuePair;
40  
41  /**
42   * A RequestEntity that contains a String.
43   * 
44   * @since 3.0
45   */
46  public class StringRequestEntity implements RequestEntity {
47  
48      /** The content */
49      private byte[] content;
50      
51      /** The charset */
52      private String charset;
53  
54      /** The content type (i.e. text/html; charset=EUC-JP). */
55      private String contentType;
56      
57      /**
58       * <p>Creates a new entity with the given content. This constructor 
59       * will use the default platform charset to convert the content string 
60       * and will provide no content type.</p>
61       *  
62       * @see #StringRequestEntity(String, String, String)
63       * 
64       * @param content The content to set.
65       * 
66       * @deprecated use {@link #StringRequestEntity(String, String, String)} instead
67       */
68      public StringRequestEntity(String content) {
69          super();
70          if (content == null) {
71              throw new IllegalArgumentException("The content cannot be null");
72          }
73          this.contentType = null;
74          this.charset = null;
75          this.content = content.getBytes();
76      }
77  
78      /**
79       * Creates a new entity with the given content, content type, and charset.
80       *  
81       * @param content The content to set.
82       * @param contentType The type of the content, or <code>null</code>.  The value retured 
83       *   by {@link #getContentType()}.  If this content type contains a charset and the charset
84       *   parameter is null, the content's type charset will be used.
85       * @param charset The charset of the content, or <code>null</code>.  Used to convert the 
86       *   content to bytes.  If the content type does not contain a charset and charset is not null,
87       *   then the charset will be appended to the content type.
88       */
89      public StringRequestEntity(String content, String contentType, String charset) 
90          throws UnsupportedEncodingException {
91          super();
92          if (content == null) {
93              throw new IllegalArgumentException("The content cannot be null");
94          }
95          
96          this.contentType = contentType;
97          this.charset = charset;
98          
99          // resolve the content type and the charset
100         if (contentType != null) {
101             HeaderElement[] values = HeaderElement.parseElements(contentType);
102             NameValuePair charsetPair = null;
103             for (int i = 0; i < values.length; i++) {
104                 if ((charsetPair = values[i].getParameterByName("charset")) != null) {
105                     // charset found
106                     break;
107                 }
108             }
109             if (charset == null && charsetPair != null) {
110                 // use the charset from the content type
111                 this.charset = charsetPair.getValue();
112             } else if (charset != null && charsetPair == null) {
113                 // append the charset to the content type
114                 this.contentType = contentType + "; charset=" + charset; 
115             }
116         }
117         if (this.charset != null) {
118             this.content = content.getBytes(this.charset);
119         } else {
120             this.content = content.getBytes();
121         }
122     }
123 
124     /* (non-Javadoc)
125      * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType()
126      */
127     public String getContentType() {
128         return contentType;
129     }
130 
131     /**
132      * @return <code>true</code>
133      */
134     public boolean isRepeatable() {
135         return true;
136     }
137 
138     /* (non-Javadoc)
139      * @see org.apache.commons.httpclient.RequestEntity#writeRequest(java.io.OutputStream)
140      */
141     public void writeRequest(OutputStream out) throws IOException {
142         if (out == null) {
143             throw new IllegalArgumentException("Output stream may not be null");
144         }
145         out.write(this.content);
146         out.flush();
147     }
148 
149     /**
150      * @return The length of the content.
151      */
152     public long getContentLength() {
153         return this.content.length;
154     }
155 
156     /**
157      * @return Returns the content.
158      */
159     public String getContent() {
160         if (this.charset != null) {
161             try {
162                 return new String(this.content, this.charset);
163             } catch (UnsupportedEncodingException e) {
164                 return new String(this.content);
165             }
166         } else {
167             return new String(this.content);
168         }
169     }
170 
171     /**
172      * @return Returns the charset used to convert the content to bytes. <code>null</code> if
173      * no charset as been specified.
174      */
175     public String getCharset() {
176         return charset;
177     }
178 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/TraceMethod.html100644 0 0 22621 10661532627 26653 0ustar 0 0 TraceMethod xref

1   /*
2    * $Header: $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30   
31  package org.apache.commons.httpclient.methods;
32  
33  import org.apache.commons.httpclient.HttpMethodBase;
34  
35  /**
36   * Implements the HTTP TRACE method.
37   * <p>
38   * The HTTP TRACE method is defined in section 9.6 of 
39   * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
40   * <blockquote>
41   *  The TRACE method is used to invoke a remote, application-layer loop-
42   *  back of the request message. The final recipient of the request
43   *  SHOULD reflect the message received back to the client as the
44   *  entity-body of a 200 (OK) response. The final recipient is either the
45   *  origin server or the first proxy or gateway to receive a Max-Forwards
46   *  value of zero (0) in the request (see section 14.31). A TRACE request
47   *  MUST NOT include an entity.
48   * </blockquote>
49   * </p>
50   *
51   * @author Sean C. Sullivan
52   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
53   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
54   *
55   * @version $Revision: 480424 $
56   * @since 2.0
57   * 
58   */
59  public class TraceMethod extends HttpMethodBase {
60  
61      //~ Constructors
62  
63      /**
64       * Constructor specifying a URI.
65       *
66       * @param uri either an absolute or relative URI
67       * 
68       * @since 2.0
69       * 
70       */
71      public TraceMethod(String uri) {
72          super(uri);
73          setFollowRedirects(false);
74      }
75  
76      //~ Methods
77  
78      /**
79       * Returns <tt>"TRACE"</tt>.
80       * 
81       * @return <tt>"TRACE"</tt>
82       * 
83       * @since 2.0
84       * 
85       */
86      public String getName() {
87          return "TRACE";
88      }
89  
90      /**
91       * Recycles the HTTP method so that it can be used again.
92       * Note that all of the instance variables will be reset
93       * once this method has been called. This method will also
94       * release the connection being used by this HTTP method.
95       * 
96       * @see #releaseConnection()
97       * 
98       * @since 2.0
99       * 
100      * @deprecated no longer supported and will be removed in the future
101      *             version of HttpClient
102      */
103     public void recycle() {
104         super.recycle();
105         setFollowRedirects(false);
106     }
107 
108 }

././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/ByteArrayPartSource.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/ByteArrayPartSource100644 0 0 17637 10661532627 31457 0ustar 0 0 ByteArrayPartSource xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/ByteArrayPartSource.java,v 1.7 2004/04/18 23:51:37 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods.multipart;
32  
33  import java.io.ByteArrayInputStream;
34  import java.io.IOException;
35  import java.io.InputStream;
36  
37  /**
38   * A PartSource that reads from a byte array.  This class should be used when
39   * the data to post is already loaded into memory.
40   * 
41   * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
42   *   
43   * @since 2.0 
44   */
45  public class ByteArrayPartSource implements PartSource {
46  
47      /** Name of the source file. */
48      private String fileName;
49  
50      /** Byte array of the source file. */
51      private byte[] bytes;
52  
53      /**
54       * Constructor for ByteArrayPartSource.
55       * 
56       * @param fileName the name of the file these bytes represent
57       * @param bytes the content of this part
58       */
59      public ByteArrayPartSource(String fileName, byte[] bytes) {
60  
61          this.fileName = fileName;
62          this.bytes = bytes;
63  
64      }
65  
66      /**
67       * @see PartSource#getLength()
68       */
69      public long getLength() {
70          return bytes.length;
71      }
72  
73      /**
74       * @see PartSource#getFileName()
75       */
76      public String getFileName() {
77          return fileName;
78      }
79  
80      /**
81       * @see PartSource#createInputStream()
82       */
83      public InputStream createInputStream() throws IOException {
84          return new ByteArrayInputStream(bytes);
85      }
86  
87  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/FilePart.html100644 0 0 56603 10661532627 30212 0ustar 0 0 FilePart xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/FilePart.java,v 1.19 2004/04/18 23:51:37 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods.multipart;
32  
33  import java.io.File;
34  import java.io.FileNotFoundException;
35  import java.io.IOException;
36  import java.io.InputStream;
37  import java.io.OutputStream;
38  import org.apache.commons.httpclient.util.EncodingUtil;
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  
42  /**
43   * This class implements a part of a Multipart post object that
44   * consists of a file.  
45   *
46   * @author <a href="mailto:mattalbright@yahoo.com">Matthew Albright</a>
47   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
48   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
49   * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
50   * @author <a href="mailto:mdiggory@latte.harvard.edu">Mark Diggory</a>
51   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
52   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
53   *   
54   * @since 2.0 
55   *
56   */
57  public class FilePart extends PartBase {
58  
59      /** Default content encoding of file attachments. */
60      public static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
61  
62      /** Default charset of file attachments. */
63      public static final String DEFAULT_CHARSET = "ISO-8859-1";
64  
65      /** Default transfer encoding of file attachments. */
66      public static final String DEFAULT_TRANSFER_ENCODING = "binary";
67  
68      /** Log object for this class. */
69      private static final Log LOG = LogFactory.getLog(FilePart.class);
70  
71      /** Attachment's file name */
72      protected static final String FILE_NAME = "; filename=";
73  
74      /** Attachment's file name as a byte array */
75      private static final byte[] FILE_NAME_BYTES = 
76          EncodingUtil.getAsciiBytes(FILE_NAME);
77  
78      /** Source of the file part. */
79      private PartSource source;
80  
81      /**
82       * FilePart Constructor.
83       *
84       * @param name the name for this part
85       * @param partSource the source for this part
86       * @param contentType the content type for this part, if <code>null</code> the 
87       * {@link #DEFAULT_CONTENT_TYPE default} is used
88       * @param charset the charset encoding for this part, if <code>null</code> the 
89       * {@link #DEFAULT_CHARSET default} is used
90       */
91      public FilePart(String name, PartSource partSource, String contentType, String charset) {
92          
93          super(
94              name, 
95              contentType == null ? DEFAULT_CONTENT_TYPE : contentType, 
96              charset == null ? "ISO-8859-1" : charset, 
97              DEFAULT_TRANSFER_ENCODING
98          );
99  
100         if (partSource == null) {
101             throw new IllegalArgumentException("Source may not be null");
102         }
103         this.source = partSource;
104     }
105         
106     /**
107      * FilePart Constructor.
108      *
109      * @param name the name for this part
110      * @param partSource the source for this part
111      */
112     public FilePart(String name, PartSource partSource) {
113         this(name, partSource, null, null);
114     }
115 
116     /**
117      * FilePart Constructor.
118      *
119      * @param name the name of the file part
120      * @param file the file to post
121      *
122      * @throws FileNotFoundException if the <i>file</i> is not a normal
123      * file or if it is not readable.
124      */
125     public FilePart(String name, File file) 
126     throws FileNotFoundException {
127         this(name, new FilePartSource(file), null, null);
128     }
129 
130     /**
131      * FilePart Constructor.
132      *
133      * @param name the name of the file part
134      * @param file the file to post
135      * @param contentType the content type for this part, if <code>null</code> the 
136      * {@link #DEFAULT_CONTENT_TYPE default} is used
137      * @param charset the charset encoding for this part, if <code>null</code> the 
138      * {@link #DEFAULT_CHARSET default} is used
139      *
140      * @throws FileNotFoundException if the <i>file</i> is not a normal
141      * file or if it is not readable.
142      */
143     public FilePart(String name, File file, String contentType, String charset) 
144     throws FileNotFoundException {
145         this(name, new FilePartSource(file), contentType, charset);
146     }
147 
148      /**
149      * FilePart Constructor.
150      *
151      * @param name the name of the file part
152      * @param fileName the file name 
153      * @param file the file to post
154      *
155      * @throws FileNotFoundException if the <i>file</i> is not a normal
156      * file or if it is not readable.
157      */
158     public FilePart(String name, String fileName, File file) 
159     throws FileNotFoundException {
160         this(name, new FilePartSource(fileName, file), null, null);
161     }
162     
163      /**
164      * FilePart Constructor.
165      *
166      * @param name the name of the file part
167      * @param fileName the file name 
168      * @param file the file to post
169      * @param contentType the content type for this part, if <code>null</code> the 
170      * {@link #DEFAULT_CONTENT_TYPE default} is used
171      * @param charset the charset encoding for this part, if <code>null</code> the 
172      * {@link #DEFAULT_CHARSET default} is used
173      *
174      * @throws FileNotFoundException if the <i>file</i> is not a normal
175      * file or if it is not readable.
176      */
177     public FilePart(String name, String fileName, File file, String contentType, String charset) 
178     throws FileNotFoundException {
179         this(name, new FilePartSource(fileName, file), contentType, charset);
180     }
181     
182     /**
183      * Write the disposition header to the output stream
184      * @param out The output stream
185      * @throws IOException If an IO problem occurs
186      * @see Part#sendDispositionHeader(OutputStream)
187      */
188     protected void sendDispositionHeader(OutputStream out) 
189     throws IOException {
190         LOG.trace("enter sendDispositionHeader(OutputStream out)");
191         super.sendDispositionHeader(out);
192         String filename = this.source.getFileName();
193         if (filename != null) {
194             out.write(FILE_NAME_BYTES);
195             out.write(QUOTE_BYTES);
196             out.write(EncodingUtil.getAsciiBytes(filename));
197             out.write(QUOTE_BYTES);
198         }
199     }
200     
201     /**
202      * Write the data in "source" to the specified stream.
203      * @param out The output stream.
204      * @throws IOException if an IO problem occurs.
205      * @see org.apache.commons.httpclient.methods.multipart.Part#sendData(OutputStream)
206      */
207     protected void sendData(OutputStream out) throws IOException {
208         LOG.trace("enter sendData(OutputStream out)");
209         if (lengthOfData() == 0) {
210             
211             // this file contains no data, so there is nothing to send.
212             // we don't want to create a zero length buffer as this will
213             // cause an infinite loop when reading.
214             LOG.debug("No data to send.");
215             return;
216         }
217         
218         byte[] tmp = new byte[4096];
219         InputStream instream = source.createInputStream();
220         try {
221             int len;
222             while ((len = instream.read(tmp)) >= 0) {
223                 out.write(tmp, 0, len);
224             }
225         } finally {
226             // we're done with the stream, close it
227             instream.close();
228         }
229     }
230 
231     /** 
232      * Returns the source of the file part.
233      *  
234      * @return The source.
235      */
236     protected PartSource getSource() {
237         LOG.trace("enter getSource()");
238         return this.source;
239     }
240 
241     /**
242      * Return the length of the data.
243      * @return The length.
244      * @throws IOException if an IO problem occurs
245      * @see org.apache.commons.httpclient.methods.multipart.Part#lengthOfData()
246      */    
247     protected long lengthOfData() throws IOException {
248         LOG.trace("enter lengthOfData()");
249         return source.getLength();
250     }    
251 
252 }

././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/FilePartSource.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/FilePartSource.html100644 0 0 27506 10661532627 31373 0ustar 0 0 FilePartSource xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/FilePartSource.java,v 1.10 2004/04/18 23:51:37 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30   
31  package org.apache.commons.httpclient.methods.multipart;
32  
33  import java.io.ByteArrayInputStream;
34  import java.io.File;
35  import java.io.FileInputStream;
36  import java.io.FileNotFoundException;
37  import java.io.IOException;
38  import java.io.InputStream;
39  
40  /**
41   * A PartSource that reads from a File.
42   * 
43   * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
44   * @author <a href="mailto:mdiggory@latte.harvard.edu">Mark Diggory</a>
45   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
46   *   
47   * @since 2.0 
48   */
49  public class FilePartSource implements PartSource {
50  
51      /** File part file. */
52      private File file = null;
53  
54      /** File part file name. */
55      private String fileName = null;
56      
57      /**
58       * Constructor for FilePartSource.
59       * 
60       * @param file the FilePart source File. 
61       *
62       * @throws FileNotFoundException if the file does not exist or 
63       * cannot be read
64       */
65      public FilePartSource(File file) throws FileNotFoundException {
66          this.file = file;
67          if (file != null) {
68              if (!file.isFile()) {
69                  throw new FileNotFoundException("File is not a normal file.");
70              }
71              if (!file.canRead()) {
72                  throw new FileNotFoundException("File is not readable.");
73              }
74              this.fileName = file.getName();       
75          }
76      }
77  
78      /**
79       * Constructor for FilePartSource.
80       * 
81       * @param fileName the file name of the FilePart
82       * @param file the source File for the FilePart
83       *
84       * @throws FileNotFoundException if the file does not exist or 
85       * cannot be read
86       */
87      public FilePartSource(String fileName, File file) 
88        throws FileNotFoundException {
89          this(file);
90          if (fileName != null) {
91              this.fileName = fileName;
92          }
93      }
94      
95      /**
96       * Return the length of the file
97       * @return the length of the file.
98       * @see PartSource#getLength()
99       */
100     public long getLength() {
101         if (this.file != null) {
102             return this.file.length();
103         } else {
104             return 0;
105         }
106     }
107 
108     /**
109      * Return the current filename
110      * @return the filename.
111      * @see PartSource#getFileName()
112      */
113     public String getFileName() {
114         return (fileName == null) ? "noname" : fileName;
115     }
116 
117     /**
118      * Return a new {@link FileInputStream} for the current filename.
119      * @return the new input stream.
120      * @throws IOException If an IO problem occurs.
121      * @see PartSource#createInputStream()
122      */
123     public InputStream createInputStream() throws IOException {
124         if (this.file != null) {
125             return new FileInputStream(this.file);
126         } else {
127             return new ByteArrayInputStream(new byte[] {});
128         }
129     }
130 
131 }

././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/MultipartRequestEntity.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/MultipartRequestEnt100644 0 0 43505 10661532627 31537 0ustar 0 0 MultipartRequestEntity xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/MultipartRequestEntity.java,v 1.1 2004/10/06 03:39:59 mbecke Exp $
3    * $Revision: 502647 $
4    * $Date: 2007-02-02 17:22:54 +0100 (Fri, 02 Feb 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient.methods.multipart;
31  
32  import java.io.IOException;
33  import java.io.OutputStream;
34  import java.util.Random;
35  
36  import org.apache.commons.httpclient.methods.RequestEntity;
37  import org.apache.commons.httpclient.params.HttpMethodParams;
38  import org.apache.commons.httpclient.util.EncodingUtil;
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  
42  /**
43   * Implements a request entity suitable for an HTTP multipart POST method.
44   * <p>
45   * The HTTP multipart POST method is defined in section 3.3 of
46   * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC1867</a>:
47   * <blockquote>
48   * The media-type multipart/form-data follows the rules of all multipart
49   * MIME data streams as outlined in RFC 1521. The multipart/form-data contains 
50   * a series of parts. Each part is expected to contain a content-disposition 
51   * header where the value is "form-data" and a name attribute specifies 
52   * the field name within the form, e.g., 'content-disposition: form-data; 
53   * name="xxxxx"', where xxxxx is the field name corresponding to that field.
54   * Field names originally in non-ASCII character sets may be encoded using 
55   * the method outlined in RFC 1522.
56   * </blockquote>
57   * </p>
58   * <p>This entity is designed to be used in conjunction with the 
59   * {@link org.apache.commons.httpclient.methods.PostMethod post method} to provide
60   * multipart posts.  Example usage:</p>
61   * <pre>
62   *  File f = new File("/path/fileToUpload.txt");
63   *  PostMethod filePost = new PostMethod("http://host/some_path");
64   *  Part[] parts = {
65   *      new StringPart("param_name", "value"),
66   *      new FilePart(f.getName(), f)
67   *  };
68   *  filePost.setRequestEntity(
69   *      new MultipartRequestEntity(parts, filePost.getParams())
70   *      );
71   *  HttpClient client = new HttpClient();
72   *  int status = client.executeMethod(filePost);
73   * </pre>
74   * 
75   * @since 3.0
76   */
77  public class MultipartRequestEntity implements RequestEntity {
78  
79      private static final Log log = LogFactory.getLog(MultipartRequestEntity.class);
80      
81      /** The Content-Type for multipart/form-data. */
82      private static final String MULTIPART_FORM_CONTENT_TYPE = "multipart/form-data";
83      
84      /**
85       * The pool of ASCII chars to be used for generating a multipart boundary.
86       */
87      private static byte[] MULTIPART_CHARS = EncodingUtil.getAsciiBytes(
88          "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
89      
90      /**
91       * Generates a random multipart boundary string.
92       * @return
93       */
94      private static byte[] generateMultipartBoundary() {
95          Random rand = new Random();
96          byte[] bytes = new byte[rand.nextInt(11) + 30]; // a random size from 30 to 40
97          for (int i = 0; i < bytes.length; i++) {
98              bytes[i] = MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)];
99          }
100         return bytes;
101     }
102     
103     /** The MIME parts as set by the constructor */
104     protected Part[] parts;
105     
106     private byte[] multipartBoundary;
107     
108     private HttpMethodParams params;
109     
110     /**
111      * Creates a new multipart entity containing the given parts.
112      * @param parts The parts to include.
113      * @param params The params of the HttpMethod using this entity.
114      */
115     public MultipartRequestEntity(Part[] parts, HttpMethodParams params) {
116         if (parts == null) {
117             throw new IllegalArgumentException("parts cannot be null");
118         }
119         if (params == null) {
120             throw new IllegalArgumentException("params cannot be null");
121         }
122         this.parts = parts;
123         this.params = params;
124     }
125 
126     /**
127      * Returns the MIME boundary string that is used to demarcate boundaries of
128      * this part. The first call to this method will implicitly create a new
129      * boundary string. To create a boundary string first the 
130      * HttpMethodParams.MULTIPART_BOUNDARY parameter is considered. Otherwise 
131      * a random one is generated.
132      * 
133      * @return The boundary string of this entity in ASCII encoding.
134      */
135     protected byte[] getMultipartBoundary() {
136         if (multipartBoundary == null) {
137             String temp = (String) params.getParameter(HttpMethodParams.MULTIPART_BOUNDARY);
138             if (temp != null) {
139                 multipartBoundary = EncodingUtil.getAsciiBytes(temp);
140             } else {
141                 multipartBoundary = generateMultipartBoundary();
142             }
143         }
144         return multipartBoundary;
145     }
146 
147     /**
148      * Returns <code>true</code> if all parts are repeatable, <code>false</code> otherwise.
149      * @see org.apache.commons.httpclient.methods.RequestEntity#isRepeatable()
150      */
151     public boolean isRepeatable() {
152         for (int i = 0; i < parts.length; i++) {
153             if (!parts[i].isRepeatable()) {
154                 return false;
155             }
156         }
157         return true;
158     }
159 
160     /* (non-Javadoc)
161      * @see org.apache.commons.httpclient.methods.RequestEntity#writeRequest(java.io.OutputStream)
162      */
163     public void writeRequest(OutputStream out) throws IOException {
164         Part.sendParts(out, parts, getMultipartBoundary());
165     }
166 
167     /* (non-Javadoc)
168      * @see org.apache.commons.httpclient.methods.RequestEntity#getContentLength()
169      */
170     public long getContentLength() {
171         try {
172             return Part.getLengthOfParts(parts, getMultipartBoundary());            
173         } catch (Exception e) {
174             log.error("An exception occurred while getting the length of the parts", e);
175             return 0;
176         }
177     }
178 
179     /* (non-Javadoc)
180      * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType()
181      */
182     public String getContentType() {
183         StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
184         buffer.append("; boundary=");
185         buffer.append(EncodingUtil.getAsciiString(getMultipartBoundary()));
186         return buffer.toString();
187     }
188 
189 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/Part.html100644 0 0 110410 10661532627 27415 0ustar 0 0 Part xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/Part.java,v 1.16 2005/01/14 21:16:40 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods.multipart;
32  
33  import java.io.ByteArrayOutputStream;
34  import java.io.IOException;
35  import java.io.OutputStream;
36  
37  import org.apache.commons.httpclient.util.EncodingUtil;
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  
41  /**
42   * Abstract class for one Part of a multipart post object.
43   *
44   * @author <a href="mailto:mattalbright@yahoo.com">Matthew Albright</a>
45   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
46   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
47   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
48   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
49   *
50   * @since 2.0
51   */
52  public abstract class Part {
53  
54      /** Log object for this class. */
55      private static final Log LOG = LogFactory.getLog(Part.class);
56  
57      /** 
58       * The boundary 
59       * @deprecated use {@link org.apache.commons.httpclient.params.HttpMethodParams#MULTIPART_BOUNDARY}
60       */
61      protected static final String BOUNDARY = "----------------314159265358979323846";
62      
63      /** 
64       * The boundary as a byte array.
65       * @deprecated
66       */
67      protected static final byte[] BOUNDARY_BYTES = EncodingUtil.getAsciiBytes(BOUNDARY);
68  
69      /**
70       * The default boundary to be used if {@link #setBoundaryBytes(byte[])) has not
71       * been called.
72       */
73      private static final byte[] DEFAULT_BOUNDARY_BYTES = BOUNDARY_BYTES;    
74      
75      /** Carriage return/linefeed */
76      protected static final String CRLF = "\r\n";
77      
78      /** Carriage return/linefeed as a byte array */
79      protected static final byte[] CRLF_BYTES = EncodingUtil.getAsciiBytes(CRLF);
80      
81      /** Content dispostion characters */
82      protected static final String QUOTE = "\"";
83      
84      /** Content dispostion as a byte array */
85      protected static final byte[] QUOTE_BYTES = 
86        EncodingUtil.getAsciiBytes(QUOTE);
87  
88      /** Extra characters */
89      protected static final String EXTRA = "--";
90      
91      /** Extra characters as a byte array */
92      protected static final byte[] EXTRA_BYTES = 
93        EncodingUtil.getAsciiBytes(EXTRA);
94      
95      /** Content dispostion characters */
96      protected static final String CONTENT_DISPOSITION = "Content-Disposition: form-data; name=";
97      
98      /** Content dispostion as a byte array */
99      protected static final byte[] CONTENT_DISPOSITION_BYTES = 
100       EncodingUtil.getAsciiBytes(CONTENT_DISPOSITION);
101 
102     /** Content type header */
103     protected static final String CONTENT_TYPE = "Content-Type: ";
104 
105     /** Content type header as a byte array */
106     protected static final byte[] CONTENT_TYPE_BYTES = 
107       EncodingUtil.getAsciiBytes(CONTENT_TYPE);
108 
109     /** Content charset */
110     protected static final String CHARSET = "; charset=";
111 
112     /** Content charset as a byte array */
113     protected static final byte[] CHARSET_BYTES = 
114       EncodingUtil.getAsciiBytes(CHARSET);
115 
116     /** Content type header */
117     protected static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: ";
118 
119     /** Content type header as a byte array */
120     protected static final byte[] CONTENT_TRANSFER_ENCODING_BYTES = 
121       EncodingUtil.getAsciiBytes(CONTENT_TRANSFER_ENCODING);
122 
123     /**
124      * Return the boundary string.
125      * @return the boundary string
126      * @deprecated uses a constant string. Rather use {@link #getPartBoundary}
127      */
128     public static String getBoundary() {
129         return BOUNDARY;
130     }
131 
132     /**
133      * The ASCII bytes to use as the multipart boundary.
134      */
135     private byte[] boundaryBytes;
136     
137     /**
138      * Return the name of this part.
139      * @return The name.
140      */
141     public abstract String getName();
142     
143     /**
144      * Returns the content type of this part.
145      * @return the content type, or <code>null</code> to exclude the content type header
146      */
147     public abstract String getContentType();
148 
149     /**
150      * Return the character encoding of this part.
151      * @return the character encoding, or <code>null</code> to exclude the character 
152      * encoding header
153      */
154     public abstract String getCharSet();
155 
156     /**
157      * Return the transfer encoding of this part.
158      * @return the transfer encoding, or <code>null</code> to exclude the transfer encoding header
159      */
160     public abstract String getTransferEncoding();
161 
162     /**
163      * Gets the part boundary to be used.
164      * @return the part boundary as an array of bytes.
165      * 
166      * @since 3.0
167      */
168     protected byte[] getPartBoundary() {
169         if (boundaryBytes == null) {
170             // custom boundary bytes have not been set, use the default.
171             return DEFAULT_BOUNDARY_BYTES;
172         } else {
173             return boundaryBytes;            
174         }
175     }
176     
177     /**
178      * Sets the part boundary.  Only meant to be used by 
179      * {@link Part#sendParts(OutputStream, Part[], byte[])}
180      * and {@link Part#getLengthOfParts(Part[], byte[])}
181      * @param boundaryBytes An array of ASCII bytes.
182      * @since 3.0
183      */
184     void setPartBoundary(byte[] boundaryBytes) {
185         this.boundaryBytes = boundaryBytes;
186     }
187     
188     /**
189      * Tests if this part can be sent more than once.
190      * @return <code>true</code> if {@link #sendData(OutputStream)} can be successfully called 
191      * more than once.
192      * @since 3.0
193      */
194     public boolean isRepeatable() {
195         return true;
196     }
197     
198     /**
199      * Write the start to the specified output stream
200      * @param out The output stream
201      * @throws IOException If an IO problem occurs.
202      */
203     protected void sendStart(OutputStream out) throws IOException {
204         LOG.trace("enter sendStart(OutputStream out)");
205         out.write(EXTRA_BYTES);
206         out.write(getPartBoundary());
207         out.write(CRLF_BYTES);
208     }
209     
210     /**
211      * Write the content disposition header to the specified output stream
212      * 
213      * @param out The output stream
214      * @throws IOException If an IO problem occurs.
215      */
216     protected void sendDispositionHeader(OutputStream out) throws IOException {
217         LOG.trace("enter sendDispositionHeader(OutputStream out)");
218         out.write(CONTENT_DISPOSITION_BYTES);
219         out.write(QUOTE_BYTES);
220         out.write(EncodingUtil.getAsciiBytes(getName()));
221         out.write(QUOTE_BYTES);
222     }
223     
224     /**
225      * Write the content type header to the specified output stream
226      * @param out The output stream
227      * @throws IOException If an IO problem occurs.
228      */
229      protected void sendContentTypeHeader(OutputStream out) throws IOException {
230         LOG.trace("enter sendContentTypeHeader(OutputStream out)");
231         String contentType = getContentType();
232         if (contentType != null) {
233             out.write(CRLF_BYTES);
234             out.write(CONTENT_TYPE_BYTES);
235             out.write(EncodingUtil.getAsciiBytes(contentType));
236             String charSet = getCharSet();
237             if (charSet != null) {
238                 out.write(CHARSET_BYTES);
239                 out.write(EncodingUtil.getAsciiBytes(charSet));
240             }
241         }
242     }
243 
244     /**
245      * Write the content transfer encoding header to the specified 
246      * output stream
247      * 
248      * @param out The output stream
249      * @throws IOException If an IO problem occurs.
250      */
251      protected void sendTransferEncodingHeader(OutputStream out) throws IOException {
252         LOG.trace("enter sendTransferEncodingHeader(OutputStream out)");
253         String transferEncoding = getTransferEncoding();
254         if (transferEncoding != null) {
255             out.write(CRLF_BYTES);
256             out.write(CONTENT_TRANSFER_ENCODING_BYTES);
257             out.write(EncodingUtil.getAsciiBytes(transferEncoding));
258         }
259     }
260 
261     /**
262      * Write the end of the header to the output stream
263      * @param out The output stream
264      * @throws IOException If an IO problem occurs.
265      */
266     protected void sendEndOfHeader(OutputStream out) throws IOException {
267         LOG.trace("enter sendEndOfHeader(OutputStream out)");
268         out.write(CRLF_BYTES);
269         out.write(CRLF_BYTES);
270     }
271     
272     /**
273      * Write the data to the specified output stream
274      * @param out The output stream
275      * @throws IOException If an IO problem occurs.
276      */
277     protected abstract void sendData(OutputStream out) throws IOException;
278     
279     /**
280      * Return the length of the main content
281      * 
282      * @return long The length.
283      * @throws IOException If an IO problem occurs
284      */
285     protected abstract long lengthOfData() throws IOException;
286     
287     /**
288      * Write the end data to the output stream.
289      * @param out The output stream
290      * @throws IOException If an IO problem occurs.
291      */
292     protected void sendEnd(OutputStream out) throws IOException {
293         LOG.trace("enter sendEnd(OutputStream out)");
294         out.write(CRLF_BYTES);
295     }
296     
297     /**
298      * Write all the data to the output stream.
299      * If you override this method make sure to override 
300      * #length() as well
301      * 
302      * @param out The output stream
303      * @throws IOException If an IO problem occurs.
304      */
305     public void send(OutputStream out) throws IOException {
306         LOG.trace("enter send(OutputStream out)");
307         sendStart(out);
308         sendDispositionHeader(out);
309         sendContentTypeHeader(out);
310         sendTransferEncodingHeader(out);
311         sendEndOfHeader(out);
312         sendData(out);
313         sendEnd(out);
314     }
315 
316 
317     /**
318      * Return the full length of all the data.
319      * If you override this method make sure to override 
320      * #send(OutputStream) as well
321      * 
322      * @return long The length.
323      * @throws IOException If an IO problem occurs
324      */
325     public long length() throws IOException {
326         LOG.trace("enter length()");
327         if (lengthOfData() < 0) {
328             return -1;
329         }
330         ByteArrayOutputStream overhead = new ByteArrayOutputStream();
331         sendStart(overhead);
332         sendDispositionHeader(overhead);
333         sendContentTypeHeader(overhead);
334         sendTransferEncodingHeader(overhead);
335         sendEndOfHeader(overhead);
336         sendEnd(overhead);
337         return overhead.size() + lengthOfData();
338     }
339 
340     /**
341      * Return a string representation of this object.
342      * @return A string representation of this object.
343      * @see java.lang.Object#toString()
344      */    
345     public String toString() {
346         return this.getName();
347     }
348 
349     /**
350      * Write all parts and the last boundary to the specified output stream.
351      * 
352      * @param out The stream to write to.
353      * @param parts The parts to write.
354      * 
355      * @throws IOException If an I/O error occurs while writing the parts.
356      */
357     public static void sendParts(OutputStream out, final Part[] parts)
358         throws IOException {
359         sendParts(out, parts, DEFAULT_BOUNDARY_BYTES);
360     }
361 
362     /**
363      * Write all parts and the last boundary to the specified output stream.
364      * 
365      * @param out The stream to write to.
366      * @param parts The parts to write.
367      * @param partBoundary The ASCII bytes to use as the part boundary.
368      * 
369      * @throws IOException If an I/O error occurs while writing the parts.
370      * 
371      * @since 3.0
372      */
373     public static void sendParts(OutputStream out, Part[] parts, byte[] partBoundary)
374         throws IOException {
375         
376         if (parts == null) {
377             throw new IllegalArgumentException("Parts may not be null"); 
378         }
379         if (partBoundary == null || partBoundary.length == 0) {
380             throw new IllegalArgumentException("partBoundary may not be empty");
381         }
382         for (int i = 0; i < parts.length; i++) {
383             // set the part boundary before the part is sent
384             parts[i].setPartBoundary(partBoundary);
385             parts[i].send(out);
386         }
387         out.write(EXTRA_BYTES);
388         out.write(partBoundary);
389         out.write(EXTRA_BYTES);
390         out.write(CRLF_BYTES);
391     }
392     
393     /**
394      * Return the total sum of all parts and that of the last boundary
395      * 
396      * @param parts The parts.
397      * @return The total length
398      * 
399      * @throws IOException If an I/O error occurs while writing the parts.
400      */
401     public static long getLengthOfParts(Part[] parts)
402     throws IOException {
403         return getLengthOfParts(parts, DEFAULT_BOUNDARY_BYTES);
404     }
405     
406     /**
407      * Gets the length of the multipart message including the given parts.
408      * 
409      * @param parts The parts.
410      * @param partBoundary The ASCII bytes to use as the part boundary.
411      * @return The total length
412      * 
413      * @throws IOException If an I/O error occurs while writing the parts.
414      * 
415      * @since 3.0
416      */
417     public static long getLengthOfParts(Part[] parts, byte[] partBoundary) throws IOException {
418         LOG.trace("getLengthOfParts(Parts[])");
419         if (parts == null) {
420             throw new IllegalArgumentException("Parts may not be null"); 
421         }
422         long total = 0;
423         for (int i = 0; i < parts.length; i++) {
424             // set the part boundary before we calculate the part's length
425             parts[i].setPartBoundary(partBoundary);
426             long l = parts[i].length();
427             if (l < 0) {
428                 return -1;
429             }
430             total += l;
431         }
432         total += EXTRA_BYTES.length;
433         total += partBoundary.length;
434         total += EXTRA_BYTES.length;
435         total += CRLF_BYTES.length;
436         return total;
437     }        
438 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/PartBase.html100644 0 0 30204 10661532627 30172 0ustar 0 0 PartBase xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/PartBase.java,v 1.5 2004/04/18 23:51:37 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30   
31  package org.apache.commons.httpclient.methods.multipart;
32  
33  
34  /**
35   * Provides setters and getters for the basic Part properties.
36   * 
37   * @author Michael Becke
38   */
39  public abstract class PartBase extends Part {
40  
41      /** Name of the file part. */
42      private String name;
43          
44      /** Content type of the file part. */
45      private String contentType;
46  
47      /** Content encoding of the file part. */
48      private String charSet;
49      
50      /** The transfer encoding. */
51      private String transferEncoding;
52  
53      /**
54       * Constructor.
55       * 
56       * @param name The name of the part
57       * @param contentType The content type, or <code>null</code>
58       * @param charSet The character encoding, or <code>null</code> 
59       * @param transferEncoding The transfer encoding, or <code>null</code>
60       */
61      public PartBase(String name, String contentType, String charSet, String transferEncoding) {
62  
63          if (name == null) {
64              throw new IllegalArgumentException("Name must not be null");
65          }
66          this.name = name;
67          this.contentType = contentType;
68          this.charSet = charSet;
69          this.transferEncoding = transferEncoding;
70      }
71  
72      /**
73       * Returns the name.
74       * @return The name.
75       * @see org.apache.commons.httpclient.methods.multipart.Part#getName()
76       */
77      public String getName() { 
78          return this.name; 
79      }
80  
81      /**
82       * Returns the content type of this part.
83       * @return String The name.
84       */
85      public String getContentType() {
86          return this.contentType;
87      }
88  
89      /**
90       * Return the character encoding of this part.
91       * @return String The name.
92       */
93      public String getCharSet() {
94          return this.charSet;
95      }
96  
97      /**
98       * Returns the transfer encoding of this part.
99       * @return String The name.
100      */
101     public String getTransferEncoding() {
102         return transferEncoding;
103     }
104 
105     /**
106      * Sets the character encoding.
107      * 
108      * @param charSet the character encoding, or <code>null</code> to exclude the character 
109      * encoding header
110      */
111     public void setCharSet(String charSet) {
112         this.charSet = charSet;
113     }
114 
115     /**
116      * Sets the content type.
117      * 
118      * @param contentType the content type, or <code>null</code> to exclude the content type header
119      */
120     public void setContentType(String contentType) {
121         this.contentType = contentType;
122     }
123 
124     /**
125      * Sets the part name.
126      * 
127      * @param name
128      */
129     public void setName(String name) {
130         if (name == null) {
131             throw new IllegalArgumentException("Name must not be null");
132         }
133         this.name = name;
134     }
135 
136     /**
137      * Sets the transfer encoding.
138      * 
139      * @param transferEncoding the transfer encoding, or <code>null</code> to exclude the 
140      * transfer encoding header
141      */
142     public void setTransferEncoding(String transferEncoding) {
143         this.transferEncoding = transferEncoding;
144     }
145 
146 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/PartSource.html100644 0 0 15351 10661532627 30566 0ustar 0 0 PartSource xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/PartSource.java,v 1.6 2004/04/18 23:51:37 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30   
31  package org.apache.commons.httpclient.methods.multipart;
32  
33  import java.io.IOException;
34  import java.io.InputStream;
35  
36  /**
37   * An interface for providing access to data when posting MultiPart messages.
38   * 
39   * @see FilePart
40   * 
41   * @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
42   *   
43   * @since 2.0 
44   */
45  public interface PartSource {
46  
47      /**
48       * Gets the number of bytes contained in this source.
49       * 
50       * @return a value >= 0
51       */
52      long getLength();
53      
54      /**
55       * Gets the name of the file this source represents.
56       * 
57       * @return the fileName used for posting a MultiPart file part
58       */
59      String getFileName();
60      
61      /**
62       * Gets a new InputStream for reading this source.  This method can be 
63       * called more than once and should therefore return a new stream every
64       * time.
65       * 
66       * @return a new InputStream
67       * 
68       * @throws IOException if an error occurs when creating the InputStream
69       */
70      InputStream createInputStream() throws IOException;
71  
72  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/StringPart.html100644 0 0 33037 10661532627 30575 0ustar 0 0 StringPart xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/StringPart.java,v 1.11 2004/04/18 23:51:37 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.methods.multipart;
32  
33  import java.io.OutputStream;
34  import java.io.IOException;
35  
36  import org.apache.commons.httpclient.util.EncodingUtil;
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  
40  /**
41   * Simple string parameter for a multipart post
42   *
43   * @author <a href="mailto:mattalbright@yahoo.com">Matthew Albright</a>
44   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
45   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
46   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
47   *
48   * @since 2.0
49   */
50  public class StringPart extends PartBase {
51  
52      /** Log object for this class. */
53      private static final Log LOG = LogFactory.getLog(StringPart.class);
54  
55      /** Default content encoding of string parameters. */
56      public static final String DEFAULT_CONTENT_TYPE = "text/plain";
57  
58      /** Default charset of string parameters*/
59      public static final String DEFAULT_CHARSET = "US-ASCII";
60  
61      /** Default transfer encoding of string parameters*/
62      public static final String DEFAULT_TRANSFER_ENCODING = "8bit";
63  
64      /** Contents of this StringPart. */
65      private byte[] content;
66      
67      /** The String value of this part. */
68      private String value;
69  
70      /**
71       * Constructor.
72       *
73       * @param name The name of the part
74       * @param value the string to post
75       * @param charset the charset to be used to encode the string, if <code>null</code> 
76       * the {@link #DEFAULT_CHARSET default} is used
77       */
78      public StringPart(String name, String value, String charset) {
79          
80          super(
81              name,
82              DEFAULT_CONTENT_TYPE,
83              charset == null ? DEFAULT_CHARSET : charset,
84              DEFAULT_TRANSFER_ENCODING
85          );
86          if (value == null) {
87              throw new IllegalArgumentException("Value may not be null");
88          }
89          if (value.indexOf(0) != -1) {
90              // See RFC 2048, 2.8. "8bit Data"
91              throw new IllegalArgumentException("NULs may not be present in string parts");
92          }
93          this.value = value;
94      }
95  
96      /**
97       * Constructor.
98       *
99       * @param name The name of the part
100      * @param value the string to post
101      */
102     public StringPart(String name, String value) {
103         this(name, value, null);
104     }
105     
106     /**
107      * Gets the content in bytes.  Bytes are lazily created to allow the charset to be changed
108      * after the part is created.
109      * 
110      * @return the content in bytes
111      */
112     private byte[] getContent() {
113         if (content == null) {
114             content = EncodingUtil.getBytes(value, getCharSet());
115         }
116         return content;
117     }
118     
119     /**
120      * Writes the data to the given OutputStream.
121      * @param out the OutputStream to write to
122      * @throws IOException if there is a write error
123      */
124     protected void sendData(OutputStream out) throws IOException {
125         LOG.trace("enter sendData(OutputStream)");
126         out.write(getContent());
127     }
128     
129     /**
130      * Return the length of the data.
131      * @return The length of the data.
132      * @throws IOException If an IO problem occurs
133      * @see org.apache.commons.httpclient.methods.multipart.Part#lengthOfData()
134      */
135     protected long lengthOfData() throws IOException {
136         LOG.trace("enter lengthOfData()");
137         return getContent().length;
138     }
139     
140     /* (non-Javadoc)
141      * @see org.apache.commons.httpclient.methods.multipart.BasePart#setCharSet(java.lang.String)
142      */
143     public void setCharSet(String charSet) {
144         super.setCharSet(charSet);
145         this.content = null;
146     }
147 
148 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/package-frame.html100644 0 0 3110 10661532632 31124 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.methods.multipart

org.apache.commons.httpclient.methods.multipart

Classes

././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/package-summary.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/multipart/package-summary.htm100644 0 0 6201 10661532632 31357 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.methods.multipart

Package org.apache.commons.httpclient.methods.multipart

Class Summary
ByteArrayPartSource
FilePart
FilePartSource
MultipartRequestEntity
Part
PartBase
PartSource
StringPart

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/package-frame.html100644 0 0 4753 10661532632 27121 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.methods

org.apache.commons.httpclient.methods

Classes

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/methods/package-summary.html100644 0 0 10523 10661532632 27534 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.methods

Package org.apache.commons.httpclient.methods

Class Summary
ByteArrayRequestEntity
DeleteMethod
EntityEnclosingMethod
ExpectContinueMethod
FileRequestEntity
GetMethod
HeadMethod
InputStreamRequestEntity
MultipartPostMethod
OptionsMethod
PostMethod
PutMethod
RequestEntity
StringRequestEntity
TraceMethod

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/package-frame.html100644 0 0 16746 10661532632 25503 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient

org.apache.commons.httpclient

Classes

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/package-summary.html100644 0 0 26035 10661532632 26076 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient

Package org.apache.commons.httpclient

Class Summary
AutoCloseInputStream
ChunkedInputStream
ChunkedOutputStream
CircularRedirectException
ConnectMethod
ConnectTimeoutException
ConnectionPoolTimeoutException
ContentLengthInputStream
Cookie
Credentials
DefaultHttpMethodRetryHandler
DefaultMethodRetryHandler
Header
HeaderElement
HeaderGroup
HostConfiguration
HttpClient
HttpClientError
HttpConnection
HttpConnectionManager
HttpConstants
HttpContentTooLargeException
HttpException
HttpHost
HttpMethod
HttpMethodBase
HttpMethodDirector
HttpMethodRetryHandler
HttpParser
HttpRecoverableException
HttpState
HttpStatus
HttpURL
HttpVersion
HttpsURL
InvalidRedirectLocationException
MethodRetryHandler
MultiThreadedHttpConnectionManager
NTCredentials
NameValuePair
NoHttpResponseException
ProtocolException
ProxyClient
ProxyHost
RedirectException
ResponseConsumedWatcher
SimpleHttpConnectionManager
StatusLine
URI
URIException
UsernamePasswordCredentials
Wire
WireLogInputStream
WireLogOutputStream

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/DefaultHttpParams.html100644 0 0 55662 10661532627 27677 0ustar 0 0 DefaultHttpParams xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/DefaultHttpParams.java,v 1.9 2004/12/21 23:15:21 olegk Exp $
3    * $Revision: 510589 $
4    * $Date: 2007-02-22 18:04:52 +0100 (Thu, 22 Feb 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.params;
32  
33  import java.io.Serializable;
34  import java.util.HashMap;
35  
36  import org.apache.commons.logging.Log;
37  import org.apache.commons.logging.LogFactory;
38  
39  /**
40   * This class represents a collection of HTTP protocol parameters. Protocol parameters
41   * may be linked together to form a hierarchy. If a particular parameter value has not been
42   * explicitly defined in the collection itself, its value will be drawn from the parent 
43   * collection of parameters.
44   * 
45   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
46   * 
47   * @version $Revision: 510589 $
48   * 
49   * @since 3.0
50   */
51  public class DefaultHttpParams implements HttpParams, Serializable, Cloneable {
52  
53      /** Log object for this class. */
54      private static final Log LOG = LogFactory.getLog(DefaultHttpParams.class);
55  
56      /** HttpParams class factory. */
57      private static HttpParamsFactory httpParamsFactory = new DefaultHttpParamsFactory();
58  
59      /**
60       * Gets the default HttpParams to be used.
61       * 
62       * @return the value returned from <code>HttpParamsFactory#getDefaultParams()</code>
63       * 
64       * @see HttpParamsFactory#getDefaultParams()
65       */
66      public static HttpParams getDefaultParams() {
67          return httpParamsFactory.getDefaultParams();
68      }
69      
70      /**
71       * Sets the factory that will provide the default HttpParams.
72       * 
73       * @param httpParamsFactory an instance of HttpParamsFactory
74       * 
75       * @see #getDefaultParams()
76       */
77      public static void setHttpParamsFactory(HttpParamsFactory httpParamsFactory) {
78          if (httpParamsFactory == null) {
79              throw new IllegalArgumentException("httpParamsFactory may not be null");
80          }
81          DefaultHttpParams.httpParamsFactory = httpParamsFactory;
82      }
83  
84      /** The set of default values to defer to */
85      private HttpParams defaults = null;
86  
87      /** Hash map of HTTP parameters that this collection contains */
88      private HashMap parameters = null;
89      
90      /**
91       * Creates a new collection of parameters with the given parent. 
92       * The collection will defer to its parent for a default value 
93       * if a particular parameter is not explicitly set in the collection
94       * itself.
95       * 
96       * @param defaults the parent collection to defer to, if a parameter
97       * is not explictly set in the collection itself.
98       */
99      public DefaultHttpParams(final HttpParams defaults) {
100         super();
101         this.defaults = defaults; 
102     }
103     
104     /**
105      * Creates a new collection of parameters with the collection returned
106      * by {@link #getDefaultParams()} as a parent. The collection will defer
107      * to its parent for a default value if a particular parameter is not 
108      * explicitly set in the collection itself.
109      * 
110      * @see #getDefaultParams()
111      */
112     public DefaultHttpParams() {
113         this(getDefaultParams());
114     }
115     
116     public synchronized HttpParams getDefaults() {
117         return this.defaults;
118     }
119     
120     public synchronized void setDefaults(final HttpParams params) {
121         this.defaults = params;
122     }
123     
124     public synchronized Object getParameter(final String name) {
125         // See if the parameter has been explicitly defined
126         Object param = null;
127         if (this.parameters != null) {
128             param = this.parameters.get(name);
129         }    
130         if (param != null) {
131             // If so, return
132             return param;
133         } else {
134             // If not, see if defaults are available
135             if (this.defaults != null) {
136                 // Return default parameter value
137                 return this.defaults.getParameter(name);
138             } else {
139                 // Otherwise, return null
140                 return null;
141             }
142         }
143     }
144 
145     public synchronized void setParameter(final String name, final Object value) {
146         if (this.parameters == null) {
147             this.parameters = new HashMap();
148         }
149         this.parameters.put(name, value);
150         if (LOG.isDebugEnabled()) {
151             LOG.debug("Set parameter " + name + " = " + value);
152         }
153     }
154     
155     /**
156      * Assigns the value to all the parameter with the given names
157      * 
158      * @param names array of parameter name
159      * @param value parameter value
160      */ 
161     public synchronized void setParameters(final String[] names, final Object value) {
162         for (int i = 0; i < names.length; i++) {
163             setParameter(names[i], value);
164         }
165     }
166 
167     public long getLongParameter(final String name, long defaultValue) { 
168         Object param = getParameter(name);
169         if (param == null) {
170             return defaultValue;
171         }
172         return ((Long)param).longValue();
173     }
174     
175     public void setLongParameter(final String name, long value) {
176         setParameter(name, new Long(value));
177     }
178 
179     public int getIntParameter(final String name, int defaultValue) { 
180         Object param = getParameter(name);
181         if (param == null) {
182             return defaultValue;
183         }
184         return ((Integer)param).intValue();
185     }
186     
187     public void setIntParameter(final String name, int value) {
188         setParameter(name, new Integer(value));
189     }
190 
191     public double getDoubleParameter(final String name, double defaultValue) { 
192         Object param = getParameter(name);
193         if (param == null) {
194             return defaultValue;
195         }
196         return ((Double)param).doubleValue();
197     }
198     
199     public void setDoubleParameter(final String name, double value) {
200         setParameter(name, new Double(value));
201     }
202 
203     public boolean getBooleanParameter(final String name, boolean defaultValue) { 
204         Object param = getParameter(name);
205         if (param == null) {
206             return defaultValue;
207         }
208         return ((Boolean)param).booleanValue();
209     }
210     
211     public void setBooleanParameter(final String name, boolean value) {
212         setParameter(name, value ? Boolean.TRUE : Boolean.FALSE);// Boolean.valueOf() = Java 1.4+
213     }
214 
215     public boolean isParameterSet(final String name) {
216         return getParameter(name) != null;
217     }
218         
219     public boolean isParameterSetLocally(final String name) {
220         return this.parameters != null && this.parameters.get(name) != null;
221     }
222         
223     public boolean isParameterTrue(final String name) {
224         return getBooleanParameter(name, false);
225     }
226         
227     public boolean isParameterFalse(final String name) {
228         return !getBooleanParameter(name, false);
229     }
230 
231     /**
232      * Removes all parameters from this collection. 
233      */
234     public void clear() {
235         this.parameters = null;
236     }
237 
238     /**
239      * Clones this collection of parameters. Please note that paramter values
240      * themselves are not cloned. 
241      * 
242      * @see java.io.Serializable
243      * @see java.lang.Object#clone()
244      */
245     public Object clone() throws CloneNotSupportedException
246     {
247         DefaultHttpParams clone = (DefaultHttpParams)super.clone();
248         if (this.parameters != null) {
249             clone.parameters = (HashMap)this.parameters.clone(); 
250         }
251         clone.setDefaults(this.defaults);
252         return clone;
253     }
254 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.html100644 0 0 34401 10661532627 31213 0ustar 0 0 DefaultHttpParamsFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.java,v 1.16 2004/11/20 21:48:47 mbecke Exp $
3    * $Revision: 566065 $
4    * $Date: 2007-08-15 10:34:30 +0200 (Wed, 15 Aug 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30   
31  package org.apache.commons.httpclient.params;
32  
33  import java.util.ArrayList;
34  import java.util.Arrays;
35  
36  import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
37  import org.apache.commons.httpclient.HttpVersion;
38  import org.apache.commons.httpclient.SimpleHttpConnectionManager;
39  import org.apache.commons.httpclient.cookie.CookiePolicy;
40  import org.apache.commons.httpclient.util.DateUtil;
41  
42  /**
43   * @since 3.0
44   */
45  public class DefaultHttpParamsFactory implements HttpParamsFactory {
46  
47      private HttpParams httpParams;
48  
49      /**
50       * 
51       */
52      public DefaultHttpParamsFactory() {
53          super();
54      }
55  
56      /* (non-Javadoc)
57       * @see org.apache.commons.httpclient.params.HttpParamsFactory#getDefaultParams()
58       */
59      public synchronized HttpParams getDefaultParams() {
60          if (httpParams == null) {
61              httpParams = createParams();
62          }
63  
64          return httpParams;
65      }
66  
67      protected HttpParams createParams() {
68          HttpClientParams params = new HttpClientParams(null);
69          
70          params.setParameter(HttpMethodParams.USER_AGENT, "Jakarta Commons-HttpClient/3.1");
71          params.setVersion(HttpVersion.HTTP_1_1);
72          params.setConnectionManagerClass(SimpleHttpConnectionManager.class);
73          params.setCookiePolicy(CookiePolicy.DEFAULT);
74          params.setHttpElementCharset("US-ASCII");
75          params.setContentCharset("ISO-8859-1");
76          params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
77          
78          ArrayList datePatterns = new ArrayList();
79          datePatterns.addAll(
80              Arrays.asList(
81                  new String[] {
82                      DateUtil.PATTERN_RFC1123,
83                      DateUtil.PATTERN_RFC1036,
84                      DateUtil.PATTERN_ASCTIME,
85                      "EEE, dd-MMM-yyyy HH:mm:ss z",
86                      "EEE, dd-MMM-yyyy HH-mm-ss z",
87                      "EEE, dd MMM yy HH:mm:ss z",
88                      "EEE dd-MMM-yyyy HH:mm:ss z",
89                      "EEE dd MMM yyyy HH:mm:ss z",
90                      "EEE dd-MMM-yyyy HH-mm-ss z",
91                      "EEE dd-MMM-yy HH:mm:ss z",
92                      "EEE dd MMM yy HH:mm:ss z",
93                      "EEE,dd-MMM-yy HH:mm:ss z",
94                      "EEE,dd-MMM-yyyy HH:mm:ss z",
95                      "EEE, dd-MM-yyyy HH:mm:ss z",                
96                  }
97              )
98          );
99          params.setParameter(HttpMethodParams.DATE_PATTERNS, datePatterns);
100             
101         // TODO: To be removed. Provided for backward compatibility
102         String agent = null;
103         try {
104             agent = System.getProperty("httpclient.useragent");
105         } catch (SecurityException ignore) {
106         }
107         if (agent != null) {        
108             params.setParameter(HttpMethodParams.USER_AGENT, agent);
109         }
110         
111         // TODO: To be removed. Provided for backward compatibility
112         String preemptiveDefault = null;
113         try {
114             preemptiveDefault = System.getProperty("httpclient.authentication.preemptive");
115         } catch (SecurityException ignore) {
116         }
117         if (preemptiveDefault != null) {
118             preemptiveDefault = preemptiveDefault.trim().toLowerCase();
119             if (preemptiveDefault.equals("true")) {
120                 params.setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, Boolean.TRUE);
121             } else if (preemptiveDefault.equals("false")) {
122                 params.setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, Boolean.FALSE);
123             }
124         }
125         
126         // TODO: To be removed. Provided for backward compatibility
127         String defaultCookiePolicy = null;
128         try {
129             defaultCookiePolicy = System.getProperty("apache.commons.httpclient.cookiespec");
130         } catch (SecurityException ignore) {
131         }
132         if (defaultCookiePolicy != null) {
133             if ("COMPATIBILITY".equalsIgnoreCase(defaultCookiePolicy)) {
134                 params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
135             } else if ("NETSCAPE_DRAFT".equalsIgnoreCase(defaultCookiePolicy)) {
136                 params.setCookiePolicy(CookiePolicy.NETSCAPE);
137             } else if ("RFC2109".equalsIgnoreCase(defaultCookiePolicy)) {
138                 params.setCookiePolicy(CookiePolicy.RFC_2109);
139             }
140         }
141 
142         return params;
143     } 
144 
145 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/HostParams.html100644 0 0 23130 10661532627 26351 0ustar 0 0 HostParams xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HostParams.java,v 1.5 2004/10/06 17:32:04 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.params;
32  
33  /**
34   * This class represents a collection of HTTP protocol parameters applicable to 
35   * {@link org.apache.commons.httpclient.HostConfiguration instances of HostConfiguration}. 
36   * Protocol parameters may be linked together to form a hierarchy. If a particular 
37   * parameter value has not been explicitly defined in the collection itself, its 
38   * value will be drawn from the parent collection of parameters.
39   * 
40   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
41   * 
42   * @version $Revision: 480424 $
43   * 
44   * @since 3.0
45   */
46  public class HostParams extends DefaultHttpParams {
47  
48      /**
49       * Defines the request headers to be sent per default with each request.
50       * <p>
51       * This parameter expects a value of type {@link java.util.Collection}. The 
52       * collection is expected to contain {@link org.apache.commons.httpclient.Header}s. 
53       * </p>
54       */
55      public static final String DEFAULT_HEADERS = "http.default-headers"; 
56  
57      /**
58       * Creates a new collection of parameters with the collection returned
59       * by {@link #getDefaultParams()} as a parent. The collection will defer
60       * to its parent for a default value if a particular parameter is not 
61       * explicitly set in the collection itself.
62       * 
63       * @see #getDefaultParams()
64       */
65      public HostParams() {
66          super();
67      }
68  
69      /**
70       * Creates a new collection of parameters with the given parent. 
71       * The collection will defer to its parent for a default value 
72       * if a particular parameter is not explicitly set in the collection
73       * itself.
74       * 
75       * @param defaults the parent collection to defer to, if a parameter
76       * is not explictly set in the collection itself.
77       *
78       * @see #getDefaultParams()
79       */
80      public HostParams(HttpParams defaults) {
81          super(defaults);
82      }
83      
84      /**
85       * Sets the virtual host name.
86       * 
87       * @param hostname The host name
88       */
89      public void setVirtualHost(final String hostname) {
90          setParameter(HttpMethodParams.VIRTUAL_HOST, hostname);
91      }
92  
93      /**
94       * Returns the virtual host name.
95       * 
96       * @return The virtual host name
97       */
98      public String getVirtualHost() {
99          return (String) getParameter(HttpMethodParams.VIRTUAL_HOST);
100     }
101         
102 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/HttpClientParams.html100644 0 0 45163 10661532627 27524 0ustar 0 0 HttpClientParams xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpClientParams.java,v 1.7 2004/05/13 04:01:22 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.params;
32  
33  /**
34   * This class represents a collection of HTTP protocol parameters applicable to 
35   * {@link org.apache.commons.httpclient.HttpClient instances of HttpClient}. 
36   * Protocol parameters may be linked together to form a hierarchy. If a particular 
37   * parameter value has not been explicitly defined in the collection itself, its 
38   * value will be drawn from the parent collection of parameters.
39   * 
40   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
41   * 
42   * @version $Revision: 480424 $
43   * 
44   * @since 3.0
45   */
46  public class HttpClientParams extends HttpMethodParams {
47  
48      /**
49       * Sets the timeout in milliseconds used when retrieving an 
50       * {@link org.apache.commons.httpclient.HttpConnection HTTP connection} from the
51       * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}.
52       * <p>
53       * This parameter expects a value of type {@link Long}.
54       * </p>
55       */ 
56      public static final String CONNECTION_MANAGER_TIMEOUT = "http.connection-manager.timeout"; 
57  
58      /**
59       * Defines the default 
60       * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}
61       * class.
62       * <p>
63       * This parameter expects a value of type {@link Class}.
64       * </p>
65       */ 
66      public static final String CONNECTION_MANAGER_CLASS = "http.connection-manager.class"; 
67  
68      /**
69       * Defines whether authentication should be attempted preemptively.
70       * <p>
71       * This parameter expects a value of type {@link Boolean}.
72       * </p>
73       */
74      public static final String PREEMPTIVE_AUTHENTICATION = "http.authentication.preemptive";
75  
76      /**
77       * Defines whether relative redirects should be rejected.
78       * <p>
79       * This parameter expects a value of type {@link Boolean}.
80       * </p>
81       */
82      public static final String REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect"; 
83  
84      /** 
85       * Defines the maximum number of redirects to be followed. 
86       * The limit on number of redirects is intended to prevent infinite loops. 
87       * <p>
88       * This parameter expects a value of type {@link Integer}.
89       * </p>
90       */
91      public static final String MAX_REDIRECTS = "http.protocol.max-redirects";
92  
93      /** 
94       * Defines whether circular redirects (redirects to the same location) should be allowed. 
95       * The HTTP spec is not sufficiently clear whether circular redirects are permitted, 
96       * therefore optionally they can be enabled
97       * <p>
98       * This parameter expects a value of type {@link Boolean}.
99       * </p>
100      */
101     public static final String ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects";
102 
103     /**
104      * Creates a new collection of parameters with the collection returned
105      * by {@link #getDefaultParams()} as a parent. The collection will defer
106      * to its parent for a default value if a particular parameter is not 
107      * explicitly set in the collection itself.
108      * 
109      * @see #getDefaultParams()
110      */
111     public HttpClientParams() {
112         super();
113     }
114 
115     /**
116      * Creates a new collection of parameters with the given parent. 
117      * The collection will defer to its parent for a default value 
118      * if a particular parameter is not explicitly set in the collection
119      * itself.
120      * 
121      * @param defaults the parent collection to defer to, if a parameter
122      * is not explictly set in the collection itself.
123      *
124      * @see #getDefaultParams()
125      */
126     public HttpClientParams(HttpParams defaults) {
127         super(defaults);
128     }
129 
130     /**
131      * Returns the timeout in milliseconds used when retrieving an 
132      * {@link org.apache.commons.httpclient.HttpConnection HTTP connection} from the
133      * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}.
134      * 
135      * @return timeout in milliseconds.
136      */ 
137     public long getConnectionManagerTimeout() {
138         return getLongParameter(CONNECTION_MANAGER_TIMEOUT, 0);
139     }
140 
141     /**
142      * Sets the timeout in milliseconds used when retrieving an 
143      * {@link org.apache.commons.httpclient.HttpConnection HTTP connection} from the
144      * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}.
145      * 
146      * @param timeout the timeout in milliseconds
147      */ 
148     public void setConnectionManagerTimeout(long timeout) {
149         setLongParameter(CONNECTION_MANAGER_TIMEOUT, timeout);
150     }
151 
152     /**
153      * Returns the default 
154      * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}
155      * class.
156      * @return {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}
157      * factory class.
158      */ 
159     public Class getConnectionManagerClass() {
160         return (Class) getParameter(CONNECTION_MANAGER_CLASS);
161     }
162 
163     /**
164      * Sets {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}
165      * class to be used der default.
166      * @param clazz 
167      *  {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}
168      *  factory class.
169      */ 
170     public void setConnectionManagerClass(Class clazz) {
171         setParameter(CONNECTION_MANAGER_CLASS, clazz);
172     }
173     
174     /**
175      * Returns <tt>true</tt> if authentication should be attempted preemptively, 
176      * <tt>false</tt> otherwise.
177      * 
178      * @return <tt>true</tt> if authentication should be attempted preemptively,
179      *   <tt>false</tt> otherwise.
180      */
181     public boolean isAuthenticationPreemptive() {
182         return getBooleanParameter(PREEMPTIVE_AUTHENTICATION, false); 
183     }
184 
185     /**
186      * Sets whether authentication should be attempted preemptively.
187      * 
188      * @param value <tt>true</tt> if authentication should be attempted preemptively,
189      *   <tt>false</tt> otherwise.
190      */
191     public void setAuthenticationPreemptive(boolean value) {
192         setBooleanParameter(PREEMPTIVE_AUTHENTICATION, value); 
193     }
194 
195     private static final String[] PROTOCOL_STRICTNESS_PARAMETERS = {
196         REJECT_RELATIVE_REDIRECT,
197         ALLOW_CIRCULAR_REDIRECTS
198     };
199 
200 
201     public void makeStrict() {
202         super.makeStrict();
203         setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.TRUE);
204     }
205 
206 
207     public void makeLenient() {
208         super.makeLenient();
209         setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.FALSE);
210     }
211 }

././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/HttpConnectionManagerParams.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/HttpConnectionManagerParams.ht100644 0 0 42373 10661532627 31347 0ustar 0 0 HttpConnectionManagerParams xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpConnectionManagerParams.java,v 1.9 2004/09/13 16:25:20 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.params;
32  
33  import java.util.HashMap;
34  import java.util.Map;
35  
36  import org.apache.commons.httpclient.HostConfiguration;
37  import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
38  
39  /**
40   * This class represents a collection of HTTP protocol parameters applicable to 
41   * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection managers}. 
42   * Protocol parameters may be linked together to form a hierarchy. If a particular 
43   * parameter value has not been explicitly defined in the collection itself, its 
44   * value will be drawn from the parent collection of parameters.
45   * 
46   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
47   * @author Michael Becke
48   * 
49   * @version $Revision: 480424 $
50   * 
51   * @since 3.0
52   */
53  public class HttpConnectionManagerParams extends HttpConnectionParams {
54  
55      /** 
56       * Defines the maximum number of connections allowed per host configuration. 
57       * These values only apply to the number of connections from a particular instance 
58       * of HttpConnectionManager.
59       * <p>
60       * This parameter expects a value of type {@link java.util.Map}.  The value
61       * should map instances of {@link org.apache.commons.httpclient.HostConfiguration}
62       * to {@link Integer integers}.  The default value can be specified using
63       * {@link org.apache.commons.httpclient.HostConfiguration#ANY_HOST_CONFIGURATION}.
64       * </p>
65       */
66      public static final String MAX_HOST_CONNECTIONS = "http.connection-manager.max-per-host";
67  
68      /** 
69       * Defines the maximum number of connections allowed overall. This value only applies
70       * to the number of connections from a particular instance of HttpConnectionManager.
71       * <p>
72       * This parameter expects a value of type {@link Integer}.
73       * </p>
74       */
75      public static final String MAX_TOTAL_CONNECTIONS = "http.connection-manager.max-total";
76      
77      /**
78       * Sets the default maximum number of connections allowed for a given
79       * host config.
80       *
81       * @param maxHostConnections The default maximum.
82       * 
83       * @see #MAX_HOST_CONNECTIONS
84       */
85      public void setDefaultMaxConnectionsPerHost(int maxHostConnections) {
86          setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, maxHostConnections);
87      }
88  
89      /**
90       * Sets the maximum number of connections to be used for the given host config.
91       * 
92       * @param hostConfiguration The host config to set the maximum for.  Use 
93       * {@link HostConfiguration#ANY_HOST_CONFIGURATION} to configure the default value
94       * per host.
95       * @param maxHostConnections The maximum number of connections, <code>> 0</code>
96       * 
97       * @see #MAX_HOST_CONNECTIONS
98       */
99      public void setMaxConnectionsPerHost(
100         HostConfiguration hostConfiguration,
101         int maxHostConnections) {
102         
103         if (maxHostConnections <= 0) {
104             throw new IllegalArgumentException("maxHostConnections must be greater than 0");
105         }
106         
107         Map currentValues = (Map) getParameter(MAX_HOST_CONNECTIONS);
108         // param values are meant to be immutable so we'll make a copy
109         // to modify
110         Map newValues = null;
111         if (currentValues == null) {
112             newValues = new HashMap();
113         } else {
114             newValues = new HashMap(currentValues);
115         }
116         newValues.put(hostConfiguration, new Integer(maxHostConnections));
117         setParameter(MAX_HOST_CONNECTIONS, newValues);
118     }
119     
120     /**
121      * Gets the default maximum number of connections allowed for a given
122      * host config.
123      *
124      * @return The default maximum.
125      * 
126      * @see #MAX_HOST_CONNECTIONS
127      */
128     public int getDefaultMaxConnectionsPerHost() {
129         return getMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION);
130     }
131 
132     /**
133      * Gets the maximum number of connections to be used for a particular host config.  If
134      * the value has not been specified for the given host the default value will be
135      * returned.
136      * 
137      * @param hostConfiguration The host config.
138      * @return The maximum number of connections to be used for the given host config.
139      * 
140      * @see #MAX_HOST_CONNECTIONS
141      */
142     public int getMaxConnectionsPerHost(HostConfiguration hostConfiguration) {
143         
144         Map m = (Map) getParameter(MAX_HOST_CONNECTIONS);
145         if (m == null) {
146             // MAX_HOST_CONNECTIONS have not been configured, using the default value
147             return MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS;
148         } else {
149             Integer max = (Integer) m.get(hostConfiguration);
150             if (max == null && hostConfiguration != HostConfiguration.ANY_HOST_CONFIGURATION) {
151                 // the value has not been configured specifically for this host config,
152                 // use the default value
153                 return getMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION);
154             } else {
155                 return (
156                         max == null 
157                         ? MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS 
158                         : max.intValue()
159                     );
160             }
161         }
162     }
163 
164     /**
165      * Sets the maximum number of connections allowed.
166      *
167      * @param maxTotalConnections The maximum number of connections allowed.
168      * 
169      * @see #MAX_TOTAL_CONNECTIONS
170      */
171     public void setMaxTotalConnections(int maxTotalConnections) {
172         setIntParameter(
173             HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS,
174             maxTotalConnections);
175     }
176 
177     /**
178      * Gets the maximum number of connections allowed.
179      *
180      * @return The maximum number of connections allowed.
181      * 
182      * @see #MAX_TOTAL_CONNECTIONS
183      */
184     public int getMaxTotalConnections() {
185         return getIntParameter(
186             HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS,
187             MultiThreadedHttpConnectionManager.DEFAULT_MAX_TOTAL_CONNECTIONS);
188     }
189 
190 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/HttpConnectionParams.html100644 0 0 66061 10661532627 30405 0ustar 0 0 HttpConnectionParams xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpConnectionParams.java,v 1.6 2004/09/15 20:32:21 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.params;
32  
33  /**
34   * This class represents a collection of HTTP protocol parameters applicable to 
35   * {@link org.apache.commons.httpclient.HttpConnection HTTP connections}. 
36   * Protocol parameters may be linked together to form a hierarchy. If a particular 
37   * parameter value has not been explicitly defined in the collection itself, its 
38   * value will be drawn from the parent collection of parameters.
39   * 
40   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
41   * 
42   * @version $Revision: 480424 $
43   * 
44   * @since 3.0
45   */
46  public class HttpConnectionParams extends DefaultHttpParams {
47  
48      /**
49       * Defines the default socket timeout (<tt>SO_TIMEOUT</tt>) in milliseconds which is the 
50       * timeout for waiting for data. A timeout value of zero is interpreted as an infinite 
51       * timeout. This value is used when no socket timeout is set in the 
52       * {@link HttpMethodParams HTTP method parameters}. 
53       * <p>
54       * This parameter expects a value of type {@link Integer}.
55       * </p>
56       * @see java.net.SocketOptions#SO_TIMEOUT
57       */
58      public static final String SO_TIMEOUT = "http.socket.timeout"; 
59  
60      /**
61       * Determines whether Nagle's algorithm is to be used. The Nagle's algorithm 
62       * tries to conserve bandwidth by minimizing the number of segments that are 
63       * sent. When applications wish to decrease network latency and increase 
64       * performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). 
65       * Data will be sent earlier, at the cost of an increase in bandwidth consumption. 
66       * <p>
67       * This parameter expects a value of type {@link Boolean}.
68       * </p>
69       * @see java.net.SocketOptions#TCP_NODELAY
70       */
71      public static final String TCP_NODELAY = "http.tcp.nodelay"; 
72  
73      /**
74       * Determines a hint the size of the underlying buffers used by the platform 
75       * for outgoing network I/O. This value is a suggestion to the kernel from 
76       * the application about the size of buffers to use for the data to be sent 
77       * over the socket.
78       * <p>
79       * This parameter expects a value of type {@link Integer}.
80       * </p>
81       * @see java.net.SocketOptions#SO_SNDBUF
82       */
83      public static final String SO_SNDBUF = "http.socket.sendbuffer"; 
84  
85      /**
86       * Determines a hint the size of the underlying buffers used by the platform 
87       * for incoming network I/O. This value is a suggestion to the kernel from 
88       * the application about the size of buffers to use for the data to be received 
89       * over the socket.  
90       * <p>
91       * This parameter expects a value of type {@link Integer}.
92       * </p>
93       * @see java.net.SocketOptions#SO_RCVBUF
94       */
95      public static final String SO_RCVBUF = "http.socket.receivebuffer"; 
96  
97      /**
98       * Sets SO_LINGER with the specified linger time in seconds. The maximum timeout 
99       * value is platform specific. Value <tt>0</tt> implies that the option is disabled.
100      * Value <tt>-1</tt> implies that the JRE default is used. The setting only affects 
101      * socket close.  
102      * <p>
103      * This parameter expects a value of type {@link Integer}.
104      * </p>
105      * @see java.net.SocketOptions#SO_LINGER
106      */
107     public static final String SO_LINGER = "http.socket.linger"; 
108 
109     /**
110      * Determines the timeout until a connection is etablished. A value of zero 
111      * means the timeout is not used. The default value is zero.
112      * <p>
113      * This parameter expects a value of type {@link Integer}.
114      * </p>
115      */
116     public static final String CONNECTION_TIMEOUT = "http.connection.timeout"; 
117 
118     /**
119      * Determines whether stale connection check is to be used. Disabling 
120      * stale connection check may result in slight performance improvement 
121      * at the risk of getting an I/O error when executing a request over a
122      * connection that has been closed at the server side. 
123      * <p>
124      * This parameter expects a value of type {@link Boolean}.
125      * </p>
126      */
127     public static final String STALE_CONNECTION_CHECK = "http.connection.stalecheck"; 
128 
129     /**
130      * Creates a new collection of parameters with the collection returned
131      * by {@link #getDefaultParams()} as a parent. The collection will defer
132      * to its parent for a default value if a particular parameter is not 
133      * explicitly set in the collection itself.
134      * 
135      * @see #getDefaultParams()
136      */
137     public HttpConnectionParams() {
138         super();
139     }
140 
141     /**
142      * Returns the default socket timeout (<tt>SO_TIMEOUT</tt>) in milliseconds which is the 
143      * timeout for waiting for data. A timeout value of zero is interpreted as an infinite 
144      * timeout. This value is used when no socket timeout is set in the 
145      * {@link HttpMethodParams HTTP method parameters}. 
146      *
147      * @return timeout in milliseconds
148      */
149     public int getSoTimeout() {
150         return getIntParameter(SO_TIMEOUT, 0);
151     }
152 
153     /**
154      * Sets the default socket timeout (<tt>SO_TIMEOUT</tt>) in milliseconds which is the 
155      * timeout for waiting for data. A timeout value of zero is interpreted as an infinite 
156      * timeout. This value is used when no socket timeout is set in the 
157      * {@link HttpMethodParams HTTP method parameters}. 
158      *
159      * @param timeout Timeout in milliseconds
160      */
161     public void setSoTimeout(int timeout) {
162         setIntParameter(SO_TIMEOUT, timeout);
163     }
164 
165     /**
166      * Determines whether Nagle's algorithm is to be used. The Nagle's algorithm 
167      * tries to conserve bandwidth by minimizing the number of segments that are 
168      * sent. When applications wish to decrease network latency and increase 
169      * performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). 
170      * Data will be sent earlier, at the cost of an increase in bandwidth consumption. 
171      *
172      * @param value <tt>true</tt> if the Nagle's algorithm is to NOT be used
173      *   (that is enable TCP_NODELAY), <tt>false</tt> otherwise.
174      */
175     public void setTcpNoDelay(boolean value) {
176         setBooleanParameter(TCP_NODELAY, value);
177     }
178 
179     /**
180      * Tests if Nagle's algorithm is to be used.  
181      *
182      * @return <tt>true</tt> if the Nagle's algorithm is to NOT be used
183      *   (that is enable TCP_NODELAY), <tt>false</tt> otherwise.
184      */
185     public boolean getTcpNoDelay() {
186         return getBooleanParameter(TCP_NODELAY, true);
187     }
188 
189     /**
190      * Returns a hint the size of the underlying buffers used by the platform for 
191      * outgoing network I/O. This value is a suggestion to the kernel from the 
192      * application about the size of buffers to use for the data to be sent over 
193      * the socket.
194      *
195      * @return the hint size of the send buffer
196      */
197     public int getSendBufferSize() {
198         return getIntParameter(SO_SNDBUF, -1);
199     }
200 
201     /**
202      * Sets a hint the size of the underlying buffers used by the platform for 
203      * outgoing network I/O. This value is a suggestion to the kernel from the 
204      * application about the size of buffers to use for the data to be sent over 
205      * the socket.
206      *
207      * @param size the hint size of the send buffer
208      */
209     public void setSendBufferSize(int size) {
210         setIntParameter(SO_SNDBUF, size);
211     }
212 
213     /**
214      * Returns a hint the size of the underlying buffers used by the platform 
215      * for incoming network I/O. This value is a suggestion to the kernel from 
216      * the application about the size of buffers to use for the data to be received 
217      * over the socket.  
218      *
219      * @return the hint size of the send buffer
220      */
221     public int getReceiveBufferSize() {
222         return getIntParameter(SO_RCVBUF, -1);
223     }
224 
225     /**
226      * Sets a hint the size of the underlying buffers used by the platform 
227      * for incoming network I/O. This value is a suggestion to the kernel from 
228      * the application about the size of buffers to use for the data to be received 
229      * over the socket.  
230      *
231      * @param size the hint size of the send buffer
232      */
233     public void setReceiveBufferSize(int size) {
234         setIntParameter(SO_RCVBUF, size);
235     }
236 
237     /**
238      * Returns linger-on-close timeout. Value <tt>0</tt> implies that the option is 
239      * disabled. Value <tt>-1</tt> implies that the JRE default is used.
240      * 
241      * @return the linger-on-close timeout
242      */
243     public int getLinger() {
244         return getIntParameter(SO_LINGER, -1);
245     }
246 
247     /**
248      * Returns linger-on-close timeout. This option disables/enables immediate return 
249      * from a close() of a TCP Socket. Enabling this option with a non-zero Integer 
250      * timeout means that a close() will block pending the transmission and 
251      * acknowledgement of all data written to the peer, at which point the socket is 
252      * closed gracefully. Value <tt>0</tt> implies that the option is 
253      * disabled. Value <tt>-1</tt> implies that the JRE default is used.
254      *
255      * @param value the linger-on-close timeout
256      */
257     public void setLinger(int value) {
258         setIntParameter(SO_LINGER, value);
259     }
260 
261     /**
262      * Returns the timeout until a connection is etablished. A value of zero 
263      * means the timeout is not used. The default value is zero.
264      * 
265      * @return timeout in milliseconds.
266      */
267     public int getConnectionTimeout() {
268         return getIntParameter(CONNECTION_TIMEOUT, 0);
269     }
270 
271     /**
272      * Sets the timeout until a connection is etablished. A value of zero 
273      * means the timeout is not used. The default value is zero.
274      * 
275      * @param timeout Timeout in milliseconds.
276      */
277     public void setConnectionTimeout(int timeout) {
278         setIntParameter(CONNECTION_TIMEOUT, timeout);
279     }
280     
281     /**
282      * Tests whether stale connection check is to be used. Disabling 
283      * stale connection check may result in slight performance improvement 
284      * at the risk of getting an I/O error when executing a request over a
285      * connection that has been closed at the server side. 
286      * 
287      * @return <tt>true</tt> if stale connection check is to be used, 
288      *   <tt>false</tt> otherwise.
289      */
290     public boolean isStaleCheckingEnabled() {
291         return getBooleanParameter(STALE_CONNECTION_CHECK, true);
292     }
293 
294     /**
295      * Defines whether stale connection check is to be used. Disabling 
296      * stale connection check may result in slight performance improvement 
297      * at the risk of getting an I/O error when executing a request over a
298      * connection that has been closed at the server side. 
299      * 
300      * @param value <tt>true</tt> if stale connection check is to be used, 
301      *   <tt>false</tt> otherwise.
302      */
303     public void setStaleCheckingEnabled(boolean value) {
304         setBooleanParameter(STALE_CONNECTION_CHECK, value);
305     }
306 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/HttpMethodParams.html100644 0 0 127444 10661532627 27551 0ustar 0 0 HttpMethodParams xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpMethodParams.java,v 1.17 2004/10/06 17:32:04 olegk Exp $
3    * $Revision: 483949 $
4    * $Date: 2006-12-08 12:34:50 +0100 (Fri, 08 Dec 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.params;
32  
33  import org.apache.commons.httpclient.HttpVersion;
34  import org.apache.commons.httpclient.cookie.CookiePolicy;
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  
38  /**
39   * This class represents a collection of HTTP protocol parameters applicable to 
40   * {@link org.apache.commons.httpclient.HttpMethod HTTP methods}. Protocol 
41   * parameters may be linked together to form a hierarchy. If a particular 
42   * parameter value has not been explicitly defined in the collection itself, 
43   * its value will be drawn from the parent collection of parameters.
44   * 
45   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
46   * @author Christian Kohlschuetter
47   * 
48   * @version $Revision: 483949 $
49   * 
50   * @since 3.0
51   */
52  public class HttpMethodParams extends DefaultHttpParams {
53  
54      /** Log object for this class. */
55      private static final Log LOG = LogFactory.getLog(HttpMethodParams.class);
56  
57      /**
58       * Defines the content of the <tt>User-Agent</tt> header used by  
59       * {@link org.apache.commons.httpclient.HttpMethod HTTP methods}.
60       * <p>
61       * This parameter expects a value of type {@link String}.
62       * </p>
63       */
64      public static final String USER_AGENT = "http.useragent"; 
65  
66      /**
67       * Defines the {@link HttpVersion HTTP protocol version} used by  
68       * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} per
69       * default.
70       * <p>
71       * This parameter expects a value of type {@link HttpVersion}.
72       * </p>
73       */
74      public static final String PROTOCOL_VERSION = "http.protocol.version"; 
75  
76      /**
77       * Defines whether {@link org.apache.commons.httpclient.HttpMethod HTTP methods} should
78       * reject ambiguous {@link org.apache.commons.httpclient.StatusLine HTTP status line}.
79       * <p>
80       * This parameter expects a value of type {@link Boolean}.
81       * </p>
82       */
83      public static final String UNAMBIGUOUS_STATUS_LINE = "http.protocol.unambiguous-statusline"; 
84  
85      /**
86       * Defines whether {@link org.apache.commons.httpclient.Cookie cookies} should be put on 
87       * a single {@link org.apache.commons.httpclient.Header response header}.
88       * <p>
89       * This parameter expects a value of type {@link Boolean}.
90       * </p>
91       */
92      public static final String SINGLE_COOKIE_HEADER = "http.protocol.single-cookie-header"; 
93  
94      /**
95       * Defines whether responses with an invalid <tt>Transfer-Encoding</tt> header should be 
96       * rejected.
97       * <p>
98       * This parameter expects a value of type {@link Boolean}.
99       * </p>
100      */
101     public static final String STRICT_TRANSFER_ENCODING = "http.protocol.strict-transfer-encoding"; 
102 
103     /**
104      * Defines whether the content body sent in response to 
105      * {@link org.apache.commons.httpclient.methods.HeadMethod} should be rejected.
106      * <p>
107      * This parameter expects a value of type {@link Boolean}.
108      * </p>
109      */
110     public static final String REJECT_HEAD_BODY = "http.protocol.reject-head-body"; 
111 
112     /**
113      * Sets period of time in milliseconds to wait for a content body sent in response to 
114      * {@link org.apache.commons.httpclient.methods.HeadMethod HEAD method} from a 
115      * non-compliant server. If the parameter is not set or set to <tt>-1</tt> non-compliant 
116      * response body check is disabled.
117      * <p>
118      * This parameter expects a value of type {@link Integer}.
119      * </p>
120      */
121     public static final String HEAD_BODY_CHECK_TIMEOUT = "http.protocol.head-body-timeout"; 
122 
123     /**
124      * <p>
125      * Activates 'Expect: 100-Continue' handshake for the 
126      * {@link org.apache.commons.httpclient.methods.ExpectContinueMethod 
127      * entity enclosing methods}. The purpose of the 'Expect: 100-Continue'
128      * handshake to allow a client that is sending a request message with 
129      * a request body to determine if the origin server is willing to 
130      * accept the request (based on the request headers) before the client
131      * sends the request body.
132      * </p>
133      * 
134      * <p>
135      * The use of the 'Expect: 100-continue' handshake can result in 
136      * noticable peformance improvement for entity enclosing requests
137      * (such as POST and PUT) that require the target server's 
138      * authentication.
139      * </p>
140      * 
141      * <p>
142      * 'Expect: 100-continue' handshake should be used with 
143      * caution, as it may cause problems with HTTP servers and 
144      * proxies that do not support HTTP/1.1 protocol.
145      * </p>
146      * 
147      * This parameter expects a value of type {@link Boolean}.
148      */
149     public static final String USE_EXPECT_CONTINUE = "http.protocol.expect-continue"; 
150 
151     /**
152      * Defines the charset to be used when encoding 
153      * {@link org.apache.commons.httpclient.Credentials}. If not defined then the 
154      * {@link #HTTP_ELEMENT_CHARSET} should be used.
155      * <p>
156      * This parameter expects a value of type {@link String}.
157      * </p>
158      */
159     public static final String CREDENTIAL_CHARSET = "http.protocol.credential-charset"; 
160     
161     /**
162      * Defines the charset to be used for encoding HTTP protocol elements.
163      * <p>
164      * This parameter expects a value of type {@link String}.
165      * </p>
166      */
167     public static final String HTTP_ELEMENT_CHARSET = "http.protocol.element-charset"; 
168     
169     /**
170      * Defines the charset to be used for parsing URIs.
171      * <p>
172      * This parameter expects a value of type {@link String}.
173      * </p>
174      */
175     public static final String HTTP_URI_CHARSET = "http.protocol.uri-charset"; 
176     
177     /**
178      * Defines the charset to be used for encoding content body.
179      * <p>
180      * This parameter expects a value of type {@link String}.
181      * </p>
182      */
183     public static final String HTTP_CONTENT_CHARSET = "http.protocol.content-charset"; 
184     
185     /**
186      * Defines {@link CookiePolicy cookie policy} to be used for cookie management.
187      * <p>
188      * This parameter expects a value of type {@link String}.
189      * </p>
190      */
191     public static final String COOKIE_POLICY = "http.protocol.cookie-policy";
192     
193     /**
194      * Defines HttpClient's behavior when a response provides more bytes than
195      * expected (specified with Content-Length, for example).
196      * <p>
197      * Such surplus data makes the HTTP connection unreliable for keep-alive
198      * requests, as malicious response data (faked headers etc.) can lead to undesired
199      * results on the next request using that connection.
200      * </p>
201      * <p>
202      * If this parameter is set to <code>true</code>, any detection of extra
203      * input data will generate a warning in the log.
204      * </p>
205      * <p>
206      * This parameter expects a value of type {@link Boolean}.
207      * </p>
208      */
209     public static final String WARN_EXTRA_INPUT = "http.protocol.warn-extra-input";
210     
211     /**
212      * Defines the maximum number of ignorable lines before we expect
213      * a HTTP response's status code.
214      * <p>
215      * With HTTP/1.1 persistent connections, the problem arises that
216      * broken scripts could return a wrong Content-Length
217      * (there are more bytes sent than specified).<br />
218      * Unfortunately, in some cases, this is not possible after the bad response,
219      * but only before the next one. <br />
220      * So, HttpClient must be able to skip those surplus lines this way.
221      * </p>
222      * <p>
223      * Set this to 0 to disallow any garbage/empty lines before the status line.<br />
224      * To specify no limit, use {@link java.lang.Integer#MAX_VALUE} (default in lenient mode).
225      * </p>
226      *  
227      * This parameter expects a value of type {@link Integer}.
228      */
229     public static final String STATUS_LINE_GARBAGE_LIMIT = "http.protocol.status-line-garbage-limit";
230 
231     /**
232      * Sets the socket timeout (<tt>SO_TIMEOUT</tt>) in milliseconds to be used when executing the method. 
233      * A timeout value of zero is interpreted as an infinite timeout.
234      * <p>
235      * This parameter expects a value of type {@link Integer}.
236      * </p>
237      * @see java.net.SocketOptions#SO_TIMEOUT
238      */
239     public static final String SO_TIMEOUT = "http.socket.timeout"; 
240 
241     /**
242      * The key used to look up the date patterns used for parsing. The String patterns are stored
243      * in a {@link java.util.Collection} and must be compatible with 
244      * {@link java.text.SimpleDateFormat}.
245      * <p>
246      * This parameter expects a value of type {@link java.util.Collection}.
247      * </p>
248      */
249     public static final String DATE_PATTERNS = "http.dateparser.patterns";
250 
251     /**
252      * Sets the method retry handler parameter.
253      * <p>
254      * This parameter expects a value of type {@link org.apache.commons.httpclient.HttpMethodRetryHandler}.
255      * </p>
256      */ 
257     public static final String RETRY_HANDLER = "http.method.retry-handler";
258     
259     /**
260      * Sets the maximum buffered response size (in bytes) that triggers no warning. Buffered
261      * responses exceeding this size will trigger a warning in the log.
262      * <p>
263      * This parameter expects a value if type {@link Integer}.
264      * </p>
265      */
266     public static final String BUFFER_WARN_TRIGGER_LIMIT = "http.method.response.buffer.warnlimit";
267     
268     /**
269      * Defines the virtual host name.
270      * <p>
271      * This parameter expects a value of type {@link java.lang.String}. 
272      * </p>
273      */
274     public static final String VIRTUAL_HOST = "http.virtual-host"; 
275 
276     /**
277      * Sets the value to use as the multipart boundary.
278      * <p>
279      * This parameter expects a value if type {@link String}.
280      * </p>
281      * @see org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity
282      */
283     public static final String MULTIPART_BOUNDARY = "http.method.multipart.boundary";
284     
285     /**
286      * Creates a new collection of parameters with the collection returned
287      * by {@link #getDefaultParams()} as a parent. The collection will defer
288      * to its parent for a default value if a particular parameter is not 
289      * explicitly set in the collection itself.
290      * 
291      * @see #getDefaultParams()
292      */
293     public HttpMethodParams() {
294         super(getDefaultParams());
295     }
296 
297     /**
298      * Creates a new collection of parameters with the given parent. 
299      * The collection will defer to its parent for a default value 
300      * if a particular parameter is not explicitly set in the collection
301      * itself.
302      * 
303      * @param defaults the parent collection to defer to, if a parameter
304      * is not explictly set in the collection itself.
305      *
306      * @see #getDefaultParams()
307      */
308     public HttpMethodParams(HttpParams defaults) {
309         super(defaults);
310     }
311 
312     /**
313      * Returns the charset to be used for writing HTTP headers.
314      * @return The charset
315      */
316     public String getHttpElementCharset() {
317         String charset = (String) getParameter(HTTP_ELEMENT_CHARSET);
318         if (charset == null) {
319             LOG.warn("HTTP element charset not configured, using US-ASCII");
320             charset = "US-ASCII";
321         }
322         return charset;
323     }
324     
325     /**
326      * Sets the charset to be used for writing HTTP headers.
327      * @param charset The charset
328      */
329     public void setHttpElementCharset(String charset) {
330         setParameter(HTTP_ELEMENT_CHARSET, charset);
331     }
332 
333     /**
334      * Returns the default charset to be used for writing content body, 
335      * when no charset explicitly specified.
336      * @return The charset
337      */
338     public String getContentCharset() {
339         String charset = (String) getParameter(HTTP_CONTENT_CHARSET);
340         if (charset == null) {
341             LOG.warn("Default content charset not configured, using ISO-8859-1");
342             charset = "ISO-8859-1";
343         }
344         return charset;
345     }
346     
347     /**
348      * Sets the charset to be used for parsing URIs.
349      * @param charset The charset
350      */
351     public void setUriCharset(String charset) {
352         setParameter(HTTP_URI_CHARSET, charset);
353     }
354 
355     /**
356      * Returns the charset to be used for parsing URIs.
357      * @return The charset
358      */
359     public String getUriCharset() {
360         String charset = (String) getParameter(HTTP_URI_CHARSET);
361         if (charset == null) {
362             charset = "UTF-8";
363         }
364         return charset;
365     }
366     
367     /**
368      * Sets the default charset to be used for writing content body,
369      * when no charset explicitly specified.
370      * @param charset The charset
371      */
372     public void setContentCharset(String charset) {
373         setParameter(HTTP_CONTENT_CHARSET, charset);
374     }
375 
376     /**
377      * Returns the charset to be used for {@link org.apache.commons.httpclient.Credentials}. If
378      * not configured the {@link #HTTP_ELEMENT_CHARSET HTTP element charset} is used.
379      * @return The charset
380      */
381     public String getCredentialCharset() {
382         String charset = (String) getParameter(CREDENTIAL_CHARSET);
383         if (charset == null) {
384             LOG.debug("Credential charset not configured, using HTTP element charset");
385             charset = getHttpElementCharset();
386         }
387         return charset;
388     }
389     
390     /**
391      * Sets the charset to be used for writing HTTP headers.
392      * @param charset The charset
393      */
394     public void setCredentialCharset(String charset) {
395         setParameter(CREDENTIAL_CHARSET, charset);
396     }
397     
398     /**
399      * Returns {@link HttpVersion HTTP protocol version} to be used by the 
400      * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} that 
401      * this collection of parameters applies to. 
402      *
403      * @return {@link HttpVersion HTTP protocol version}
404      */
405     public HttpVersion getVersion() { 
406         Object param = getParameter(PROTOCOL_VERSION);
407         if (param == null) {
408             return HttpVersion.HTTP_1_1;
409         }
410         return (HttpVersion)param;
411     }
412     
413     /**
414      * Assigns the {@link HttpVersion HTTP protocol version} to be used by the 
415      * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} that 
416      * this collection of parameters applies to. 
417      *
418      * @param version the {@link HttpVersion HTTP protocol version}
419      */
420     public void setVersion(HttpVersion version) {
421         setParameter(PROTOCOL_VERSION, version);
422     }
423 
424 
425     /**
426      * Returns {@link CookiePolicy cookie policy} to be used by the 
427      * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} 
428      * this collection of parameters applies to. 
429      *
430      * @return {@link CookiePolicy cookie policy}
431      */
432     public String getCookiePolicy() { 
433         Object param = getParameter(COOKIE_POLICY);
434         if (param == null) {
435             return CookiePolicy.DEFAULT;
436         }
437         return (String)param;
438     }
439     
440     /**
441      * Assigns the {@link CookiePolicy cookie policy} to be used by the 
442      * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} 
443      * this collection of parameters applies to. 
444      *
445      * @param policy the {@link CookiePolicy cookie policy}
446      */
447     public void setCookiePolicy(String policy) {
448         setParameter(COOKIE_POLICY, policy);
449     }
450 
451     /**
452      * Returns the default socket timeout (<tt>SO_TIMEOUT</tt>) in milliseconds which is the 
453      * timeout for waiting for data. A timeout value of zero is interpreted as an infinite 
454      * timeout.  
455      *
456      * @return timeout in milliseconds
457      */
458     public int getSoTimeout() {
459         return getIntParameter(SO_TIMEOUT, 0);
460     }
461 
462     /**
463      * Sets the default socket timeout (<tt>SO_TIMEOUT</tt>) in milliseconds which is the 
464      * timeout for waiting for data. A timeout value of zero is interpreted as an infinite 
465      * timeout.  
466      *
467      * @param timeout Timeout in milliseconds
468      */
469     public void setSoTimeout(int timeout) {
470         setIntParameter(SO_TIMEOUT, timeout);
471     }
472 
473     /**
474      * Sets the virtual host name.
475      * 
476      * @param hostname The host name
477      */
478     public void setVirtualHost(final String hostname) {
479         setParameter(VIRTUAL_HOST, hostname);
480     }
481 
482     /**
483      * Returns the virtual host name.
484      * 
485      * @return The virtual host name
486      */
487     public String getVirtualHost() {
488         return (String) getParameter(VIRTUAL_HOST);
489     }
490     
491     private static final String[] PROTOCOL_STRICTNESS_PARAMETERS = {
492         UNAMBIGUOUS_STATUS_LINE,
493         SINGLE_COOKIE_HEADER,
494         STRICT_TRANSFER_ENCODING,
495         REJECT_HEAD_BODY,
496         WARN_EXTRA_INPUT
497     };
498     
499     /**
500      * Makes the {@link org.apache.commons.httpclient.HttpMethod HTTP methods} 
501      * strictly follow the HTTP protocol specification (RFC 2616 and other relevant RFCs).
502      * It must be noted that popular HTTP agents have different degree of HTTP protocol 
503      * compliance and some HTTP serves are programmed to expect the behaviour that does not 
504      * strictly adhere to the HTTP specification.  
505      */
506     public void makeStrict() {
507         setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.TRUE);
508         setIntParameter(STATUS_LINE_GARBAGE_LIMIT, 0);
509     }
510 
511     /**
512      * Makes the {@link org.apache.commons.httpclient.HttpMethod HTTP methods}
513      * attempt to mimic the exact behaviour of commonly used HTTP agents, 
514      * which many HTTP servers expect, even though such behaviour may violate   
515      * the HTTP protocol specification (RFC 2616 and other relevant RFCs).
516      */
517     public void makeLenient() {
518         setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.FALSE);
519         setIntParameter(STATUS_LINE_GARBAGE_LIMIT, Integer.MAX_VALUE);
520     }
521 
522 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/HttpParams.html100644 0 0 50513 10661532627 26360 0ustar 0 0 HttpParams xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpParams.java,v 1.6 2004/05/13 04:01:22 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.params;
32  
33  /**
34   * This interface represents a collection of HTTP protocol parameters. Protocol parameters
35   * may be linked together to form a hierarchy. If a particular parameter value has not been
36   * explicitly defined in the collection itself, its value will be drawn from the parent 
37   * collection of parameters.
38   *   
39   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
40   * 
41   * @version $Revision: 480424 $
42   *
43   * @since 3.0
44   */
45  public interface HttpParams {
46  
47      /** 
48       * Returns the parent collection that this collection will defer to
49       * for a default value if a particular parameter is not explicitly 
50       * set in the collection itself
51       * 
52       * @return the parent collection to defer to, if a particular parameter
53       * is not explictly set in the collection itself.
54       * 
55       * @see #setDefaults(HttpParams)
56       */
57      public HttpParams getDefaults();
58  
59      /** 
60       * Assigns the parent collection that this collection will defer to
61       * for a default value if a particular parameter is not explicitly 
62       * set in the collection itself
63       * 
64       * @param params the parent collection to defer to, if a particular 
65       * parameter is not explictly set in the collection itself.
66       * 
67       * @see #getDefaults()
68       */
69      public void setDefaults(final HttpParams params);
70      
71      /** 
72       * Returns a parameter value with the given name. If the parameter is
73       * not explicitly defined in this collection, its value will be drawn 
74       * from a higer level collection at which this parameter is defined.
75       * If the parameter is not explicitly set anywhere up the hierarchy,
76       * <tt>null</tt> value is returned.  
77       * 
78       * @param name the parent name.
79       * 
80       * @return an object that represents the value of the parameter.
81       * 
82       * @see #setParameter(String, Object)
83       */
84      public Object getParameter(final String name);
85  
86      /**
87       * Assigns the value to the parameter with the given name
88       * 
89       * @param name parameter name
90       * @param value parameter value
91       */ 
92      public void setParameter(final String name, final Object value);
93      
94      /** 
95       * Returns a {@link Long} parameter value with the given name. 
96       * If the parameter is not explicitly defined in this collection, its 
97       * value will be drawn from a higer level collection at which this parameter 
98       * is defined. If the parameter is not explicitly set anywhere up the hierarchy,
99       * the default value is returned.  
100      * 
101      * @param name the parent name.
102      * @param defaultValue the default value.
103      * 
104      * @return a {@link Long} that represents the value of the parameter.
105      * 
106      * @see #setLongParameter(String, long)
107      */
108     public long getLongParameter(final String name, long defaultValue); 
109     
110     /**
111      * Assigns a {@link Long} to the parameter with the given name
112      * 
113      * @param name parameter name
114      * @param value parameter value
115      */ 
116     public void setLongParameter(final String name, long value);
117 
118     /** 
119      * Returns an {@link Integer} parameter value with the given name. 
120      * If the parameter is not explicitly defined in this collection, its 
121      * value will be drawn from a higer level collection at which this parameter 
122      * is defined. If the parameter is not explicitly set anywhere up the hierarchy,
123      * the default value is returned.  
124      * 
125      * @param name the parent name.
126      * @param defaultValue the default value.
127      * 
128      * @return a {@link Integer} that represents the value of the parameter.
129      * 
130      * @see #setIntParameter(String, int)
131      */
132     public int getIntParameter(final String name, int defaultValue); 
133     
134     /**
135      * Assigns an {@link Integer} to the parameter with the given name
136      * 
137      * @param name parameter name
138      * @param value parameter value
139      */ 
140     public void setIntParameter(final String name, int value);
141 
142     /** 
143      * Returns a {@link Double} parameter value with the given name. 
144      * If the parameter is not explicitly defined in this collection, its 
145      * value will be drawn from a higer level collection at which this parameter 
146      * is defined. If the parameter is not explicitly set anywhere up the hierarchy,
147      * the default value is returned.  
148      * 
149      * @param name the parent name.
150      * @param defaultValue the default value.
151      * 
152      * @return a {@link Double} that represents the value of the parameter.
153      * 
154      * @see #setDoubleParameter(String, double)
155      */
156     public double getDoubleParameter(final String name, double defaultValue); 
157     
158     /**
159      * Assigns a {@link Double} to the parameter with the given name
160      * 
161      * @param name parameter name
162      * @param value parameter value
163      */ 
164     public void setDoubleParameter(final String name, double value);
165 
166     /** 
167      * Returns a {@link Boolean} parameter value with the given name. 
168      * If the parameter is not explicitly defined in this collection, its 
169      * value will be drawn from a higer level collection at which this parameter 
170      * is defined. If the parameter is not explicitly set anywhere up the hierarchy,
171      * the default value is returned.  
172      * 
173      * @param name the parent name.
174      * @param defaultValue the default value.
175      * 
176      * @return a {@link Boolean} that represents the value of the parameter.
177      * 
178      * @see #setBooleanParameter(String, boolean)
179      */
180     public boolean getBooleanParameter(final String name, boolean defaultValue); 
181     
182     /**
183      * Assigns a {@link Boolean} to the parameter with the given name
184      * 
185      * @param name parameter name
186      * @param value parameter value
187      */ 
188     public void setBooleanParameter(final String name, boolean value);
189 
190     /**
191      * Returns <tt>true</tt> if the parameter is set at any level, <tt>false</tt> otherwise.
192      * 
193      * @param name parameter name
194      * 
195      * @return <tt>true</tt> if the parameter is set at any level, <tt>false</tt>
196      * otherwise.
197      */
198     public boolean isParameterSet(final String name);
199         
200     /**
201      * Returns <tt>true</tt> if the parameter is set locally, <tt>false</tt> otherwise.
202      * 
203      * @param name parameter name
204      * 
205      * @return <tt>true</tt> if the parameter is set locally, <tt>false</tt>
206      * otherwise.
207      */
208     public boolean isParameterSetLocally(final String name);
209         
210     /**
211      * Returns <tt>true</tt> if the parameter is set and is <tt>true</tt>, <tt>false</tt>
212      * otherwise.
213      * 
214      * @param name parameter name
215      * 
216      * @return <tt>true</tt> if the parameter is set and is <tt>true</tt>, <tt>false</tt>
217      * otherwise.
218      */
219     public boolean isParameterTrue(final String name);
220         
221     /**
222      * Returns <tt>true</tt> if the parameter is either not set or is <tt>false</tt>, 
223      * <tt>false</tt> otherwise.
224      * 
225      * @param name parameter name
226      * 
227      * @return <tt>true</tt> if the parameter is either not set or is <tt>false</tt>, 
228      * <tt>false</tt> otherwise.
229      */
230     public boolean isParameterFalse(final String name);
231 
232 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/HttpParamsFactory.html100644 0 0 12726 10661532627 27714 0ustar 0 0 HttpParamsFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpParamsFactory.java,v 1.5 2004/05/13 04:01:22 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30   
31  package org.apache.commons.httpclient.params;
32  
33  /**
34   * A factory for getting the default set of parameters to use when creating an instance of 
35   * <code>HttpParams</code>.
36   * 
37   * @see org.apache.commons.httpclient.params.DefaultHttpParams#setHttpParamsFactory(HttpParamsFactory)
38   * 
39   * @since 3.0
40   */
41  public interface HttpParamsFactory {
42  
43      /**
44       * Gets the default parameters.  This method may be called more than once and is not required
45       * to always return the same value.
46       * 
47       * @return an instance of HttpParams
48       */
49      HttpParams getDefaultParams();
50  
51  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/package-frame.html100644 0 0 3415 10661532632 26733 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.params

org.apache.commons.httpclient.params

Classes

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/params/package-summary.html100644 0 0 6547 10661532632 27347 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.params

Package org.apache.commons.httpclient.params

Class Summary
DefaultHttpParams
DefaultHttpParamsFactory
HostParams
HttpClientParams
HttpConnectionManagerParams
HttpConnectionParams
HttpMethodParams
HttpParams
HttpParamsFactory

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. ././@LongLink100644 0 0 153 10661532634 10260 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactory.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactor100644 0 0 36110 10661532627 31470 0ustar 0 0 ControllerThreadSocketFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactory.java,v 1.2 2004/04/18 23:51:38 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.protocol;
32  
33  import java.io.IOException;
34  import java.net.InetAddress;
35  import java.net.Socket;
36  import java.net.UnknownHostException;
37  
38  import org.apache.commons.httpclient.ConnectTimeoutException;
39  import org.apache.commons.httpclient.util.TimeoutController;
40  
41  /**
42   * This helper class is intedned to help work around the limitation of older Java versions
43   * (older than 1.4) that prevents from specifying a connection timeout when creating a
44   * socket. This factory executes a controller thread overssing the process of socket 
45   * initialisation. If the socket constructor cannot be created within the specified time
46   * limit, the controller terminates and throws an {@link ConnectTimeoutException} 
47   * 
48   * @author Ortwin Glueck
49   * @author Oleg Kalnichevski
50   * 
51   * @since 3.0
52   */
53  public final class ControllerThreadSocketFactory {
54  
55      private ControllerThreadSocketFactory() {
56          super();
57      }
58  
59      /**
60       * This method spawns a controller thread overseeing the process of socket 
61       * initialisation. If the socket constructor cannot be created within the specified time
62       * limit, the controller terminates and throws an {@link ConnectTimeoutException}
63       * 
64       * @param host the host name/IP
65       * @param port the port on the host
66       * @param localAddress the local host name/IP to bind the socket to
67       * @param localPort the port on the local machine
68       * @param timeout the timeout value to be used in milliseconds. If the socket cannot be
69       *        completed within the given time limit, it will be abandoned
70       * 
71       * @return a connected Socket
72       * 
73       * @throws IOException if an I/O error occurs while creating the socket
74       * @throws UnknownHostException if the IP address of the host cannot be
75       * determined
76       * @throws ConnectTimeoutException if socket cannot be connected within the
77       *  given time limit
78       * 
79       */
80      public static Socket createSocket(
81          final ProtocolSocketFactory socketfactory, 
82          final String host,
83          final int port,
84          final InetAddress localAddress,
85          final int localPort,
86          int timeout)
87       throws IOException, UnknownHostException, ConnectTimeoutException
88      {
89              SocketTask task = new SocketTask() {
90                  public void doit() throws IOException {
91                      setSocket(socketfactory.createSocket(host, port, localAddress, localPort));
92                  }                 
93              };
94              try {
95                  TimeoutController.execute(task, timeout);
96              } catch (TimeoutController.TimeoutException e) {
97                  throw new ConnectTimeoutException(
98                      "The host did not accept the connection within timeout of " 
99                      + timeout + " ms");
100             }
101             Socket socket = task.getSocket();
102             if (task.exception != null) {
103                 throw task.exception;
104             }
105             return socket;
106     }
107 
108     public static Socket createSocket(final SocketTask task, int timeout)
109      throws IOException, UnknownHostException, ConnectTimeoutException
110     {
111             try {
112                 TimeoutController.execute(task, timeout);
113             } catch (TimeoutController.TimeoutException e) {
114                 throw new ConnectTimeoutException(
115                     "The host did not accept the connection within timeout of " 
116                     + timeout + " ms");
117             }
118             Socket socket = task.getSocket();
119             if (task.exception != null) {
120                 throw task.exception;
121             }
122             return socket;
123     }
124 
125     /**
126     * Helper class for wrapping socket based tasks.
127     */
128     public static abstract class SocketTask implements Runnable {
129         /** The socket */
130         private Socket socket;
131         /** The exception */
132         private IOException exception;
133 
134         /**
135          * Set the socket.
136          * @param newSocket The new socket.
137          */
138         protected void setSocket(final Socket newSocket) {
139             socket = newSocket;
140         }
141 
142         /**
143          * Return the socket.
144          * @return Socket The socket.
145          */
146         protected Socket getSocket() {
147             return socket;
148         }
149         /**
150          * Perform the logic.
151          * @throws IOException If an IO problem occurs
152          */
153         public abstract void doit() throws IOException;
154 
155         /** Execute the logic in this object and keep track of any exceptions. */
156         public void run() {
157             try {
158                 doit();
159             } catch (IOException e) {
160                 exception = e;
161             }
162         }
163     }
164 }

././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFactory100644 0 0 35040 10661532627 31515 0ustar 0 0 DefaultProtocolSocketFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFactory.java,v 1.10 2004/05/13 04:01:22 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.protocol;
32  
33  import java.io.IOException;
34  import java.net.InetAddress;
35  import java.net.Socket;
36  import java.net.UnknownHostException;
37  
38  import org.apache.commons.httpclient.ConnectTimeoutException;
39  import org.apache.commons.httpclient.params.HttpConnectionParams;
40  
41  /**
42   * The default class for creating protocol sockets.  This class just uses the
43   * {@link java.net.Socket socket} constructors.
44   * 
45   * @author Michael Becke
46   * 
47   * @since 2.0
48   */
49  public class DefaultProtocolSocketFactory implements ProtocolSocketFactory {
50  
51      /**
52       * The factory singleton.
53       */
54      private static final DefaultProtocolSocketFactory factory = new DefaultProtocolSocketFactory();
55      
56      /**
57       * Gets an singleton instance of the DefaultProtocolSocketFactory.
58       * @return a DefaultProtocolSocketFactory
59       */
60      static DefaultProtocolSocketFactory getSocketFactory() {
61          return factory;
62      }
63      
64      /**
65       * Constructor for DefaultProtocolSocketFactory.
66       */
67      public DefaultProtocolSocketFactory() {
68          super();
69      }
70  
71      /**
72       * @see #createSocket(java.lang.String,int,java.net.InetAddress,int)
73       */
74      public Socket createSocket(
75          String host,
76          int port,
77          InetAddress localAddress,
78          int localPort
79      ) throws IOException, UnknownHostException {
80          return new Socket(host, port, localAddress, localPort);
81      }
82      
83      /**
84       * Attempts to get a new socket connection to the given host within the given time limit.
85       * <p>
86       * This method employs several techniques to circumvent the limitations of older JREs that 
87       * do not support connect timeout. When running in JRE 1.4 or above reflection is used to 
88       * call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older 
89       * JREs a controller thread is executed. The controller thread attempts to create a new socket
90       * within the given limit of time. If socket constructor does not return until the timeout 
91       * expires, the controller terminates and throws an {@link ConnectTimeoutException}
92       * </p>
93       *  
94       * @param host the host name/IP
95       * @param port the port on the host
96       * @param localAddress the local host name/IP to bind the socket to
97       * @param localPort the port on the local machine
98       * @param params {@link HttpConnectionParams Http connection parameters}
99       * 
100      * @return Socket a new socket
101      * 
102      * @throws IOException if an I/O error occurs while creating the socket
103      * @throws UnknownHostException if the IP address of the host cannot be
104      * determined
105      * @throws ConnectTimeoutException if socket cannot be connected within the
106      *  given time limit
107      * 
108      * @since 3.0
109      */
110     public Socket createSocket(
111         final String host,
112         final int port,
113         final InetAddress localAddress,
114         final int localPort,
115         final HttpConnectionParams params
116     ) throws IOException, UnknownHostException, ConnectTimeoutException {
117         if (params == null) {
118             throw new IllegalArgumentException("Parameters may not be null");
119         }
120         int timeout = params.getConnectionTimeout();
121         if (timeout == 0) {
122             return createSocket(host, port, localAddress, localPort);
123         } else {
124             // To be eventually deprecated when migrated to Java 1.4 or above
125             Socket socket = ReflectionSocketFactory.createSocket(
126                 "javax.net.SocketFactory", host, port, localAddress, localPort, timeout);
127             if (socket == null) {
128                 socket = ControllerThreadSocketFactory.createSocket(
129                     this, host, port, localAddress, localPort, timeout);
130             }
131             return socket;
132         }
133     }
134 
135     /**
136      * @see ProtocolSocketFactory#createSocket(java.lang.String,int)
137      */
138     public Socket createSocket(String host, int port)
139         throws IOException, UnknownHostException {
140         return new Socket(host, port);
141     }
142 
143     /**
144      * All instances of DefaultProtocolSocketFactory are the same.
145      */
146     public boolean equals(Object obj) {
147         return ((obj != null) && obj.getClass().equals(getClass()));
148     }
149 
150     /**
151      * All instances of DefaultProtocolSocketFactory have the same hash code.
152      */
153     public int hashCode() {
154         return getClass().hashCode();
155     }
156 
157 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/Protocol.html100644 0 0 61776 10661532627 26471 0ustar 0 0 Protocol xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/Protocol.java,v 1.10 2004/04/18 23:51:38 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient.protocol;
31  
32  import java.util.Collections;
33  import java.util.HashMap;
34  import java.util.Map;
35  
36  import org.apache.commons.httpclient.util.LangUtils;
37  
38  /**
39   * A class to encapsulate the specifics of a protocol.  This class class also
40   * provides the ability to customize the set and characteristics of the
41   * protocols used.
42   * 
43   * <p>One use case for modifying the default set of protocols would be to set a
44   * custom SSL socket factory.  This would look something like the following:
45   * <pre> 
46   * Protocol myHTTPS = new Protocol( "https", new MySSLSocketFactory(), 443 );
47   * 
48   * Protocol.registerProtocol( "https", myHTTPS );
49   * </pre>
50   *
51   * @author Michael Becke 
52   * @author Jeff Dever
53   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
54   *  
55   * @since 2.0 
56   */
57  public class Protocol {
58  
59      /** The available protocols */
60      private static final Map PROTOCOLS = Collections.synchronizedMap(new HashMap());
61  
62      /**
63       * Registers a new protocol with the given identifier.  If a protocol with
64       * the given ID already exists it will be overridden.  This ID is the same
65       * one used to retrieve the protocol from getProtocol(String).
66       * 
67       * @param id the identifier for this protocol
68       * @param protocol the protocol to register
69       * 
70       * @see #getProtocol(String)
71       */
72      public static void registerProtocol(String id, Protocol protocol) {
73  
74          if (id == null) {
75              throw new IllegalArgumentException("id is null");
76          }
77          if (protocol == null) {
78              throw new IllegalArgumentException("protocol is null");
79          }
80  
81          PROTOCOLS.put(id, protocol);
82      }
83  
84      /**
85       * Unregisters the protocol with the given ID.
86       * 
87       * @param id the ID of the protocol to remove
88       */
89      public static void unregisterProtocol(String id) {
90  
91          if (id == null) {
92              throw new IllegalArgumentException("id is null");
93          }
94  
95          PROTOCOLS.remove(id);
96      }
97  
98      /**
99       * Gets the protocol with the given ID.
100      * 
101      * @param id the protocol ID
102      * 
103      * @return Protocol a protocol
104      * 
105      * @throws IllegalStateException if a protocol with the ID cannot be found
106      */
107     public static Protocol getProtocol(String id) 
108         throws IllegalStateException {
109 
110         if (id == null) {
111             throw new IllegalArgumentException("id is null");
112         }
113 
114         Protocol protocol = (Protocol) PROTOCOLS.get(id);
115 
116         if (protocol == null) {
117             protocol = lazyRegisterProtocol(id);
118         }
119 
120         return protocol;
121     } 
122 
123     /**
124      * Lazily registers the protocol with the given id.
125      * 
126      * @param id the protocol ID
127      * 
128      * @return the lazily registered protocol
129      * 
130      * @throws IllegalStateException if the protocol with id is not recognized
131      */
132     private static Protocol lazyRegisterProtocol(String id) 
133         throws IllegalStateException {
134 
135         if ("http".equals(id)) {
136             final Protocol http 
137                 = new Protocol("http", DefaultProtocolSocketFactory.getSocketFactory(), 80);
138             Protocol.registerProtocol("http", http);
139             return http;
140         }
141 
142         if ("https".equals(id)) {
143             final Protocol https 
144                 = new Protocol("https", SSLProtocolSocketFactory.getSocketFactory(), 443);
145             Protocol.registerProtocol("https", https);
146             return https;
147         }
148 
149         throw new IllegalStateException("unsupported protocol: '" + id + "'");
150     }
151     
152 
153     /** the scheme of this protocol (e.g. http, https) */
154     private String scheme;
155     
156     /** The socket factory for this protocol */
157     private ProtocolSocketFactory socketFactory;
158     
159     /** The default port for this protocol */
160     private int defaultPort;
161     
162     /** True if this protocol is secure */
163     private boolean secure;
164   
165     /**
166      * Constructs a new Protocol. Whether the created protocol is secure depends on
167      * the class of <code>factory</code>.
168      * 
169      * @param scheme the scheme (e.g. http, https)
170      * @param factory the factory for creating sockets for communication using
171      * this protocol
172      * @param defaultPort the port this protocol defaults to
173      */
174     public Protocol(String scheme, ProtocolSocketFactory factory, int defaultPort) {
175         
176         if (scheme == null) {
177             throw new IllegalArgumentException("scheme is null");
178         }
179         if (factory == null) {
180             throw new IllegalArgumentException("socketFactory is null");
181         }
182         if (defaultPort <= 0) {
183             throw new IllegalArgumentException("port is invalid: " + defaultPort);
184         }
185         
186         this.scheme = scheme;
187         this.socketFactory = factory;
188         this.defaultPort = defaultPort;
189         this.secure = (factory instanceof SecureProtocolSocketFactory);
190     }
191     
192     /**
193      * Constructs a new Protocol. Whether the created protocol is secure depends on
194      * the class of <code>factory</code>.
195      *
196      * @param scheme the scheme (e.g. http, https)
197      * @param factory the factory for creating sockets for communication using
198      * this protocol
199      * @param defaultPort the port this protocol defaults to
200      * @deprecated Use the constructor that uses ProtocolSocketFactory, this version of
201      * the constructor is only kept for backwards API compatibility.
202      */
203     public Protocol(String scheme, 
204         SecureProtocolSocketFactory factory, int defaultPort) {
205         this(scheme, (ProtocolSocketFactory) factory, defaultPort);   
206     }    
207     
208     /**
209      * Returns the defaultPort.
210      * @return int
211      */
212     public int getDefaultPort() {
213         return defaultPort;
214     }
215 
216     /**
217      * Returns the socketFactory.  If secure the factory is a
218      * SecureProtocolSocketFactory.
219      * @return SocketFactory
220      */
221     public ProtocolSocketFactory getSocketFactory() {
222         return socketFactory;
223     }
224 
225     /**
226      * Returns the scheme.
227      * @return The scheme
228      */
229     public String getScheme() {
230         return scheme;
231     }
232 
233     /**
234      * Returns true if this protocol is secure
235      * @return true if this protocol is secure
236      */
237     public boolean isSecure() {
238         return secure;
239     }
240     
241     /**
242      * Resolves the correct port for this protocol.  Returns the given port if
243      * valid or the default port otherwise.
244      * 
245      * @param port the port to be resolved
246      * 
247      * @return the given port or the defaultPort
248      */
249     public int resolvePort(int port) {
250         return port <= 0 ? getDefaultPort() : port;
251     }
252 
253     /**
254      * Return a string representation of this object.
255      * @return a string representation of this object.
256      */
257     public String toString() {
258         return scheme + ":" + defaultPort;
259     }
260     
261     /**
262      * Return true if the specified object equals this object.
263      * @param obj The object to compare against.
264      * @return true if the objects are equal.
265      */
266     public boolean equals(Object obj) {
267         
268         if (obj instanceof Protocol) {
269             
270             Protocol p = (Protocol) obj;
271             
272             return (
273                 defaultPort == p.getDefaultPort()
274                 && scheme.equalsIgnoreCase(p.getScheme())
275                 && secure == p.isSecure()
276                 && socketFactory.equals(p.getSocketFactory()));
277             
278         } else {
279             return false;
280         }
281         
282     }
283 
284     /**
285      * Return a hash code for this object
286      * @return The hash code.
287      */
288     public int hashCode() {
289         int hash = LangUtils.HASH_SEED;
290         hash = LangUtils.hashCode(hash, this.defaultPort);
291         hash = LangUtils.hashCode(hash, this.scheme.toLowerCase());
292         hash = LangUtils.hashCode(hash, this.secure);
293         hash = LangUtils.hashCode(hash, this.socketFactory);
294         return hash;
295     }
296 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/ProtocolSocketFactory.html100644 0 0 25707 10661532627 31164 0ustar 0 0 ProtocolSocketFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/ProtocolSocketFactory.java,v 1.10 2004/05/13 04:01:22 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.protocol;
32  
33  import java.io.IOException;
34  import java.net.InetAddress;
35  import java.net.Socket;
36  import java.net.UnknownHostException;
37  
38  import org.apache.commons.httpclient.ConnectTimeoutException;
39  import org.apache.commons.httpclient.params.HttpConnectionParams;
40  
41  /**
42   * A factory for creating Sockets.
43   * 
44   * <p>Both {@link java.lang.Object#equals(java.lang.Object) Object.equals()} and 
45   * {@link java.lang.Object#hashCode() Object.hashCode()} should be overridden appropriately.  
46   * Protocol socket factories are used to uniquely identify <code>Protocol</code>s and 
47   * <code>HostConfiguration</code>s, and <code>equals()</code> and <code>hashCode()</code> are 
48   * required for the correct operation of some connection managers.</p>
49   * 
50   * @see Protocol
51   * 
52   * @author Michael Becke
53   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
54   * 
55   * @since 2.0
56   */
57  public interface ProtocolSocketFactory {
58  
59      /**
60       * Gets a new socket connection to the given host.
61       * 
62       * @param host the host name/IP
63       * @param port the port on the host
64       * @param localAddress the local host name/IP to bind the socket to
65       * @param localPort the port on the local machine
66       * 
67       * @return Socket a new socket
68       * 
69       * @throws IOException if an I/O error occurs while creating the socket
70       * @throws UnknownHostException if the IP address of the host cannot be
71       * determined
72       */
73      Socket createSocket(
74          String host, 
75          int port, 
76          InetAddress localAddress, 
77          int localPort
78      ) throws IOException, UnknownHostException;
79  
80      /**
81       * Gets a new socket connection to the given host.
82       * 
83       * @param host the host name/IP
84       * @param port the port on the host
85       * @param localAddress the local host name/IP to bind the socket to
86       * @param localPort the port on the local machine
87       * @param params {@link HttpConnectionParams Http connection parameters}
88       * 
89       * @return Socket a new socket
90       * 
91       * @throws IOException if an I/O error occurs while creating the socket
92       * @throws UnknownHostException if the IP address of the host cannot be
93       * determined
94       * @throws ConnectTimeoutException if socket cannot be connected within the
95       *  given time limit
96       * 
97       * @since 3.0
98       */
99      Socket createSocket(
100         String host, 
101         int port, 
102         InetAddress localAddress, 
103         int localPort,
104         HttpConnectionParams params
105     ) throws IOException, UnknownHostException, ConnectTimeoutException;
106 
107     /**
108      * Gets a new socket connection to the given host.
109      *
110      * @param host the host name/IP
111      * @param port the port on the host
112      *
113      * @return Socket a new socket
114      *
115      * @throws IOException if an I/O error occurs while creating the socket
116      * @throws UnknownHostException if the IP address of the host cannot be
117      * determined
118      */
119     Socket createSocket(
120         String host, 
121         int port
122     ) throws IOException, UnknownHostException;
123 
124 }

././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/ReflectionSocketFactory.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/ReflectionSocketFactory.html100644 0 0 40776 10661532627 31460 0ustar 0 0 ReflectionSocketFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/ReflectionSocketFactory.java,v 1.4 2004/12/21 23:15:21 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.protocol;
32  
33  import java.io.IOException;
34  import java.lang.reflect.Constructor;
35  import java.lang.reflect.InvocationTargetException;
36  import java.lang.reflect.Method;
37  import java.net.InetAddress;
38  import java.net.Socket;
39  import java.net.UnknownHostException;
40  
41  import org.apache.commons.httpclient.ConnectTimeoutException;
42  
43  /**
44   * This helper class uses refelction in order to execute Socket methods
45   * available in Java 1.4 and above  
46   * 
47   * @author Oleg Kalnichevski
48   * 
49   * @since 3.0
50   */
51  public final class ReflectionSocketFactory {
52  
53      private static boolean REFLECTION_FAILED = false;
54      
55      private static Constructor INETSOCKETADDRESS_CONSTRUCTOR = null;
56      private static Method SOCKETCONNECT_METHOD = null;
57      private static Method SOCKETBIND_METHOD = null;
58      private static Class SOCKETTIMEOUTEXCEPTION_CLASS = null;
59  
60      private ReflectionSocketFactory() {
61          super();
62      }
63  
64      /**
65       * This method attempts to execute Socket method available since Java 1.4
66       * using reflection. If the methods are not available or could not be executed
67       * <tt>null</tt> is returned
68       *   
69       * @param socketfactoryName name of the socket factory class
70       * @param host the host name/IP
71       * @param port the port on the host
72       * @param localAddress the local host name/IP to bind the socket to
73       * @param localPort the port on the local machine
74       * @param timeout the timeout value to be used in milliseconds. If the socket cannot be
75       *        completed within the given time limit, it will be abandoned
76       * 
77       * @return a connected Socket
78       * 
79       * @throws IOException if an I/O error occurs while creating the socket
80       * @throws UnknownHostException if the IP address of the host cannot be
81       * determined
82       * @throws ConnectTimeoutException if socket cannot be connected within the
83       *  given time limit
84       * 
85       */
86      public static Socket createSocket(
87          final String socketfactoryName, 
88          final String host,
89          final int port,
90          final InetAddress localAddress,
91          final int localPort,
92          int timeout)
93       throws IOException, UnknownHostException, ConnectTimeoutException
94      {
95          if (REFLECTION_FAILED) {
96              //This is known to have failed before. Do not try it again
97              return null;
98          }
99          // This code uses reflection to essentially do the following:
100         //
101         //  SocketFactory socketFactory = Class.forName(socketfactoryName).getDefault();
102         //  Socket socket = socketFactory.createSocket();
103         //  SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
104         //  SocketAddress remoteaddr = new InetSocketAddress(host, port);
105         //  socket.bind(localaddr);
106         //  socket.connect(remoteaddr, timeout);
107         //  return socket;
108         try {
109             Class socketfactoryClass = Class.forName(socketfactoryName);
110             Method method = socketfactoryClass.getMethod("getDefault", 
111                 new Class[] {});
112             Object socketfactory = method.invoke(null, 
113                 new Object[] {});
114             method = socketfactoryClass.getMethod("createSocket", 
115                 new Class[] {});
116             Socket socket = (Socket) method.invoke(socketfactory, new Object[] {});
117             
118             if (INETSOCKETADDRESS_CONSTRUCTOR == null) {
119                 Class addressClass = Class.forName("java.net.InetSocketAddress");
120                 INETSOCKETADDRESS_CONSTRUCTOR = addressClass.getConstructor(
121                     new Class[] { InetAddress.class, Integer.TYPE });
122             }
123                 
124             Object remoteaddr = INETSOCKETADDRESS_CONSTRUCTOR.newInstance(
125                 new Object[] { InetAddress.getByName(host), new Integer(port)});
126 
127             Object localaddr = INETSOCKETADDRESS_CONSTRUCTOR.newInstance(
128                     new Object[] { localAddress, new Integer(localPort)});
129 
130             if (SOCKETCONNECT_METHOD == null) {
131                 SOCKETCONNECT_METHOD = Socket.class.getMethod("connect", 
132                     new Class[] {Class.forName("java.net.SocketAddress"), Integer.TYPE});
133             }
134 
135             if (SOCKETBIND_METHOD == null) {
136                 SOCKETBIND_METHOD = Socket.class.getMethod("bind", 
137                     new Class[] {Class.forName("java.net.SocketAddress")});
138             }
139             SOCKETBIND_METHOD.invoke(socket, new Object[] { localaddr});
140             SOCKETCONNECT_METHOD.invoke(socket, new Object[] { remoteaddr, new Integer(timeout)});
141             return socket;
142         }
143         catch (InvocationTargetException e) {
144             Throwable cause = e.getTargetException(); 
145             if (SOCKETTIMEOUTEXCEPTION_CLASS == null) {
146                 try {
147                     SOCKETTIMEOUTEXCEPTION_CLASS = Class.forName("java.net.SocketTimeoutException");
148                 } catch (ClassNotFoundException ex) {
149                     // At this point this should never happen. Really.
150                     REFLECTION_FAILED = true;
151                     return null;
152                 }
153             }
154             if (SOCKETTIMEOUTEXCEPTION_CLASS.isInstance(cause)) {
155                 throw new ConnectTimeoutException(
156                     "The host did not accept the connection within timeout of " 
157                     + timeout + " ms", cause);
158             }
159             if (cause instanceof IOException) {
160                 throw (IOException)cause;
161             }
162             return null;
163         }
164         catch (Exception e) {
165             REFLECTION_FAILED = true;
166             return null;
167         }
168     }
169 }

././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.htm100644 0 0 40053 10661532627 31361 0ustar 0 0 SSLProtocolSocketFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.java,v 1.10 2004/05/13 04:01:22 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.protocol;
32  
33  import java.io.IOException;
34  import java.net.InetAddress;
35  import java.net.Socket;
36  import java.net.UnknownHostException;
37  
38  import javax.net.ssl.SSLSocketFactory;
39  
40  import org.apache.commons.httpclient.ConnectTimeoutException;
41  import org.apache.commons.httpclient.params.HttpConnectionParams;
42  
43  /**
44   * A SecureProtocolSocketFactory that uses JSSE to create sockets.
45   * 
46   * @author Michael Becke
47   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
48   * 
49   * @since 2.0
50   */
51  public class SSLProtocolSocketFactory implements SecureProtocolSocketFactory {
52  
53      /**
54       * The factory singleton.
55       */
56      private static final SSLProtocolSocketFactory factory = new SSLProtocolSocketFactory();
57      
58      /**
59       * Gets an singleton instance of the SSLProtocolSocketFactory.
60       * @return a SSLProtocolSocketFactory
61       */
62      static SSLProtocolSocketFactory getSocketFactory() {
63          return factory;
64      }    
65      
66      /**
67       * Constructor for SSLProtocolSocketFactory.
68       */
69      public SSLProtocolSocketFactory() {
70          super();
71      }
72  
73      /**
74       * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
75       */
76      public Socket createSocket(
77          String host,
78          int port,
79          InetAddress clientHost,
80          int clientPort)
81          throws IOException, UnknownHostException {
82          return SSLSocketFactory.getDefault().createSocket(
83              host,
84              port,
85              clientHost,
86              clientPort
87          );
88      }
89  
90      /**
91       * Attempts to get a new socket connection to the given host within the given time limit.
92       * <p>
93       * This method employs several techniques to circumvent the limitations of older JREs that 
94       * do not support connect timeout. When running in JRE 1.4 or above reflection is used to 
95       * call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older 
96       * JREs a controller thread is executed. The controller thread attempts to create a new socket
97       * within the given limit of time. If socket constructor does not return until the timeout 
98       * expires, the controller terminates and throws an {@link ConnectTimeoutException}
99       * </p>
100      *  
101      * @param host the host name/IP
102      * @param port the port on the host
103      * @param localAddress the local host name/IP to bind the socket to
104      * @param localPort the port on the local machine
105      * @param params {@link HttpConnectionParams Http connection parameters}
106      * 
107      * @return Socket a new socket
108      * 
109      * @throws IOException if an I/O error occurs while creating the socket
110      * @throws UnknownHostException if the IP address of the host cannot be
111      * determined
112      * 
113      * @since 3.0
114      */
115     public Socket createSocket(
116         final String host,
117         final int port,
118         final InetAddress localAddress,
119         final int localPort,
120         final HttpConnectionParams params
121     ) throws IOException, UnknownHostException, ConnectTimeoutException {
122         if (params == null) {
123             throw new IllegalArgumentException("Parameters may not be null");
124         }
125         int timeout = params.getConnectionTimeout();
126         if (timeout == 0) {
127             return createSocket(host, port, localAddress, localPort);
128         } else {
129             // To be eventually deprecated when migrated to Java 1.4 or above
130             Socket socket = ReflectionSocketFactory.createSocket(
131                 "javax.net.ssl.SSLSocketFactory", host, port, localAddress, localPort, timeout);
132             if (socket == null) {
133                 socket = ControllerThreadSocketFactory.createSocket(
134                     this, host, port, localAddress, localPort, timeout);
135             }
136             return socket;
137         }
138     }
139 
140     /**
141      * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
142      */
143     public Socket createSocket(String host, int port)
144         throws IOException, UnknownHostException {
145         return SSLSocketFactory.getDefault().createSocket(
146             host,
147             port
148         );
149     }
150 
151     /**
152      * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
153      */
154     public Socket createSocket(
155         Socket socket,
156         String host,
157         int port,
158         boolean autoClose)
159         throws IOException, UnknownHostException {
160         return ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(
161             socket,
162             host,
163             port,
164             autoClose
165         );
166     }
167 
168     /**
169      * All instances of SSLProtocolSocketFactory are the same.
170      */
171     public boolean equals(Object obj) {
172         return ((obj != null) && obj.getClass().equals(getClass()));
173     }
174 
175     /**
176      * All instances of SSLProtocolSocketFactory have the same hash code.
177      */
178     public int hashCode() {
179         return getClass().hashCode();
180     }    
181     
182 }

././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.100644 0 0 16205 10661532627 31437 0ustar 0 0 SecureProtocolSocketFactory xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.java,v 1.6 2004/04/18 23:51:38 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.protocol;
32  
33  import java.io.IOException;
34  import java.net.Socket;
35  import java.net.UnknownHostException;
36  
37  /**
38   * A ProtocolSocketFactory that is secure.
39   * 
40   * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory
41   * 
42   * @author Michael Becke
43   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
44   * @since 2.0
45   */
46  public interface SecureProtocolSocketFactory extends ProtocolSocketFactory {
47  
48      /**
49       * Returns a socket connected to the given host that is layered over an
50       * existing socket.  Used primarily for creating secure sockets through
51       * proxies.
52       * 
53       * @param socket the existing socket 
54       * @param host the host name/IP
55       * @param port the port on the host
56       * @param autoClose a flag for closing the underling socket when the created
57       * socket is closed
58       * 
59       * @return Socket a new socket
60       * 
61       * @throws IOException if an I/O error occurs while creating the socket
62       * @throws UnknownHostException if the IP address of the host cannot be
63       * determined
64       */
65      Socket createSocket(
66          Socket socket, 
67          String host, 
68          int port, 
69          boolean autoClose
70      ) throws IOException, UnknownHostException;              
71  
72  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/package-frame.html100644 0 0 3123 10661532632 27305 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.protocol

org.apache.commons.httpclient.protocol

Classes

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/protocol/package-summary.html100644 0 0 6123 10661532632 27713 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.protocol

Package org.apache.commons.httpclient.protocol

Class Summary
ControllerThreadSocketFactory
DefaultProtocolSocketFactory
Protocol
ProtocolSocketFactory
ReflectionSocketFactory
SSLProtocolSocketFactory
SecureProtocolSocketFactory

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/DateParseException.html100644 0 0 13254 10661532627 27517 0ustar 0 0 DateParseException xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/DateParseException.java,v 1.5 2004/11/06 19:15:42 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.util;
32  
33  
34  /**
35   * An exception to indicate an error parsing a date string.
36   * 
37   * @see DateUtil
38   * 
39   * @author Michael Becke
40   */
41  public class DateParseException extends Exception {
42  
43      /**
44       * 
45       */
46      public DateParseException() {
47          super();
48      }
49  
50      /**
51       * @param message the exception message
52       */
53      public DateParseException(String message) {
54          super(message);
55      }
56  
57  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/DateParser.html100644 0 0 31732 10661532627 26023 0ustar 0 0 DateParser xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/DateParser.java,v 1.11 2004/11/06 19:15:42 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.util;
32  
33  import java.text.ParseException;
34  import java.text.SimpleDateFormat;
35  import java.util.Arrays;
36  import java.util.Collection;
37  import java.util.Date;
38  import java.util.Iterator;
39  import java.util.Locale;
40  import java.util.TimeZone;
41  
42  /**
43   * A utility class for parsing HTTP dates as used in cookies and other headers.  
44   * This class handles dates as defined by RFC 2616 section 3.3.1 as well as 
45   * some other common non-standard formats.
46   * 
47   * @author Christopher Brown
48   * @author Michael Becke
49   * 
50   * @deprecated Use {@link org.apache.commons.httpclient.util.DateUtil}
51   */
52  public class DateParser {
53  
54      /**
55       * Date format pattern used to parse HTTP date headers in RFC 1123 format.
56       */
57      public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
58  
59      /**
60       * Date format pattern used to parse HTTP date headers in RFC 1036 format.
61       */
62      public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
63  
64      /**
65       * Date format pattern used to parse HTTP date headers in ANSI C 
66       * <code>asctime()</code> format.
67       */
68      public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
69  
70      private static final Collection DEFAULT_PATTERNS = Arrays.asList(
71      		new String[] { PATTERN_ASCTIME, PATTERN_RFC1036, PATTERN_RFC1123 } );
72      /**
73       * Parses a date value.  The formats used for parsing the date value are retrieved from
74       * the default http params.
75       *
76       * @param dateValue the date value to parse
77       * 
78       * @return the parsed date
79       *
80       * @throws DateParseException if the value could not be parsed using any of the 
81       * supported date formats
82       */
83      public static Date parseDate(String dateValue) throws DateParseException {
84          return parseDate(dateValue, null);
85      }
86      
87      /**
88       * Parses the date value using the given date formats.
89       * 
90       * @param dateValue the date value to parse
91       * @param dateFormats the date formats to use
92       * 
93       * @return the parsed date
94       * 
95       * @throws DateParseException if none of the dataFormats could parse the dateValue
96       */
97      public static Date parseDate(
98          String dateValue, 
99          Collection dateFormats
100     ) throws DateParseException {
101         
102         if (dateValue == null) {
103             throw new IllegalArgumentException("dateValue is null");
104         }
105         if (dateFormats == null) {
106         	dateFormats = DEFAULT_PATTERNS;
107         }
108         // trim single quotes around date if present
109         // see issue #5279
110         if (dateValue.length() > 1 
111             && dateValue.startsWith("'") 
112             && dateValue.endsWith("'")
113         ) {
114             dateValue = dateValue.substring (1, dateValue.length() - 1);
115         }
116         
117         SimpleDateFormat dateParser = null;        
118         Iterator formatIter = dateFormats.iterator();
119         
120         while (formatIter.hasNext()) {
121             String format = (String) formatIter.next();            
122             if (dateParser == null) {
123                 dateParser = new SimpleDateFormat(format, Locale.US);
124                 dateParser.setTimeZone(TimeZone.getTimeZone("GMT"));
125             } else {
126                 dateParser.applyPattern(format);                    
127             }
128             try {
129                 return dateParser.parse(dateValue);
130             } catch (ParseException pe) {
131                 // ignore this exception, we will try the next format
132             }                
133         }
134         
135         // we were unable to parse the date
136         throw new DateParseException("Unable to parse the date " + dateValue);        
137     }
138 
139     /** This class should not be instantiated. */    
140     private DateParser() { }
141     
142 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/DateUtil.html100644 0 0 45153 10661532627 25506 0ustar 0 0 DateUtil xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/DateUtil.java,v 1.2 2004/12/24 20:36:13 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.util;
32  
33  import java.text.ParseException;
34  import java.text.SimpleDateFormat;
35  import java.util.Arrays;
36  import java.util.Calendar;
37  import java.util.Collection;
38  import java.util.Date;
39  import java.util.Iterator;
40  import java.util.Locale;
41  import java.util.TimeZone;
42  
43  /**
44   * A utility class for parsing and formatting HTTP dates as used in cookies and 
45   * other headers.  This class handles dates as defined by RFC 2616 section 
46   * 3.3.1 as well as some other common non-standard formats.
47   * 
48   * @author Christopher Brown
49   * @author Michael Becke
50   */
51  public class DateUtil {
52  
53      /**
54       * Date format pattern used to parse HTTP date headers in RFC 1123 format.
55       */
56      public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
57  
58      /**
59       * Date format pattern used to parse HTTP date headers in RFC 1036 format.
60       */
61      public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
62  
63      /**
64       * Date format pattern used to parse HTTP date headers in ANSI C 
65       * <code>asctime()</code> format.
66       */
67      public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
68  
69      private static final Collection DEFAULT_PATTERNS = Arrays.asList(
70      		new String[] { PATTERN_ASCTIME, PATTERN_RFC1036, PATTERN_RFC1123 } );
71      
72      private static final Date DEFAULT_TWO_DIGIT_YEAR_START;
73      
74      static {
75          Calendar calendar = Calendar.getInstance();
76          calendar.set(2000, Calendar.JANUARY, 1, 0, 0);
77          DEFAULT_TWO_DIGIT_YEAR_START = calendar.getTime(); 
78      }
79      
80      private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
81      
82      /**
83       * Parses a date value.  The formats used for parsing the date value are retrieved from
84       * the default http params.
85       *
86       * @param dateValue the date value to parse
87       * 
88       * @return the parsed date
89       *
90       * @throws DateParseException if the value could not be parsed using any of the 
91       * supported date formats
92       */
93      public static Date parseDate(String dateValue) throws DateParseException {
94          return parseDate(dateValue, null, null);
95      }
96      
97      /**
98       * Parses the date value using the given date formats.
99       * 
100      * @param dateValue the date value to parse
101      * @param dateFormats the date formats to use
102      * 
103      * @return the parsed date
104      * 
105      * @throws DateParseException if none of the dataFormats could parse the dateValue
106      */
107     public static Date parseDate(String dateValue, Collection dateFormats) 
108         throws DateParseException {
109         return parseDate(dateValue, dateFormats, null);
110     }
111     
112     /**
113      * Parses the date value using the given date formats.
114      * 
115      * @param dateValue the date value to parse
116      * @param dateFormats the date formats to use
117      * @param startDate During parsing, two digit years will be placed in the range 
118      * <code>startDate</code> to <code>startDate + 100 years</code>. This value may 
119      * be <code>null</code>. When <code>null</code> is given as a parameter, year 
120      * <code>2000</code> will be used. 
121      * 
122      * @return the parsed date
123      * 
124      * @throws DateParseException if none of the dataFormats could parse the dateValue
125      */
126     public static Date parseDate(
127         String dateValue, 
128         Collection dateFormats,
129         Date startDate 
130     ) throws DateParseException {
131         
132         if (dateValue == null) {
133             throw new IllegalArgumentException("dateValue is null");
134         }
135         if (dateFormats == null) {
136         	dateFormats = DEFAULT_PATTERNS;
137         }
138         if (startDate == null) {
139             startDate = DEFAULT_TWO_DIGIT_YEAR_START;
140         }
141         // trim single quotes around date if present
142         // see issue #5279
143         if (dateValue.length() > 1 
144             && dateValue.startsWith("'") 
145             && dateValue.endsWith("'")
146         ) {
147             dateValue = dateValue.substring (1, dateValue.length() - 1);
148         }
149         
150         SimpleDateFormat dateParser = null;        
151         Iterator formatIter = dateFormats.iterator();
152         
153         while (formatIter.hasNext()) {
154             String format = (String) formatIter.next();            
155             if (dateParser == null) {
156                 dateParser = new SimpleDateFormat(format, Locale.US);
157                 dateParser.setTimeZone(TimeZone.getTimeZone("GMT"));
158                 dateParser.set2DigitYearStart(startDate);
159             } else {
160                 dateParser.applyPattern(format);                    
161             }
162             try {
163                 return dateParser.parse(dateValue);
164             } catch (ParseException pe) {
165                 // ignore this exception, we will try the next format
166             }                
167         }
168         
169         // we were unable to parse the date
170         throw new DateParseException("Unable to parse the date " + dateValue);        
171     }
172 
173     /**
174      * Formats the given date according to the RFC 1123 pattern.
175      * 
176      * @param date The date to format.
177      * @return An RFC 1123 formatted date string.
178      * 
179      * @see #PATTERN_RFC1123
180      */
181     public static String formatDate(Date date) {
182         return formatDate(date, PATTERN_RFC1123);
183     }
184     
185     /**
186      * Formats the given date according to the specified pattern.  The pattern
187      * must conform to that used by the {@link SimpleDateFormat simple date
188      * format} class.
189      * 
190      * @param date The date to format.
191      * @param pattern The pattern to use for formatting the date.  
192      * @return A formatted date string.
193      * 
194      * @throws IllegalArgumentException If the given date pattern is invalid.
195      * 
196      * @see SimpleDateFormat
197      */
198     public static String formatDate(Date date, String pattern) {
199         if (date == null) throw new IllegalArgumentException("date is null");
200         if (pattern == null) throw new IllegalArgumentException("pattern is null");
201         
202         SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.US);
203         formatter.setTimeZone(GMT);
204         return formatter.format(date);
205     }
206     
207     /** This class should not be instantiated. */    
208     private DateUtil() { }
209     
210 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/EncodingUtil.html100644 0 0 61624 10661532627 26360 0ustar 0 0 EncodingUtil xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/EncodingUtil.java,v 1.8 2004/05/13 04:01:22 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient.util;
31  
32  import java.io.UnsupportedEncodingException;
33  
34  import org.apache.commons.codec.net.URLCodec;
35  import org.apache.commons.httpclient.HttpClientError;
36  import org.apache.commons.httpclient.NameValuePair;
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  
40  /**
41   * The home for utility methods that handle various encoding tasks.
42   * 
43   * @author Michael Becke
44   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
45   * 
46   * @since 2.0 final
47   */
48  public class EncodingUtil {
49  
50      /** Default content encoding chatset */
51      private static final String DEFAULT_CHARSET = "ISO-8859-1";
52  
53      /** Log object for this class. */
54      private static final Log LOG = LogFactory.getLog(EncodingUtil.class);
55  
56      /**
57       * Form-urlencoding routine.
58       *
59       * The default encoding for all forms is `application/x-www-form-urlencoded'. 
60       * A form data set is represented in this media type as follows:
61       *
62       * The form field names and values are escaped: space characters are replaced 
63       * by `+', and then reserved characters are escaped as per [URL]; that is, 
64       * non-alphanumeric characters are replaced by `%HH', a percent sign and two 
65       * hexadecimal digits representing the ASCII code of the character. Line breaks, 
66       * as in multi-line text field values, are represented as CR LF pairs, i.e. `%0D%0A'.
67       * 
68       * <p>
69       * if the given charset is not supported, ISO-8859-1 is used instead.
70       * </p>
71       * 
72       * @param pairs the values to be encoded
73       * @param charset the character set of pairs to be encoded
74       * 
75       * @return the urlencoded pairs
76       * 
77       * @since 2.0 final
78       */
79       public static String formUrlEncode(NameValuePair[] pairs, String charset) {
80          try {
81              return doFormUrlEncode(pairs, charset);
82          } catch (UnsupportedEncodingException e) {
83              LOG.error("Encoding not supported: " + charset);
84              try {
85                  return doFormUrlEncode(pairs, DEFAULT_CHARSET);
86              } catch (UnsupportedEncodingException fatal) {
87                  // Should never happen. ISO-8859-1 must be supported on all JVMs
88                  throw new HttpClientError("Encoding not supported: " + 
89                      DEFAULT_CHARSET);
90              }
91          }
92      }
93  
94      /**
95       * Form-urlencoding routine.
96       *
97       * The default encoding for all forms is `application/x-www-form-urlencoded'. 
98       * A form data set is represented in this media type as follows:
99       *
100      * The form field names and values are escaped: space characters are replaced 
101      * by `+', and then reserved characters are escaped as per [URL]; that is, 
102      * non-alphanumeric characters are replaced by `%HH', a percent sign and two 
103      * hexadecimal digits representing the ASCII code of the character. Line breaks, 
104      * as in multi-line text field values, are represented as CR LF pairs, i.e. `%0D%0A'.
105      * 
106      * @param pairs the values to be encoded
107      * @param charset the character set of pairs to be encoded
108      * 
109      * @return the urlencoded pairs
110      * @throws UnsupportedEncodingException if charset is not supported
111      * 
112      * @since 2.0 final
113      */
114      private static String doFormUrlEncode(NameValuePair[] pairs, String charset)
115         throws UnsupportedEncodingException 
116      {
117         StringBuffer buf = new StringBuffer();
118         for (int i = 0; i < pairs.length; i++) {
119             URLCodec codec = new URLCodec();
120             NameValuePair pair = pairs[i];
121             if (pair.getName() != null) {
122                 if (i > 0) {
123                     buf.append("&");
124                 }
125                 buf.append(codec.encode(pair.getName(), charset));
126                 buf.append("=");
127                 if (pair.getValue() != null) {
128                     buf.append(codec.encode(pair.getValue(), charset));
129                 }
130             }
131         }
132         return buf.toString();
133     }
134     
135     /**
136      * Converts the byte array of HTTP content characters to a string. If
137      * the specified charset is not supported, default system encoding
138      * is used.
139      *
140      * @param data the byte array to be encoded
141      * @param offset the index of the first byte to encode
142      * @param length the number of bytes to encode 
143      * @param charset the desired character encoding
144      * @return The result of the conversion.
145      * 
146      * @since 3.0
147      */
148     public static String getString(
149         final byte[] data, 
150         int offset, 
151         int length, 
152         String charset
153     ) {
154 
155         if (data == null) {
156             throw new IllegalArgumentException("Parameter may not be null");
157         }
158 
159         if (charset == null || charset.length() == 0) {
160             throw new IllegalArgumentException("charset may not be null or empty");
161         }
162 
163         try {
164             return new String(data, offset, length, charset);
165         } catch (UnsupportedEncodingException e) {
166 
167             if (LOG.isWarnEnabled()) {
168                 LOG.warn("Unsupported encoding: " + charset + ". System encoding used");
169             }
170             return new String(data, offset, length);
171         }
172     }
173 
174 
175     /**
176      * Converts the byte array of HTTP content characters to a string. If
177      * the specified charset is not supported, default system encoding
178      * is used.
179      *
180      * @param data the byte array to be encoded
181      * @param charset the desired character encoding
182      * @return The result of the conversion.
183      * 
184      * @since 3.0
185      */
186     public static String getString(final byte[] data, String charset) {
187         return getString(data, 0, data.length, charset);
188     }
189 
190     /**
191      * Converts the specified string to a byte array.  If the charset is not supported the
192      * default system charset is used.
193      *
194      * @param data the string to be encoded
195      * @param charset the desired character encoding
196      * @return The resulting byte array.
197      * 
198      * @since 3.0
199      */
200     public static byte[] getBytes(final String data, String charset) {
201 
202         if (data == null) {
203             throw new IllegalArgumentException("data may not be null");
204         }
205 
206         if (charset == null || charset.length() == 0) {
207             throw new IllegalArgumentException("charset may not be null or empty");
208         }
209 
210         try {
211             return data.getBytes(charset);
212         } catch (UnsupportedEncodingException e) {
213 
214             if (LOG.isWarnEnabled()) {
215                 LOG.warn("Unsupported encoding: " + charset + ". System encoding used.");
216             }
217             
218             return data.getBytes();
219         }
220     }    
221     
222     /**
223      * Converts the specified string to byte array of ASCII characters.
224      *
225      * @param data the string to be encoded
226      * @return The string as a byte array.
227      * 
228      * @since 3.0
229      */
230     public static byte[] getAsciiBytes(final String data) {
231 
232         if (data == null) {
233             throw new IllegalArgumentException("Parameter may not be null");
234         }
235 
236         try {
237             return data.getBytes("US-ASCII");
238         } catch (UnsupportedEncodingException e) {
239             throw new HttpClientError("HttpClient requires ASCII support");
240         }
241     }
242 
243     /**
244      * Converts the byte array of ASCII characters to a string. This method is
245      * to be used when decoding content of HTTP elements (such as response
246      * headers)
247      *
248      * @param data the byte array to be encoded
249      * @param offset the index of the first byte to encode
250      * @param length the number of bytes to encode 
251      * @return The string representation of the byte array
252      * 
253      * @since 3.0
254      */
255     public static String getAsciiString(final byte[] data, int offset, int length) {
256 
257         if (data == null) {
258             throw new IllegalArgumentException("Parameter may not be null");
259         }
260 
261         try {
262             return new String(data, offset, length, "US-ASCII");
263         } catch (UnsupportedEncodingException e) {
264             throw new HttpClientError("HttpClient requires ASCII support");
265         }
266     }
267 
268     /**
269      * Converts the byte array of ASCII characters to a string. This method is
270      * to be used when decoding content of HTTP elements (such as response
271      * headers)
272      *
273      * @param data the byte array to be encoded
274      * @return The string representation of the byte array
275      * 
276      * @since 3.0
277      */
278     public static String getAsciiString(final byte[] data) {
279         return getAsciiString(data, 0, data.length);
280     }
281 
282     /**
283      * This class should not be instantiated.
284      */
285     private EncodingUtil() {
286     }
287 
288 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/ExceptionUtil.html100644 0 0 27220 10661532627 26562 0ustar 0 0 ExceptionUtil xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/ExceptionUtil.java,v 1.5 2004/10/19 18:09:46 olegk Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient.util;
31  
32  import java.io.InterruptedIOException;
33  import java.lang.reflect.Method;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  
38  /**
39   * The home for utility methods that handle various exception-related tasks.
40   * 
41   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
42   * @author <a href="mailto:laura@lwerner.org">Laura Werner</a>
43   * 
44   * @since 3.0
45   */
46  public class ExceptionUtil {
47  
48      /** Log object for this class. */
49      private static final Log LOG = LogFactory.getLog(ExceptionUtil.class);
50  
51      /** A reference to Throwable's initCause method, or null if it's not there in this JVM */
52      static private final Method INIT_CAUSE_METHOD = getInitCauseMethod();
53  
54      /** A reference to SocketTimeoutExceptionClass class, or null if it's not there in this JVM */
55      static private final Class SOCKET_TIMEOUT_CLASS = SocketTimeoutExceptionClass();
56      
57      /**
58       * Returns a <code>Method<code> allowing access to
59       * {@link Throwable.initCause(Throwable) initCause} method of {@link Throwable},
60       * or <code>null</code> if the method
61       * does not exist.
62       * 
63       * @return A <code>Method<code> for <code>Throwable.initCause</code>, or
64       * <code>null</code> if unavailable.
65       */ 
66      static private Method getInitCauseMethod() {
67          try {
68              Class[] paramsClasses = new Class[] { Throwable.class };
69              return Throwable.class.getMethod("initCause", paramsClasses);
70          } catch (NoSuchMethodException e) {
71              return null;
72          }
73      }
74      
75      /**
76       * Returns <code>SocketTimeoutExceptionClass<code> or <code>null</code> if the class
77       * does not exist.
78       * 
79       * @return <code>SocketTimeoutExceptionClass<code>, or <code>null</code> if unavailable.
80       */ 
81      static private Class SocketTimeoutExceptionClass() {
82          try {
83              return Class.forName("java.net.SocketTimeoutException");
84          } catch (ClassNotFoundException e) {
85              return null;
86          }
87      }
88      
89      /** 
90       * If we're running on JDK 1.4 or later, initialize the cause for the given throwable.
91       * 
92       * @param  throwable The throwable.
93       * @param  cause     The cause of the throwable.
94       */
95      public static void initCause(Throwable throwable, Throwable cause) {
96          if (INIT_CAUSE_METHOD != null) {
97              try {
98                  INIT_CAUSE_METHOD.invoke(throwable, new Object[] { cause });
99              } catch (Exception e) {
100                 LOG.warn("Exception invoking Throwable.initCause", e);
101             }
102         }
103     }
104 
105     /** 
106      * If SocketTimeoutExceptionClass is defined, returns <tt>true</tt> only if the 
107      * exception is an instance of SocketTimeoutExceptionClass. If 
108      * SocketTimeoutExceptionClass is undefined, always returns <tt>true</tt>. 
109      * 
110      * @param  e an instance of InterruptedIOException class.
111      * 
112      * @return <tt>true</tt> if the exception signals socket timeout, <tt>false</tt>
113      *  otherwise.   
114      */
115     public static boolean isSocketTimeoutException(final InterruptedIOException e) {
116         if (SOCKET_TIMEOUT_CLASS != null) {
117             return SOCKET_TIMEOUT_CLASS.isInstance(e);
118         } else {
119             return true;
120         }
121     }
122 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/HttpURLConnection.html100644 0 0 127114 10661532627 27333 0ustar 0 0 HttpURLConnection xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/HttpURLConnection.java,v 1.15 2004/04/18 23:51:38 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.util;
32  
33  import org.apache.commons.httpclient.HttpMethod;
34  import org.apache.commons.httpclient.Header;
35  
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.commons.logging.Log;
38  import java.io.IOException;
39  import java.io.InputStream;
40  import java.io.OutputStream;
41  import java.net.URL;
42  import java.net.ProtocolException;
43  import java.security.Permission;
44  
45  /**
46   * Provides a <code>HttpURLConnection</code> wrapper around HttpClient's
47   * <code>HttpMethod</code>. This allows existing code to easily switch to
48   * HttpClieht without breaking existing interfaces using the JDK
49   * <code>HttpURLConnection</code>.
50   *
51   * Note 1: The current implementations wraps only a connected
52   * <code>HttpMethod</code>, ie a method that has alreayd been used to connect
53   * to an HTTP server.
54   *
55   * Note 2: It is a best try effort as different version of the JDK have
56   * different behaviours for <code>HttpURLConnection</code> (And I'm not even
57   * including the numerous <code>HttpURLConnection</code> bugs!).
58   *
59   * @author <a href="mailto:vmassol@apache.org">Vincent Massol</a>
60   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
61   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
62   *
63   * @since 2.0
64   *
65   * @version $Id: HttpURLConnection.java 480424 2006-11-29 05:56:49Z bayard $
66   */
67  public class HttpURLConnection extends java.net.HttpURLConnection {
68  
69      // -------------------------------------------------------- Class Variables
70     
71      /** Log object for this class. */
72      private static final Log LOG = LogFactory.getLog(HttpURLConnection.class);
73  
74  
75      // ----------------------------------------------------- Instance Variables
76  
77      /**
78       * The <code>HttpMethod</code> object that was used to connect to the
79       * HTTP server. It contains all the returned data.
80       */
81      private HttpMethod method;
82  
83      /**
84       * The URL to which we are connected
85       */
86      private URL url;
87  
88  
89  
90      // ----------------------------------------------------------- Constructors
91  
92      /**
93       * Creates an <code>HttpURLConnection</code> from a <code>HttpMethod</code>.
94       *
95       * @param method the theMethod that was used to connect to the HTTP
96       *        server and which contains the returned data.
97       * @param url the URL to which we are connected (includes query string)
98       */
99      public HttpURLConnection(HttpMethod method, URL url) {
100         super(url);
101         this.method = method;
102         this.url = url;
103     }
104 
105     /**
106      * Create an instance.
107      * @param url The URL.
108      * @see java.net.HttpURLConnection#HttpURLConnection(URL)
109      */
110     protected HttpURLConnection(URL url) {
111         super(url);
112         throw new RuntimeException("An HTTP URL connection can only be "
113             + "constructed from a HttpMethod class");
114     }
115 
116 
117     // --------------------------------------------------------- Public Methods
118 
119     /** 
120      * Gets an input stream for the HttpMethod response body.
121      * @throws IOException If an IO problem occurs.
122      * @return The input stream.
123      * @see java.net.HttpURLConnection#getInputStream()
124      * @see org.apache.commons.httpclient.HttpMethod#getResponseBodyAsStream()
125      */
126     public InputStream getInputStream() throws IOException {
127         LOG.trace("enter HttpURLConnection.getInputStream()");
128         return this.method.getResponseBodyAsStream();
129     }
130 
131     /**
132      * Not yet implemented.
133      * Return the error stream.
134      * @see java.net.HttpURLConnection#getErrorStream()
135      */
136     public InputStream getErrorStream() {
137         LOG.trace("enter HttpURLConnection.getErrorStream()");
138         throw new RuntimeException("Not implemented yet");
139     }
140 
141     /**
142      * Not yet implemented.
143      * @see java.net.HttpURLConnection#disconnect()
144      */
145     public void disconnect() {
146         LOG.trace("enter HttpURLConnection.disconnect()");
147         throw new RuntimeException("Not implemented yet");
148     }
149 
150     /**
151      * Not available: the data must have already been retrieved.
152      * @throws IOException If an IO problem occurs.
153      * @see java.net.HttpURLConnection#connect()
154      */
155     public void connect() throws IOException {
156         LOG.trace("enter HttpURLConnection.connect()");
157         throw new RuntimeException("This class can only be used with already"
158             + "retrieved data");
159     }
160 
161     /**
162      * Not yet implemented.
163      * @return true if we are using a proxy.
164      * @see java.net.HttpURLConnection#usingProxy()
165      */
166     public boolean usingProxy() {
167         LOG.trace("enter HttpURLConnection.usingProxy()");
168         throw new RuntimeException("Not implemented yet");
169     }
170 
171     /**
172      * Return the request method.
173      * @return The request method.
174      * @see java.net.HttpURLConnection#getRequestMethod()
175      * @see org.apache.commons.httpclient.HttpMethod#getName()
176      */
177     public String getRequestMethod() {
178         LOG.trace("enter HttpURLConnection.getRequestMethod()");
179         return this.method.getName();
180     }
181 
182     /**
183      * Return the response code.
184      * @return The response code.
185      * @throws IOException If an IO problem occurs.
186      * @see java.net.HttpURLConnection#getResponseCode()
187      * @see org.apache.commons.httpclient.HttpMethod#getStatusCode()
188      */
189     public int getResponseCode() throws IOException {
190         LOG.trace("enter HttpURLConnection.getResponseCode()");
191         return this.method.getStatusCode();
192     }
193 
194     /**
195      * Return the response message
196      * @return The response message
197      * @throws IOException If an IO problem occurs.
198      * @see java.net.HttpURLConnection#getResponseMessage()
199      * @see org.apache.commons.httpclient.HttpMethod#getStatusText()
200      */
201     public String getResponseMessage() throws IOException {
202         LOG.trace("enter HttpURLConnection.getResponseMessage()");
203         return this.method.getStatusText();
204     }
205 
206     /**
207      * Return the header field
208      * @param name the name of the header
209      * @return the header field.
210      * @see java.net.HttpURLConnection#getHeaderField(String)
211      * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders()
212      */
213     public String getHeaderField(String name) {
214         LOG.trace("enter HttpURLConnection.getHeaderField(String)");
215         // Note: Return the last matching header in the Header[] array, as in
216         // the JDK implementation.
217         Header[] headers = this.method.getResponseHeaders();
218         for (int i = headers.length - 1; i >= 0; i--) {
219             if (headers[i].getName().equalsIgnoreCase(name)) {
220                 return headers[i].getValue();
221             }
222         }
223 
224         return null;
225     }
226 
227     /**
228      * Return the header field key
229      * @param keyPosition The key position
230      * @return The header field key.
231      * @see java.net.HttpURLConnection#getHeaderFieldKey(int)
232      * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders()
233      */
234     public String getHeaderFieldKey(int keyPosition) {
235         LOG.trace("enter HttpURLConnection.getHeaderFieldKey(int)");
236 
237         // Note: HttpClient does not consider the returned Status Line as
238         // a response header. However, getHeaderFieldKey(0) is supposed to 
239         // return null. Hence the special case below ...
240         
241         if (keyPosition == 0) {
242             return null;
243         }
244 
245         // Note: HttpClient does not currently keep headers in the same order
246         // that they are read from the HTTP server.
247 
248         Header[] headers = this.method.getResponseHeaders();
249         if (keyPosition < 0 || keyPosition > headers.length) {
250             return null;
251         }
252 
253         return headers[keyPosition - 1].getName();
254     }
255 
256     /**
257      * Return the header field at the specified position
258      * @param position The position
259      * @return The header field.
260      * @see java.net.HttpURLConnection#getHeaderField(int)
261      * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders()
262      */
263     public String getHeaderField(int position) {
264         LOG.trace("enter HttpURLConnection.getHeaderField(int)");
265 
266         // Note: HttpClient does not consider the returned Status Line as
267         // a response header. However, getHeaderField(0) is supposed to 
268         // return the status line. Hence the special case below ...
269         
270         if (position == 0) {
271             return this.method.getStatusLine().toString();
272         }
273 
274         // Note: HttpClient does not currently keep headers in the same order
275         // that they are read from the HTTP server.
276 
277         Header[] headers = this.method.getResponseHeaders();
278         if (position < 0 || position > headers.length) {
279             return null;
280         }
281 
282         return headers[position - 1].getValue();
283     }
284 
285     /**
286      * Return the URL
287      * @return The URL.
288      * @see java.net.HttpURLConnection#getURL()
289      */
290     public URL getURL() {
291         LOG.trace("enter HttpURLConnection.getURL()");
292         return this.url;
293     }
294 
295     // Note: We don't implement the following methods so that they default to
296     // the JDK implementation. They will all call
297     // <code>getHeaderField(String)</code> which we have overridden.
298 
299     // java.net.HttpURLConnection#getHeaderFieldDate(String, long)
300     // java.net.HttpURLConnection#getContentLength()
301     // java.net.HttpURLConnection#getContentType()
302     // java.net.HttpURLConnection#getContentEncoding()
303     // java.net.HttpURLConnection#getDate()
304     // java.net.HttpURLConnection#getHeaderFieldInt(String, int)
305     // java.net.HttpURLConnection#getExpiration()
306     // java.net.HttpURLConnection#getLastModified()
307 
308     /**
309      * Not available: the data must have already been retrieved.
310      */
311     public void setInstanceFollowRedirects(boolean isFollowingRedirects) {
312         LOG.trace("enter HttpURLConnection.setInstanceFollowRedirects(boolean)");
313         throw new RuntimeException("This class can only be used with already"
314             + "retrieved data");
315     }
316 
317     /**
318      * Not yet implemented.
319      */
320     public boolean getInstanceFollowRedirects() {
321         LOG.trace("enter HttpURLConnection.getInstanceFollowRedirects()");
322         throw new RuntimeException("Not implemented yet");
323     }
324 
325     /**
326      * Not available: the data must have already been retrieved.
327      * @see java.net.HttpURLConnection#setRequestMethod(String)
328      */
329     public void setRequestMethod(String method) throws ProtocolException {
330         LOG.trace("enter HttpURLConnection.setRequestMethod(String)");
331         throw new RuntimeException("This class can only be used with already"
332             + "retrieved data");
333     }
334 
335     /**
336      * Not yet implemented.
337      * @see java.net.HttpURLConnection#getPermission()
338      */
339     public Permission getPermission() throws IOException {
340         LOG.trace("enter HttpURLConnection.getPermission()");
341         throw new RuntimeException("Not implemented yet");
342     }
343 
344     /**
345      * Not yet implemented.
346      * @see java.net.HttpURLConnection#getContent()
347      */
348     public Object getContent() throws IOException {
349         LOG.trace("enter HttpURLConnection.getContent()");
350         throw new RuntimeException("Not implemented yet");
351     }
352 
353     /**
354      * Not yet implemented.
355      */
356     public Object getContent(Class[] classes) throws IOException {
357         LOG.trace("enter HttpURLConnection.getContent(Class[])");
358         throw new RuntimeException("Not implemented yet");
359     }
360 
361     /**
362      * @see java.net.HttpURLConnection#getOutputStream()
363      */
364     public OutputStream getOutputStream() throws IOException {
365         LOG.trace("enter HttpURLConnection.getOutputStream()");
366         throw new RuntimeException("This class can only be used with already"
367             + "retrieved data");
368     }
369 
370     /**
371      * Not available: the data must have already been retrieved.
372      * @see java.net.HttpURLConnection#setDoInput(boolean)
373      */
374     public void setDoInput(boolean isInput) {
375         LOG.trace("enter HttpURLConnection.setDoInput()");
376         throw new RuntimeException("This class can only be used with already"
377             + "retrieved data");
378     }
379 
380     /**
381      * Not yet implemented.
382      * @see java.net.HttpURLConnection#getDoInput()
383      */
384     public boolean getDoInput() {
385         LOG.trace("enter HttpURLConnection.getDoInput()");
386         throw new RuntimeException("Not implemented yet");
387     }
388 
389     /**
390      * Not available: the data must have already been retrieved.
391      * @see java.net.HttpURLConnection#setDoOutput(boolean)
392      */
393     public void setDoOutput(boolean isOutput) {
394         LOG.trace("enter HttpURLConnection.setDoOutput()");
395         throw new RuntimeException("This class can only be used with already"
396             + "retrieved data");
397     }
398 
399     /**
400      * Not yet implemented.
401      * @see java.net.HttpURLConnection#getDoOutput()
402      */
403     public boolean getDoOutput() {
404         LOG.trace("enter HttpURLConnection.getDoOutput()");
405         throw new RuntimeException("Not implemented yet");
406     }
407 
408     /**
409      * Not available: the data must have already been retrieved.
410      * @see java.net.HttpURLConnection#setAllowUserInteraction(boolean)
411      */
412     public void setAllowUserInteraction(boolean isAllowInteraction) {
413         LOG.trace("enter HttpURLConnection.setAllowUserInteraction(boolean)");
414         throw new RuntimeException("This class can only be used with already"
415             + "retrieved data");
416     }
417 
418     /**
419      * Not yet implemented.
420      * @see java.net.HttpURLConnection#getAllowUserInteraction()
421      */
422     public boolean getAllowUserInteraction() {
423         LOG.trace("enter HttpURLConnection.getAllowUserInteraction()");
424         throw new RuntimeException("Not implemented yet");
425     }
426 
427     /**
428      * Not available: the data must have already been retrieved.
429      * @see java.net.HttpURLConnection#setUseCaches(boolean)
430      */
431     public void setUseCaches(boolean isUsingCaches) {
432         LOG.trace("enter HttpURLConnection.setUseCaches(boolean)");
433         throw new RuntimeException("This class can only be used with already"
434             + "retrieved data");
435     }
436 
437     /**
438      * Not yet implemented.
439      * @see java.net.HttpURLConnection#getUseCaches()
440      */
441     public boolean getUseCaches() {
442         LOG.trace("enter HttpURLConnection.getUseCaches()");
443         throw new RuntimeException("Not implemented yet");
444     }
445 
446     /**
447      * Not available: the data must have already been retrieved.
448      * @see java.net.HttpURLConnection#setIfModifiedSince(long)
449      */
450     public void setIfModifiedSince(long modificationDate) {
451         LOG.trace("enter HttpURLConnection.setIfModifiedSince(long)");
452         throw new RuntimeException("This class can only be used with already"
453             + "retrieved data");
454     }
455 
456     /**
457      * Not yet implemented.
458      * @see java.net.HttpURLConnection#getIfModifiedSince()
459      */
460     public long getIfModifiedSince() {
461         LOG.trace("enter HttpURLConnection.getIfmodifiedSince()");
462         throw new RuntimeException("Not implemented yet");
463     }
464 
465     /**
466      * Not available: the data must have already been retrieved.
467      * @see java.net.HttpURLConnection#getDefaultUseCaches()
468      */
469     public boolean getDefaultUseCaches() {
470         LOG.trace("enter HttpURLConnection.getDefaultUseCaches()");
471         throw new RuntimeException("Not implemented yet");
472     }
473 
474     /**
475      * Not available: the data must have already been retrieved.
476      * @see java.net.HttpURLConnection#setDefaultUseCaches(boolean)
477      */
478     public void setDefaultUseCaches(boolean isUsingCaches) {
479         LOG.trace("enter HttpURLConnection.setDefaultUseCaches(boolean)");
480         throw new RuntimeException("This class can only be used with already"
481             + "retrieved data");
482     }
483 
484     /**
485      * Not available: the data must have already been retrieved.
486      * @see java.net.HttpURLConnection#setRequestProperty(String,String)
487      */
488     public void setRequestProperty(String key, String value) {
489         LOG.trace("enter HttpURLConnection.setRequestProperty()");
490         throw new RuntimeException("This class can only be used with already"
491             + "retrieved data");
492     }
493 
494     /**
495      * Not yet implemented.
496      * @see java.net.HttpURLConnection#getRequestProperty(String)
497      */
498     public String getRequestProperty(String key) {
499         LOG.trace("enter HttpURLConnection.getRequestProperty()");
500         throw new RuntimeException("Not implemented yet");
501     }
502 
503 }
504 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/IdleConnectionHandler.html100644 0 0 26265 10661532627 30171 0ustar 0 0 IdleConnectionHandler xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/IdleConnectionHandler.java,v 1.2 2004/05/13 02:40:36 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient.util;
31  
32  import java.util.HashMap;
33  import java.util.Iterator;
34  import java.util.Map;
35  
36  import org.apache.commons.httpclient.HttpConnection;
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  
40  /**
41   * A helper class for connection managers to track idle connections.
42   * 
43   * <p>This class is not synchronized.</p>
44   * 
45   * @see org.apache.commons.httpclient.HttpConnectionManager#closeIdleConnections(long)
46   * 
47   * @since 3.0
48   */
49  public class IdleConnectionHandler {
50      
51      private static final Log LOG = LogFactory.getLog(IdleConnectionHandler.class);
52      
53      /** Holds connections and the time they were added. */
54      private Map connectionToAdded = new HashMap();
55      
56      /**
57       * 
58       */
59      public IdleConnectionHandler() {
60          super();
61      }
62      
63      /**
64       * Registers the given connection with this handler.  The connection will be held until 
65       * {@link #remove(HttpConnection)} or {@link #closeIdleConnections(long)} is called.
66       * 
67       * @param connection the connection to add
68       * 
69       * @see #remove(HttpConnection)
70       */
71      public void add(HttpConnection connection) {
72          
73          Long timeAdded = new Long(System.currentTimeMillis());
74          
75          if (LOG.isDebugEnabled()) {
76              LOG.debug("Adding connection at: " + timeAdded);
77          }
78          
79          connectionToAdded.put(connection, timeAdded);
80      }
81      
82      /**
83       * Removes the given connection from the list of connections to be closed when idle.
84       * @param connection
85       */
86      public void remove(HttpConnection connection) {
87          connectionToAdded.remove(connection);
88      }
89  
90      /**
91       * Removes all connections referenced by this handler.
92       */
93      public void removeAll() {
94          this.connectionToAdded.clear();
95      }
96      
97      /**
98       * Closes connections that have been idle for at least the given amount of time.
99       * 
100      * @param idleTime the minimum idle time, in milliseconds, for connections to be closed
101      */
102     public void closeIdleConnections(long idleTime) {
103         
104         // the latest time for which connections will be closed
105         long idleTimeout = System.currentTimeMillis() - idleTime;
106 
107         if (LOG.isDebugEnabled()) {
108             LOG.debug("Checking for connections, idleTimeout: "  + idleTimeout);
109         }
110         
111         Iterator connectionIter = connectionToAdded.keySet().iterator();
112         
113         while (connectionIter.hasNext()) {
114             HttpConnection conn = (HttpConnection) connectionIter.next();
115             Long connectionTime = (Long) connectionToAdded.get(conn);
116             if (connectionTime.longValue() <= idleTimeout) {
117                 if (LOG.isDebugEnabled()) {
118                     LOG.debug("Closing connection, connection time: "  + connectionTime);
119                 }
120                 connectionIter.remove();
121                 conn.close();
122             }
123         }
124     }
125 }

././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/IdleConnectionTimeoutThread.htmlcommons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/IdleConnectionTimeoutThread.html100644 0 0 34020 10661532627 31356 0ustar 0 0 IdleConnectionTimeoutThread xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/IdleConnectionTimeoutThread.java,v 1.2 2004/05/13 02:40:36 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  package org.apache.commons.httpclient.util;
31  
32  import java.util.ArrayList;
33  import java.util.Iterator;
34  import java.util.List;
35  
36  import org.apache.commons.httpclient.HttpConnectionManager;
37  
38  /**
39   * A utility class for periodically closing idle connections.
40   * 
41   * @see org.apache.commons.httpclient.HttpConnectionManager#closeIdleConnections(long)
42   * 
43   * @since 3.0
44   */
45  public class IdleConnectionTimeoutThread extends Thread {
46      
47      private List connectionManagers = new ArrayList();
48      
49      private boolean shutdown = false;
50      
51      private long timeoutInterval = 1000;
52      
53      private long connectionTimeout = 3000;
54      
55      public IdleConnectionTimeoutThread() {
56          setDaemon(true);
57      }
58      
59      /**
60       * Adds a connection manager to be handled by this class.  
61       * {@link HttpConnectionManager#closeIdleConnections(long)} will be called on the connection
62       * manager every {@link #setTimeoutInterval(long) timeoutInterval} milliseconds.
63       * 
64       * @param connectionManager The connection manager to add
65       */
66      public synchronized void addConnectionManager(HttpConnectionManager connectionManager) {
67          if (shutdown) {
68              throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown");
69          }
70          this.connectionManagers.add(connectionManager);
71      }
72      
73      /**
74       * Removes the connection manager from this class.  The idle connections from the connection
75       * manager will no longer be automatically closed by this class.
76       * 
77       * @param connectionManager The connection manager to remove
78       */
79      public synchronized void removeConnectionManager(HttpConnectionManager connectionManager) {
80          if (shutdown) {
81              throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown");
82          }
83          this.connectionManagers.remove(connectionManager);
84      }
85      
86      /**
87       * Handles calling {@link HttpConnectionManager#closeIdleConnections(long) closeIdleConnections()}
88       * and doing any other cleanup work on the given connection mangaer.
89       * @param connectionManager The connection manager to close idle connections for
90       */
91      protected void handleCloseIdleConnections(HttpConnectionManager connectionManager) {
92          connectionManager.closeIdleConnections(connectionTimeout);
93      }
94      
95      /**
96       * Closes idle connections.
97       */
98      public synchronized void run() {
99          while (!shutdown) {
100             Iterator iter = connectionManagers.iterator();
101             
102             while (iter.hasNext()) {
103                 HttpConnectionManager connectionManager = (HttpConnectionManager) iter.next();
104                 handleCloseIdleConnections(connectionManager);
105             }
106             
107             try {
108                 this.wait(timeoutInterval);
109             } catch (InterruptedException e) {
110             }
111         }
112         // clear out the connection managers now that we're shutdown
113         this.connectionManagers.clear();
114     }
115     
116     /**
117      * Stops the thread used to close idle connections.  This class cannot be used once shutdown.
118      */
119     public synchronized void shutdown() {
120         this.shutdown = true;
121         this.notifyAll();
122     }
123     
124     /**
125      * Sets the timeout value to use when testing for idle connections.
126      * 
127      * @param connectionTimeout The connection timeout in milliseconds
128      * 
129      * @see HttpConnectionManager#closeIdleConnections(long)
130      */
131     public synchronized void setConnectionTimeout(long connectionTimeout) {
132         if (shutdown) {
133             throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown");
134         }
135         this.connectionTimeout = connectionTimeout;
136     }
137     /**
138      * Sets the interval used by this class between closing idle connections.  Idle 
139      * connections will be closed every <code>timeoutInterval</code> milliseconds.
140      *  
141      * @param timeoutInterval The timeout interval in milliseconds
142      */
143     public synchronized void setTimeoutInterval(long timeoutInterval) {
144         if (shutdown) {
145             throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown");
146         }
147         this.timeoutInterval = timeoutInterval;
148     }
149     
150 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/LangUtils.html100644 0 0 15645 10661532627 25700 0ustar 0 0 LangUtils xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/util/LangUtils.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.util;
32  
33  /**
34   * A set of utility methods to help produce consistent Object#equals(Object) and
35   * Object#hashCode methods.
36   *  
37   * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
38   * 
39   * @since 3.0
40   */
41  public class LangUtils {
42      
43      public static final int HASH_SEED = 17;
44      public static final int HASH_OFFSET = 37;
45      
46      private LangUtils() {
47          super();
48      }
49  
50      public static int hashCode(final int seed, final int hashcode) {
51          return seed * HASH_OFFSET + hashcode;
52      }
53  
54      public static int hashCode(final int seed, final Object obj) {
55          return hashCode(seed, obj != null ? obj.hashCode() : 0);
56      }
57      
58      public static int hashCode(final int seed, final boolean b) {
59          return hashCode(seed, b ? 1 : 0);
60      }
61      
62      public static boolean equals(final Object obj1, final Object obj2) {
63          return obj1 == null ? obj2 == null : obj1.equals(obj2);
64      }
65  
66  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/ParameterFormatter.html100644 0 0 52202 10661532627 27570 0ustar 0 0 ParameterFormatter xref

1   /*
2    * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/util/ParameterFormatter.java $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.util;
32  
33  import org.apache.commons.httpclient.NameValuePair;
34  
35  /**
36   * <p>
37   *  This formatter produces a textual representation of attribute/value pairs. It 
38   *  comforms to the generic grammar and formatting rules outlined in the 
39   *  <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.1">Section 2.1</a>
40   *  and  
41   *  <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6">Section 3.6</a>
42   *  of <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.txt">RFC 2616</a>
43   * </p>
44   * <h>2.1 Augmented BNF</h>
45   * <p>
46   *  Many HTTP/1.1 header field values consist of words separated by LWS or special 
47   *  characters. These special characters MUST be in a quoted string to be used within 
48   *  a parameter value (as defined in section 3.6).
49   * <p>
50   * <pre>
51   * token          = 1*<any CHAR except CTLs or separators>
52   * separators     = "(" | ")" | "<" | ">" | "@"
53   *                | "," | ";" | ":" | "\" | <">
54   *                | "/" | "[" | "]" | "?" | "="
55   *                | "{" | "}" | SP | HT
56   * </pre>
57   * <p>
58   *  A string of text is parsed as a single word if it is quoted using double-quote marks.
59   * </p>
60   * <pre>
61   * quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
62   * qdtext         = <any TEXT except <">>
63   * </pre>
64   * <p>
65   *  The backslash character ("\") MAY be used as a single-character quoting mechanism only 
66   *  within quoted-string and comment constructs.
67   * </p>
68   * <pre>
69   * quoted-pair    = "\" CHAR
70   * </pre>
71   * <h>3.6 Transfer Codings</h>
72   * <p>
73   *  Parameters are in the form of attribute/value pairs.
74   * </p>
75   * <pre>
76   * parameter               = attribute "=" value
77   * attribute               = token
78   * value                   = token | quoted-string
79   * </pre>
80   * 
81   * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
82   * 
83   * @since 3.0
84   */
85  public class ParameterFormatter {
86      
87      /**
88       * Special characters that can be used as separators in HTTP parameters.
89       * These special characters MUST be in a quoted string to be used within
90       * a parameter value 
91       */
92      private static final char[] SEPARATORS   = {
93              '(', ')', '<', '>', '@', 
94              ',', ';', ':', '\\', '"', 
95              '/', '[', ']', '?', '=',
96              '{', '}', ' ', '\t'
97              };
98      
99      /**
100      * Unsafe special characters that must be escaped using the backslash
101      * character
102      */
103     private static final char[] UNSAFE_CHARS = {
104             '"', '\\'
105             };
106     
107     /**
108      * This flag determines whether all parameter values must be enclosed in 
109      * quotation marks, even if they do not contain any special characters
110      */
111     private boolean alwaysUseQuotes = true;
112     
113     /** Default ParameterFormatter constructor */
114     public ParameterFormatter() {
115         super();
116     }
117     
118     private static boolean isOneOf(char[] chars, char ch) {
119         for (int i = 0; i < chars.length; i++) {
120             if (ch == chars[i]) {
121                 return true;
122             }
123         }
124         return false;
125     }
126     
127     private static boolean isUnsafeChar(char ch) {
128         return isOneOf(UNSAFE_CHARS, ch);
129     }
130     
131     private static boolean isSeparator(char ch) {
132         return isOneOf(SEPARATORS, ch);
133     }
134 
135     /**
136      * Determines whether all parameter values must be enclosed in quotation 
137      * marks, even if they do not contain any special characters
138      * 
139      * @return <tt>true</tt> if all parameter values must be enclosed in 
140      * quotation marks, <tt>false</tt> otherwise
141      */
142     public boolean isAlwaysUseQuotes() {
143         return alwaysUseQuotes;
144     }
145     
146     /**
147      * Defines whether all parameter values must be enclosed in quotation 
148      * marks, even if they do not contain any special characters
149      * 
150      * @param alwaysUseQuotes
151      */
152     public void setAlwaysUseQuotes(boolean alwaysUseQuotes) {
153         this.alwaysUseQuotes = alwaysUseQuotes;
154     }
155     
156     /**
157      * Formats the given parameter value using formatting rules defined
158      * in RFC 2616 
159      * 
160      * @param buffer output buffer 
161      * @param value the parameter value to be formatted
162      * @param alwaysUseQuotes <tt>true</tt> if the parameter value must 
163      * be enclosed in quotation marks, even if it does not contain any special 
164      * characters<tt>, false</tt> only if the parameter value contains 
165      * potentially unsafe special characters
166      */
167     public static void formatValue(
168             final StringBuffer buffer, final String value, boolean alwaysUseQuotes) {
169         if (buffer == null) {
170             throw new IllegalArgumentException("String buffer may not be null");
171         }
172         if (value == null) {
173             throw new IllegalArgumentException("Value buffer may not be null");
174         }
175         if (alwaysUseQuotes) {
176             buffer.append('"');
177             for (int i = 0; i < value.length(); i++) {
178                 char ch = value.charAt(i);
179                 if (isUnsafeChar(ch)) {
180                     buffer.append('\\');
181                 }
182                 buffer.append(ch);
183             }
184             buffer.append('"');
185         } else {
186             int offset = buffer.length();
187             boolean unsafe = false;
188             for (int i = 0; i < value.length(); i++) {
189                 char ch = value.charAt(i);
190                 if (isSeparator(ch)) {
191                     unsafe = true;
192                 }
193                 if (isUnsafeChar(ch)) {
194                     buffer.append('\\');
195                 }
196                 buffer.append(ch);
197             }
198             if (unsafe) {
199                 buffer.insert(offset, '"');
200                 buffer.append('"');
201             }
202         }
203     }
204     
205     /**
206      * Produces textual representaion of the attribute/value pair using 
207      * formatting rules defined in RFC 2616
208      *  
209      * @param buffer output buffer 
210      * @param param the parameter to be formatted
211      */
212     public void format(final StringBuffer buffer, final NameValuePair param) {
213         if (buffer == null) {
214             throw new IllegalArgumentException("String buffer may not be null");
215         }
216         if (param == null) {
217             throw new IllegalArgumentException("Parameter may not be null");
218         }
219         buffer.append(param.getName());
220         String value = param.getValue();
221         if (value != null) {
222             buffer.append("=");
223             formatValue(buffer, value, this.alwaysUseQuotes);
224         }
225     }
226     
227     /**
228      * Produces textual representaion of the attribute/value pair using 
229      * formatting rules defined in RFC 2616
230      *  
231      * @param param the parameter to be formatted
232      * 
233      * @return RFC 2616 conformant textual representaion of the 
234      * attribute/value pair
235      */
236     public String format(final NameValuePair param) {
237         StringBuffer buffer = new StringBuffer();
238         format(buffer, param);
239         return buffer.toString();
240     }
241 
242 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/ParameterParser.html100644 0 0 46437 10661532627 27076 0ustar 0 0 ParameterParser xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/ParameterParser.java,v 1.5 2004/05/13 04:01:22 mbecke Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.util;
32  import java.util.ArrayList;
33  import java.util.List;
34  
35  import org.apache.commons.httpclient.NameValuePair;
36  
37  /**
38   * A simple parser intended to parse sequences of name/value pairs.
39   * Parameter values are exptected to be enclosed in quotes if they 
40   * contain unsafe characters, such as '=' characters or separators.
41   * Parameter values are optional and can be omitted. 
42   * 
43   * <p>
44   *  <code>param1 = value; param2 = "anything goes; really"; param3</code>
45   * </p>
46   * 
47   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
48   * 
49   * @since 3.0
50   */
51  public class ParameterParser {
52      
53      /** String to be parsed */
54      private char[] chars = null;
55      
56      /** Current position in the string */    
57      private int pos = 0;
58  
59      /** Maximum position in the string */    
60      private int len = 0;
61  
62      /** Start of a token */
63      private int i1 = 0;
64  
65      /** End of a token */
66      private int i2 = 0;
67      
68      /** Default ParameterParser constructor */
69      public ParameterParser() {
70          super();
71      }
72  
73  
74      /** Are there any characters left to parse? */
75      private boolean hasChar() {
76          return this.pos < this.len;
77      }
78  
79      
80      /** A helper method to process the parsed token. */
81      private String getToken(boolean quoted) {
82          // Trim leading white spaces
83          while ((i1 < i2) && (Character.isWhitespace(chars[i1]))) {
84              i1++;
85          }
86          // Trim trailing white spaces
87          while ((i2 > i1) && (Character.isWhitespace(chars[i2 - 1]))) {
88              i2--;
89          }
90          // Strip away quotes if necessary
91          if (quoted) {
92              if (((i2 - i1) >= 2) 
93                  && (chars[i1] == '"') 
94                  && (chars[i2 - 1] == '"')) {
95                  i1++;
96                  i2--;
97              }
98          }
99          String result = null;
100         if (i2 >= i1) {
101             result = new String(chars, i1, i2 - i1);
102         }
103         return result;
104     }
105 
106 
107     /** Is given character present in the array of characters? */
108     private boolean isOneOf(char ch, char[] charray) {
109         boolean result = false;
110         for (int i = 0; i < charray.length; i++) {
111             if (ch == charray[i]) {
112                 result = true;
113                 break;
114             }
115         }
116         return result;
117     }
118     
119     
120     /** Parse out a token until any of the given terminators
121      * is encountered. */
122     private String parseToken(final char[] terminators) {
123         char ch;
124         i1 = pos;
125         i2 = pos;
126         while (hasChar()) {
127             ch = chars[pos];
128             if (isOneOf(ch, terminators)) {
129                 break;
130             }
131             i2++;
132             pos++;
133         }
134         return getToken(false);
135     }
136     
137     
138     /** Parse out a token until any of the given terminators
139      * is encountered. Special characters in quoted tokens
140      * are escaped. */
141     private String parseQuotedToken(final char[] terminators) {
142         char ch;
143         i1 = pos;
144         i2 = pos;
145         boolean quoted = false;
146         boolean charEscaped = false;
147         while (hasChar()) {
148             ch = chars[pos];
149             if (!quoted && isOneOf(ch, terminators)) {
150                 break;
151             }
152             if (!charEscaped && ch == '"') {
153                 quoted = !quoted;
154             }
155             charEscaped = (!charEscaped && ch == '\\');
156             i2++;
157             pos++;
158 
159         }
160         return getToken(true);
161     }
162     
163     /** 
164      * Extracts a list of {@link NameValuePair}s from the given string.
165      *
166      * @param str the string that contains a sequence of name/value pairs
167      * @return a list of {@link NameValuePair}s
168      * 
169      */
170     public List parse(final String str, char separator) {
171 
172         if (str == null) {
173             return new ArrayList();
174         }
175         return parse(str.toCharArray(), separator);
176     }
177 
178     /** 
179      * Extracts a list of {@link NameValuePair}s from the given array of 
180      * characters.
181      *
182      * @param chars the array of characters that contains a sequence of 
183      * name/value pairs
184      * 
185      * @return a list of {@link NameValuePair}s
186      */
187     public List parse(final char[] chars, char separator) {
188 
189         if (chars == null) {
190             return new ArrayList();
191         }
192         return parse(chars, 0, chars.length, separator);
193     }
194 
195 
196     /** 
197      * Extracts a list of {@link NameValuePair}s from the given array of 
198      * characters.
199      *
200      * @param chars the array of characters that contains a sequence of 
201      * name/value pairs
202      * @param offset - the initial offset.
203      * @param length - the length.
204      * 
205      * @return a list of {@link NameValuePair}s
206      */
207     public List parse(final char[] chars, int offset, int length, char separator) {
208 
209         if (chars == null) {
210             return new ArrayList();
211         }
212         List params = new ArrayList();
213         this.chars = chars;
214         this.pos = offset;
215         this.len = length;
216         
217         String paramName = null;
218         String paramValue = null;
219         while (hasChar()) {
220             paramName = parseToken(new char[] {'=', separator});
221             paramValue = null;
222             if (hasChar() && (chars[pos] == '=')) {
223                 pos++; // skip '='
224                 paramValue = parseQuotedToken(new char[] {separator});
225             }
226             if (hasChar() && (chars[pos] == separator)) {
227                 pos++; // skip separator
228             }
229             if (paramName != null && !(paramName.equals("") && paramValue == null)) {
230                 params.add(new NameValuePair(paramName, paramValue));
231             }
232         }        
233         return params;
234     }
235 }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/TimeoutController.html100644 0 0 21742 10661532627 27463 0ustar 0 0 TimeoutController xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/TimeoutController.java,v 1.6 2004/04/18 23:51:38 jsdever Exp $
3    * $Revision: 480424 $
4    * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.util;
32  
33  /**
34   * <p>
35   * Executes a task with a specified timeout.
36   * </p>
37   * @author Ortwin Glueck
38   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
39   * @version $Revision: 480424 $
40   * @since 2.0
41   */
42  public final class TimeoutController {
43  
44      /**
45       * Do not instantiate objects of this class. Methods are static.
46       */
47      private TimeoutController() {
48      }
49  
50      /**
51       * Executes <code>task</code>. Waits for <code>timeout</code>
52       * milliseconds for the task to end and returns. If the task does not return
53       * in time, the thread is interrupted and an Exception is thrown.
54       * The caller should override the Thread.interrupt() method to something that
55       * quickly makes the thread die or use Thread.isInterrupted().
56       * @param task The thread to execute
57       * @param timeout The timeout in milliseconds. 0 means to wait forever.
58       * @throws TimeoutException if the timeout passes and the thread does not return.
59       */
60      public static void execute(Thread task, long timeout) throws TimeoutException {
61          task.start();
62          try {
63              task.join(timeout);
64          } catch (InterruptedException e) {
65              /* if somebody interrupts us he knows what he is doing */
66          }
67          if (task.isAlive()) {
68              task.interrupt();
69              throw new TimeoutException();
70          }
71      }
72  
73      /**
74       * Executes <code>task</code> in a new deamon Thread and waits for the timeout.
75       * @param task The task to execute
76       * @param timeout The timeout in milliseconds. 0 means to wait forever.
77       * @throws TimeoutException if the timeout passes and the thread does not return.
78       */
79      public static void execute(Runnable task, long timeout) throws TimeoutException {
80          Thread t = new Thread(task, "Timeout guard");
81          t.setDaemon(true);
82          execute(t, timeout);
83      }
84  
85      /**
86       * Signals that the task timed out.
87       */
88      public static class TimeoutException extends Exception {
89          /** Create an instance */
90          public TimeoutException() {
91          }
92      }
93  }

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/URIUtil.html100644 0 0 151362 10661532627 25310 0ustar 0 0 URIUtil xref

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/URIUtil.java,v 1.27 2004/05/05 20:34:01 olegk Exp $
3    * $Revision: 507321 $
4    * $Date: 2007-02-14 01:10:51 +0100 (Wed, 14 Feb 2007) $
5    *
6    * ====================================================================
7    *
8    *  Licensed to the Apache Software Foundation (ASF) under one or more
9    *  contributor license agreements.  See the NOTICE file distributed with
10   *  this work for additional information regarding copyright ownership.
11   *  The ASF licenses this file to You under the Apache License, Version 2.0
12   *  (the "License"); you may not use this file except in compliance with
13   *  the License.  You may obtain a copy of the License at
14   *
15   *      http://www.apache.org/licenses/LICENSE-2.0
16   *
17   *  Unless required by applicable law or agreed to in writing, software
18   *  distributed under the License is distributed on an "AS IS" BASIS,
19   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   *  See the License for the specific language governing permissions and
21   *  limitations under the License.
22   * ====================================================================
23   *
24   * This software consists of voluntary contributions made by many
25   * individuals on behalf of the Apache Software Foundation.  For more
26   * information on the Apache Software Foundation, please see
27   * <http://www.apache.org/>.
28   *
29   */
30  
31  package org.apache.commons.httpclient.util;
32  
33  import java.util.BitSet;
34  
35  import org.apache.commons.codec.DecoderException;
36  import org.apache.commons.codec.net.URLCodec;
37  import org.apache.commons.httpclient.URI;
38  import org.apache.commons.httpclient.URIException;
39  
40  /**
41   * The URI escape and character encoding and decoding utility.
42   * It's compatible with {@link org.apache.commons.httpclient.HttpURL} rather
43   * than {@link org.apache.commons.httpclient.URI}.
44   *
45   * @author <a href="mailto:jericho@apache.org">Sung-Gu</a>
46   * @version $Revision: 507321 $ $Date: 2002/03/14 15:14:01 
47   */
48  public class URIUtil {
49  
50      // ----------------------------------------------------- Instance variables
51  
52      protected static final BitSet empty = new BitSet(1);
53  
54      // ---------------------------------------------------------- URI utilities
55  
56      /**
57       * Get the basename of an URI.   It's possibly an empty string.
58       *
59       * @param uri a string regarded an URI
60       * @return the basename string; an empty string if the path ends with slash
61       */
62      public static String getName(String uri) {
63          if (uri == null || uri.length() == 0) { return uri; } 
64          String path = URIUtil.getPath(uri);
65          int at = path.lastIndexOf("/");
66          int to = path.length();
67          return (at >= 0) ? path.substring(at + 1, to) : path;
68      }
69  
70  
71      /**
72       * Get the query of an URI.
73       *
74       * @param uri a string regarded an URI
75       * @return the query string; <code>null</code> if empty or undefined
76       */
77      public static String getQuery(String uri) {
78          if (uri == null || uri.length() == 0) { return null; } 
79          // consider of net_path
80          int at = uri.indexOf("//");
81          int from = uri.indexOf(
82              "/", 
83              at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0
84          );
85          // the authority part of URI ignored
86          int to = uri.length();
87          // reuse the at and from variables to consider the query
88          at = uri.indexOf("?", from);
89          if (at >= 0) {
90              from = at + 1;
91          } else {
92              return null;
93          }
94          // check the fragment
95          if (uri.lastIndexOf("#") > from) {
96              to = uri.lastIndexOf("#");
97          }
98          // get the path and query.
99          return (from < 0 || from == to) ? null : uri.substring(from, to);
100     }
101 
102 
103     /**
104      * Get the path of an URI.
105      *
106      * @param uri a string regarded an URI
107      * @return the path string
108      */
109     public static String getPath(String uri) {
110         if (uri == null) {
111             return null;
112         } 
113         // consider of net_path
114         int at = uri.indexOf("//");
115         int from = uri.indexOf(
116             "/", 
117             at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0
118         );
119         // the authority part of URI ignored 
120         int to = uri.length();
121         // check the query
122         if (uri.indexOf('?', from) != -1) {
123             to = uri.indexOf('?', from);
124         }
125         // check the fragment
126         if (uri.lastIndexOf("#") > from && uri.lastIndexOf("#") < to) {
127             to = uri.lastIndexOf("#");
128         }
129         // get only the path.
130         return (from < 0) ? (at >= 0 ? "/" : uri) : uri.substring(from, to);
131     }
132 
133 
134     /**
135      * Get the path and query of an URI.
136      *
137      * @param uri a string regarded an URI
138      * @return the path and query string
139      */
140     public static String getPathQuery(String uri) {
141         if (uri == null) {
142             return null;
143         } 
144         // consider of net_path
145         int at = uri.indexOf("//");
146         int from = uri.indexOf(
147             "/", 
148             at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0
149         );
150         // the authority part of URI ignored
151         int to = uri.length();
152         // Ignore the '?' mark so to ignore the query.
153         // check the fragment
154         if (uri.lastIndexOf("#") > from) {
155             to = uri.lastIndexOf("#");
156         }
157         // get the path and query.
158         return (from < 0) ? (at >= 0 ? "/" : uri) : uri.substring(from, to);
159     }
160 
161 
162     /**
163      * Get the path of an URI and its rest part.
164      *
165      * @param uri a string regarded an URI
166      * @return the string from the path part
167      */
168     public static String getFromPath(String uri) {
169         if (uri == null) {
170             return null;
171         } 
172         // consider of net_path
173         int at = uri.indexOf("//");
174         int from = uri.indexOf(
175             "/", 
176             at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0
177         );
178         // get the path and its rest.
179         return (from < 0) ? (at >= 0 ? "/" : uri) : uri.substring(from);
180     }
181 
182     // ----------------------------------------------------- Encoding utilities
183 
184     /**
185      * Get the all escaped and encoded string with the default protocl charset.
186      * It's the same function to use <code>encode(String unescaped, Bitset
187      * empty, URI.getDefaultProtocolCharset())</code>.
188      *
189      * @param unescaped an unescaped string
190      * @return the escaped string
191      * 
192      * @throws URIException if the default protocol charset is not supported
193      *
194      * @see URI#getDefaultProtocolCharset
195      * @see #encode
196      */
197     public static String encodeAll(String unescaped) throws URIException {
198         return encodeAll(unescaped, URI.getDefaultProtocolCharset());
199     }
200  
201 
202     /**
203      * Get the all escaped and encoded string with a given charset.
204      * It's the same function to use <code>encode(String unescaped, Bitset
205      * empty, String charset)</code>.
206      *
207      * @param unescaped an unescaped string
208      * @param charset the charset
209      * @return the escaped string
210      * 
211      * @throws URIException if the charset is not supported
212      * 
213      * @see #encode
214      */
215     public static String encodeAll(String unescaped, String charset)
216         throws URIException {
217 
218         return encode(unescaped, empty, charset);
219     }
220   
221 
222     /**
223      * Escape and encode a string regarded as within the authority component of
224      * an URI with the default protocol charset.
225      * Within the authority component, the characters ";", ":", "@", "?", and
226      * "/" are reserved.
227      *
228      * @param unescaped an unescaped string
229      * @return the escaped string
230      * 
231      * @throws URIException if the default protocol charset is not supported
232      * 
233      * @see URI#getDefaultProtocolCharset
234      * @see #encode
235      */
236     public static String encodeWithinAuthority(String unescaped)
237         throws URIException {
238 
239         return encodeWithinAuthority(unescaped, URI.getDefaultProtocolCharset());
240     }
241 
242 
243     /**
244      * Escape and encode a string regarded as within the authority component of
245      * an URI with a given charset.
246      * Within the authority component, the characters ";", ":", "@", "?", and
247      * "/" are reserved.
248      *
249      * @param unescaped an unescaped string
250      * @param charset the charset
251      * @return the escaped string
252      * 
253      * @throws URIException if the charset is not supported
254      * 
255      * @see #encode
256      */
257     public static String encodeWithinAuthority(String unescaped, String charset)
258         throws URIException {
259 
260         return encode(unescaped, URI.allowed_within_authority, charset);
261     }
262 
263 
264     /**
265      * Escape and encode a string regarded as the path and query components of
266      * an URI with the default protocol charset.
267      *
268      * @param unescaped an unescaped string
269      * @return the escaped string
270      * 
271      * @throws URIException if the default protocol charset is not supported
272      * 
273      * @see URI#getDefaultProtocolCharset
274      * @see #encode
275      */
276     public static String encodePathQuery(String unescaped) throws URIException {
277         return encodePathQuery(unescaped, URI.getDefaultProtocolCharset());
278     }
279 
280 
281     /**
282      * Escape and encode a string regarded as the path and query components of
283      * an URI with a given charset.
284      *
285      * @param unescaped an unescaped string
286      * @param charset the charset
287      * @return the escaped string
288      * 
289      * @throws URIException if the charset is not supported
290      * 
291      * @see #encode
292      */
293     public static String encodePathQuery(String unescaped, String charset)
294         throws URIException {
295 
296         int at = unescaped.indexOf('?');
297         if (at < 0) {
298             return encode(unescaped, URI.allowed_abs_path, charset);
299         }
300         // else
301         return  encode(unescaped.substring(0, at), URI.allowed_abs_path, charset)
302             + '?' + encode(unescaped.substring(at + 1), URI.allowed_query, charset);
303     }
304 
305 
306     /**
307      * Escape and encode a string regarded as within the path component of an
308      * URI with the default protocol charset.
309      * The path may consist of a sequence of path segments separated by a
310      * single slash "/" character.  Within a path segment, the characters
311      * "/", ";", "=", and "?" are reserved.
312      *
313      * @param unescaped an unescaped string
314      * @return the escaped string
315      * 
316      * @throws URIException if the default protocol charset is not supported
317      * 
318      * @see URI#getDefaultProtocolCharset
319      * @see #encode
320      */
321     public static String encodeWithinPath(String unescaped)
322         throws URIException {
323 
324         return encodeWithinPath(unescaped, URI.getDefaultProtocolCharset());
325     }
326 
327 
328     /**
329      * Escape and encode a string regarded as within the path component of an
330      * URI with a given charset.
331      * The path may consist of a sequence of path segments separated by a
332      * single slash "/" character.  Within a path segment, the characters
333      * "/", ";", "=", and "?" are reserved.
334      *
335      * @param unescaped an unescaped string
336      * @param charset the charset
337      * @return the escaped string
338      * 
339      * @throws URIException if the charset is not supported
340      * 
341      * @see #encode
342      */
343     public static String encodeWithinPath(String unescaped, String charset)
344         throws URIException {
345 
346         return encode(unescaped, URI.allowed_within_path, charset);
347     }
348 
349 
350     /**
351      * Escape and encode a string regarded as the path component of an URI with
352      * the default protocol charset.
353      *
354      * @param unescaped an unescaped string
355      * @return the escaped string
356      * 
357      * @throws URIException if the default protocol charset is not supported
358      * 
359      * @see URI#getDefaultProtocolCharset
360      * @see #encode
361      */
362     public static String encodePath(String unescaped) throws URIException {
363         return encodePath(unescaped, URI.getDefaultProtocolCharset());
364     }
365 
366 
367     /**
368      * Escape and encode a string regarded as the path component of an URI with
369      * a given charset.
370      *
371      * @param unescaped an unescaped string
372      * @param charset the charset
373      * @return the escaped string
374      * 
375      * @throws URIException if the charset is not supported
376      * 
377      * @see #encode
378      */
379     public static String encodePath(String unescaped, String charset)
380         throws URIException {
381 
382         return encode(unescaped, URI.allowed_abs_path, charset);
383     }
384 
385 
386     /**
387      * Escape and encode a string regarded as within the query component of an
388      * URI with the default protocol charset.
389      * When a query comprise the name and value pairs, it is used in order
390      * to encode each name and value string.  The reserved special characters
391      * within a query component are being included in encoding the query.
392      *
393      * @param unescaped an unescaped string
394      * @return the escaped string
395      * 
396      * @throws URIException if the default protocol charset is not supported
397      * 
398      * @see URI#getDefaultProtocolCharset
399      * @see #encode
400      */
401     public static String encodeWithinQuery(String unescaped)
402         throws URIException {
403 
404         return encodeWithinQuery(unescaped, URI.getDefaultProtocolCharset());
405     }
406 
407 
408     /**
409      * Escape and encode a string regarded as within the query component of an
410      * URI with a given charset.
411      * When a query comprise the name and value pairs, it is used in order
412      * to encode each name and value string.  The reserved special characters
413      * within a query component are being included in encoding the query.
414      *
415      * @param unescaped an unescaped string
416      * @param charset the charset
417      * @return the escaped string
418      * 
419      * @throws URIException if the charset is not supported
420      * 
421      * @see #encode
422      */
423     public static String encodeWithinQuery(String unescaped, String charset)
424         throws URIException {
425 
426         return encode(unescaped, URI.allowed_within_query, charset);
427     }
428 
429 
430     /**
431      * Escape and encode a string regarded as the query component of an URI with
432      * the default protocol charset.
433      * When a query string is not misunderstood the reserved special characters
434      * ("&amp;", "=", "+", ",", and "$") within a query component, this method
435      * is recommended to use in encoding the whole query.
436      *
437      * @param unescaped an unescaped string
438      * @return the escaped string
439      * 
440      * @throws URIException if the default protocol charset is not supported
441      * 
442      * @see URI#getDefaultProtocolCharset
443      * @see #encode
444      */
445     public static String encodeQuery(String unescaped) throws URIException {
446         return encodeQuery(unescaped, URI.getDefaultProtocolCharset());
447     }
448 
449 
450     /**
451      * Escape and encode a string regarded as the query component of an URI with
452      * a given charset.
453      * When a query string is not misunderstood the reserved special characters
454      * ("&amp;", "=", "+", ",", and "$") within a query component, this method
455      * is recommended to use in encoding the whole query.
456      *
457      * @param unescaped an unescaped string
458      * @param charset the charset
459      * @return the escaped string
460      * 
461      * @throws URIException if the charset is not supported
462      * 
463      * @see #encode
464      */
465     public static String encodeQuery(String unescaped, String charset)
466         throws URIException {
467 
468         return encode(unescaped, URI.allowed_query, charset);
469     }
470 
471 
472     /**
473      * Escape and encode a given string with allowed characters not to be
474      * escaped and the default protocol charset.
475      *
476      * @param unescaped a string
477      * @param allowed allowed characters not to be escaped
478      * @return the escaped string
479      * 
480      * @throws URIException if the default protocol charset is not supported
481      * 
482      * @see URI#getDefaultProtocolCharset
483      */
484     public static String encode(String unescaped, BitSet allowed)
485         throws URIException {
486 
487         return encode(unescaped, allowed, URI.getDefaultProtocolCharset());
488     }
489 
490 
491     /**
492      * Escape and encode a given string with allowed characters not to be
493      * escaped and a given charset.
494      *
495      * @param unescaped a string
496      * @param allowed allowed characters not to be escaped
497      * @param charset the charset
498      * @return the escaped string
499      */
500     public static String encode(String unescaped, BitSet allowed,
501             String charset) throws URIException {
502         byte[] rawdata = URLCodec.encodeUrl(allowed, 
503             EncodingUtil.getBytes(unescaped, charset));
504         return EncodingUtil.getAsciiString(rawdata);
505     }
506 
507 
508     /**
509      * Unescape and decode a given string regarded as an escaped string with the
510      * default protocol charset.
511      *
512      * @param escaped a string
513      * @return the unescaped string
514      * 
515      * @throws URIException if the string cannot be decoded (invalid)
516      * 
517      * @see URI#getDefaultProtocolCharset
518      */
519     public static String decode(String escaped) throws URIException {
520         try {
521             byte[] rawdata = URLCodec.decodeUrl(EncodingUtil.getAsciiBytes(escaped));
522             return EncodingUtil.getString(rawdata, URI.getDefaultProtocolCharset());
523         } catch (DecoderException e) {
524             throw new URIException(e.getMessage());
525         }
526     }
527 
528     /**
529      * Unescape and decode a given string regarded as an escaped string.
530      *
531      * @param escaped a string
532      * @param charset the charset
533      * @return the unescaped string
534      * 
535      * @throws URIException if the charset is not supported
536      * 
537      * @see Coder#decode
538      */
539     public static String decode(String escaped, String charset)
540         throws URIException {
541 
542         return Coder.decode(escaped.toCharArray(), charset);
543     }
544 
545     // ---------------------------------------------------------- Inner classes
546 
547     /**
548      * The basic and internal utility for URI escape and character encoding and
549      * decoding.
550      * 
551      * @deprecated use org.apache.commons.codec.net.URLCodec
552      */
553     protected static class Coder extends URI {
554 
555         /**
556          * Escape and encode a given string with allowed characters not to be
557          * escaped.
558          *
559          * @param unescapedComponent an unescaped component
560          * @param allowed allowed characters not to be escaped
561          * @param charset the charset to encode
562          * @return the escaped and encoded string
563          * 
564          * @throws URIException if the charset is not supported
565          * 
566          * @deprecated use org.apache.commons.codec.net.URLCodec
567          */
568         public static char[] encode(String unescapedComponent, BitSet allowed, String charset) 
569             throws URIException {
570 
571             return URI.encode(unescapedComponent, allowed, charset);
572         }
573 
574 
575         /**
576          * Unescape and decode a given string.
577          *
578          * @param escapedComponent an being-unescaped component
579          * @param charset the charset to decode
580          * @return the escaped and encoded string
581          * 
582          * @throws URIException if the charset is not supported
583          * 
584          * @deprecated use org.apache.commons.codec.net.URLCodec
585          */
586         public static String decode(char[] escapedComponent, String charset)
587             throws URIException {
588 
589             return URI.decode(escapedComponent, charset);
590         }
591 
592 
593         /**
594          * Verify whether a given string is escaped or not
595          *
596          * @param original given characters
597          * @return true if the given character array is 7 bit ASCII-compatible.
598          */
599         public static boolean verifyEscaped(char[] original) {
600             for (int i = 0; i < original.length; i++) {
601                 int c = original[i];
602                 if (c > 128) {
603                     return false;
604                 } else if (c == '%') {
605                     if (Character.digit(original[++i], 16) == -1 
606                         || Character.digit(original[++i], 16) == -1) {
607                         return false;
608                     }
609                 }
610             }
611             return true;
612         }
613 
614 
615         /**
616          * Replace from a given character to given character in an array order
617          * for a given string.
618          *
619          * @param original a given string
620          * @param from a replacing character array
621          * @param to a replaced character array
622          * @return the replaced string
623          */
624         public static String replace(String original, char[] from, char[] to) {
625             for (int i = from.length; i > 0; --i) {
626                 original = replace(original, from[i], to[i]);
627             }
628             return original;
629         }
630 
631 
632         /**
633          * Replace from a given character to given character for a given string.
634          *
635          * @param original a given string
636          * @param from a replacing character array
637          * @param to a replaced character array
638          * @return the replaced string
639          */
640         public static String replace(String original, char from, char to) {
641             StringBuffer result = new StringBuffer(original.length());
642             int at, saved = 0;
643             do {
644                 at = original.indexOf(from);
645                 if (at >= 0) {
646                     result.append(original.substring(0, at));
647                     result.append(to);
648                 } else {
649                     result.append(original.substring(saved));
650                 }
651                 saved = at;
652             } while (at >= 0);
653             return result.toString();
654         }
655     }
656 
657 }
658 

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/package-frame.html100644 0 0 4327 10661532632 26430 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.util

org.apache.commons.httpclient.util

Classes

commons-httpclient-3.1/docs/xref/org/apache/commons/httpclient/util/package-summary.html100644 0 0 7745 10661532632 27042 0ustar 0 0 HttpClient 3.1 Reference Package org.apache.commons.httpclient.util

Package org.apache.commons.httpclient.util

Class Summary
DateParseException
DateParser
DateUtil
EncodingUtil
ExceptionUtil
HttpURLConnection
IdleConnectionHandler
IdleConnectionTimeoutThread
LangUtils
ParameterFormatter
ParameterParser
TimeoutController
URIUtil

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref/overview-frame.html100644 0 0 3300 10661532627 20057 0ustar 0 0 HttpClient 3.1 Reference

All Classes

Packages

commons-httpclient-3.1/docs/xref/overview-summary.html100644 0 0 6122 10661532632 20463 0ustar 0 0 HttpClient 3.1 Reference
  • Overview
  • Package

HttpClient 3.1 Reference

Packages
org.apache.commons.httpclient
org.apache.commons.httpclient.auth
org.apache.commons.httpclient.cookie
org.apache.commons.httpclient.methods
org.apache.commons.httpclient.methods.multipart
org.apache.commons.httpclient.params
org.apache.commons.httpclient.protocol
org.apache.commons.httpclient.util
  • Overview
  • Package

Copyright © 2001-2007 Apache Software Foundation. All Rights Reserved. commons-httpclient-3.1/docs/xref/stylesheet.css100644 0 0 2435 10661532632 17142 0ustar 0 0 /* Javadoc style sheet */ /* Define colors, fonts and other style attributes here to override the defaults */ body { background-color: #fff; font-family: Arial, Helvetica, sans-serif; } a:link { color: #00f; } a:visited { color: #00a; } a:active, a:hover { color: #f30 !important; } ul, li { list-style-type:none ; margin:0; padding:0; } table td{ padding: 3px; border: 1px solid #000; } table{ width:100%; border: 1px solid #000; border-collapse: collapse; } div.overview { background-color:#ddd; padding: 4px 4px 4px 0; } div.overview li, div.framenoframe li { display: inline; } div.framenoframe { text-align: center; font-size: x-small; } div.framenoframe li { margin: 0 3px 0 3px; } div.overview li { margin:3px 3px 0 3px; padding: 4px; } li.selected { background-color:#888; color: #fff; font-weight: bold; } table.summary { margin-bottom: 20px; } table.summary td, table.summary th { font-weight: bold; text-align: left; padding: 3px; } table.summary th{ background-color:#036; color: #fff; } table.summary td{ background-color:#eee; border: 1px solid black; } em { color: #A00; } em.comment { color: #390; } .string { color: #009; } div#footer { text-align:center; } #overview { padding:2px; } hr { height: 1px; color: #000; } commons-httpclient-3.1/maven.xml100644 0 0 6346 10661532626 14203 0ustar 0 0 [HttpClient] dist:prepare-bin-filesystem postGoal [HttpClient] dist:prepare-src-filesystem postGoal commons-httpclient-3.1/project.properties100644 0 0 2150 10661532626 16124 0ustar 0 0 # Maven specific project properties maven.repo.remote=http://repo1.maven.org/maven maven.compile.source=1.2 maven.compile.target=1.2 maven.compile.debug=true maven.xdoc.date=left maven.xdoc.version=${pom.currentVersion} maven.checkstyle.properties=checkstyle.xml.properties maven.checkstyle.includes=**/*.java maven.checkstyle.excludes=**/*.html maven.javadoc.links=http://java.sun.com/j2se/1.4.2/docs/api/, http://commons.apache.org/logging/commons-logging-1.0.4/docs/apidocs/ maven.changelog.factory=org.apache.maven.svnlib.SvnChangeLogFactory maven.repo.list=asf maven.repo.asf=scp://people.apache.org maven.repo.asf.directory=/www/www.apache.org/dist/java-repository maven.repo.asf.username=${maven.username} maven.repo.asf.compress=true maven.repo.asf.group=jakarta # Jar Manifest Additional Attributes maven.jar.manifest.attributes.list=Implementation-Vendor-Id,X-Compile-Source-JDK,X-Compile-Target-JDK maven.jar.manifest.attribute.Implementation-Vendor-Id=org.apache maven.jar.manifest.attribute.X-Compile-Source-JDK=${maven.compile.source} maven.jar.manifest.attribute.X-Compile-Target-JDK=${maven.compile.target} commons-httpclient-3.1/project.xml100644 0 0 25547 10661532626 14567 0ustar 0 0 3 HttpClient commons-httpclient commons-httpclient jakarta-commons-httpclient 2001 3.1 org.apache.commons.httpclient Apache Software Foundation http://jakarta.apache.org/ http://jakarta.apache.org/images/jakarta-logo.gif Jakarta Commons HttpClient The HttpClient component supports the client-side of RFC 1945 (HTTP/1.0) and RFC 2616 (HTTP/1.1) , several related specifications (RFC 2109 (Cookies) , RFC 2617 (HTTP Authentication) , etc.), and provides a framework by which new request types (methods) or HTTP extensions can be created easily. /images/httpclient_logo.png http://jakarta.apache.org/httpcomponents/httpclient-3.x/ http://issues.apache.org/jira/browse/HTTPCLIENT people.apache.org /www/jakarta.apache.org/httpcomponents/httpclient-3.x/ scm:svn:http://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/trunk http://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/trunk 3.1 3.1 HTTPCLIENT_3_1 3.1-rc1 3.1-rc1 HTTPCLIENT_3_1_RC1 3.1-beta1 3.1-beta1 HTTPCLIENT_3_1_BETA1 3.1-alpha1 3.1-alpha1 HTTPCLIENT_3_1_ALPHA1 3.0.1 3.0.1 HTTPCLIENT_3_0_1 3.0 3.0 HTTPCLIENT_3_0 3.0-rc4 3.0-rc4 HTTPCLIENT_3_0_RC4 3.0-rc3 3.0-rc3 HTTPCLIENT_3_0_RC3 3.0-rc2 3.0-rc2 HTTPCLIENT_3_0_RC2 3.0-rc1 3.0-rc1 HTTPCLIENT_3_0_RC1 3.0-beta1 3.0-beta1 HTTPCLIENT_3_0_BETA1 3.0-alpha2 3.0-alpha2 HTTPCLIENT_3_0_ALPHA2 3.0-alpha1 3.0-alpha1 HTTPCLIENT_3_0_ALPHA1 2.0 2.0 HTTPCLIENT_2_0_FINAL rc3 2.0-rc3 HTTPCLIENT_2_0_RC3 rc2 2.0-rc2 HTTPCLIENT_2_0_RC2 rc1 2.0-rc1 HTTPCLIENT_2_0_RC1 b2 2.0-beta2 HTTPCLIENT_2_0_BETA2 b1 2.0-beta1 HTTPCLIENT_2_0_BETA1 a3 2.0-alpha3 HTTPCLIENT_2_0_ALPHA3 a2 2.0-alpha2 HTTPCLIENT_2_0_ALPHA2 a1 2.0-alpha1 HTTPCLIENT_2_0_ALPHA1 HTTPCLIENT_2_0_BRANCH HTTPCLIENT_3_0_BRANCH HttpComponents Developer List httpcomponents-dev-subscribe@jakarta.apache.org httpcomponents-dev-unsubscribe@jakarta.apache.org http://mail-archives.apache.org/mod_mbox/jakarta-httpcomponents-dev/ HttpClient User List httpclient-user-subscribe@jakarta.apache.org httpclient-user-unsubscribe@jakarta.apache.org http://mail-archives.apache.org/mod_mbox/jakarta-httpclient-user/ Michael Becke mbecke mbecke -at- apache.org Release Prime Java Developer Jeff Dever jsdever jsdever -at- apache.org Independent consultant 2.0 Release Prime Java Developer dIon Gillard dion dion -at- apache.org Multitask Consulting Java Developer Ortwin Glueck oglueck oglueck -at- apache.org Java Developer http://www.odi.ch/ Sung-Gu jericho jericho -at- apache.org Java Developer Oleg Kalnichevski olegk olegk -at- apache.org Java Developer Sean C. Sullivan sullis sullis -at- apache.org Independent consultant Java Developer Adrian Sutton adrian adrian.sutton -at- ephox.com Intencha Java Developer Rodney Waldhoff rwaldhoff rwaldhoff -at- apache Britannica Java Developer Armando Anton armando.anton -at- newknow.com Sebastian Bazley sebb -at- apache.org Ola Berg Sam Berlin sberlin -at- limepeer.com Mike Bowler Samit Jain jain.samit -at- gmail.com Eric Johnson eric -at- tibco.com Christian Kohlschuetter ck -at- newsclub.de Ryan Lubke Ryan.Lubke -at- Sun.COM Sam Maloney sam.maloney -at- filogix.com Rob Di Marco rdimarco -at- hmsonline.com Juergen Pill Juergen.Pill -at- softwareag.com Mohammad Rezaei mohammad.rezaei -at- gs.com Roland Weber rolandw -at- apache.org Laura Werner laura -at- lwerner.org Mikael Wilstrom mikael.wikstrom -at- it.su.se Apache License http://www.apache.org/licenses/LICENSE-2.0 repo junit junit 3.8.1 http://www.junit.org/ test commons-logging commons-logging 1.0.4 http://commons.apache.org/logging/ commons-codec commons-codec 1.2 http://commons.apache.org/codec/ httpcomponents-dev@jakarta.apache.org src/java src/test src/resources **/TestAll.java src/test **/*.keystore maven-changelog-plugin maven-changes-plugin maven-developer-activity-plugin maven-file-activity-plugin maven-javadoc-plugin maven-jdepend-plugin maven-junit-report-plugin maven-jxr-plugin maven-license-plugin maven-tasklist-plugin commons-httpclient-3.1/src/conf/MANIFEST.MF100644 0 0 270 10661532626 15467 0ustar 0 0 Extension-Name: @name@ Specification-Vendor: Apache Software Foundation Specification-Version: 1.0 Implementation-Vendor: Apache Software Foundation Implementation-Version: @version@ commons-httpclient-3.1/src/conf/log4j.properties.sample100644 0 0 1552 10661532626 20476 0ustar 0 0 ################################################### # Sample configuraion for the log4j logging system ################################################### # Set the root output level and appenders log4j.rootCategory=INFO, consoleAppender #log4j.category.org.apache.commons.httpclient.Base64=DEBUG #log4j.category.org.apache.commons.httpclient.HeaderElement=DEBUG #log4j.category.org.apache.commons.httpclient.HttpClient=DEBUG # the httpclient.wire category provides a trace of all of # httpclient's network communictation #log4j.category.httpclient.wire=INFO # Create an appender that prints to the console log4j.appender.consoleAppender=org.apache.log4j.FileAppender log4j.appender.consoleAppender.File=System.out log4j.appender.consoleAppender.layout=org.apache.log4j.PatternLayout log4j.appender.consoleAppender.layout.ConversionPattern=%-5p [%t] %c - %m: %d{DATE}\n commons-httpclient-3.1/src/conf/simplelog.properties.sample100644 0 0 2573 10661532627 21457 0ustar 0 0 #################################################### # Sample configuraion for the simple logging system #################################################### # httpclient.simplelog.defaultlog # - Default log level for all SimpleLogs. httpclient.simplelog.defaultlog=FATAL # httpclient.simplelog.showlogname # - When true, show the name of the log in log output. httpclient.simplelog.showlogname=false # httpclient.simplelog.showdate # - When true, show a timestamp the log in log output. httpclient.simplelog.showdate=true # httpclient.simplelog.dateformat # - A SimpleDateFormat format string for timestamps in the log output httpclient.simplelog.dateformat=yyyy/MM/dd HH:mm:ss:SSS zzz # httpclient.simplelog.log.* # - Sets the logging level for specific logs. # Note that if that if you set the log level # for a log named "a.b", it will apply to all # logs with names of the form "a.b.c[.d]*" # unless overriden by a more specific log setting. #httpclient.simplelog.log.org.apache.commons.httpclient=DEBUG #httpclient.simplelog.log.org.apache.commons.httpclient.HttpClient=DEBUG #httpclient.simplelog.log.org.apache.commons.httpclient.HeaderElement=DEBUG #httpclient.simplelog.log.org.apache.commons.httpclient.Base64=DEBUG # the httpclient.wire category provides a trace of all of # httpclient's network communictation #httpclient.simplelog.log.httpclient.wire=INFO ././@LongLink100644 0 0 170 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/auth/CustomAuthenticationNegotiateExample.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/auth/CustomAuthenticationNe100644 0 0 10606 10661532626 31436 0ustar 0 0 /* * $Header: $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.auth; import java.util.ArrayList; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.auth.AuthPolicy; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.DefaultHttpParams; import org.apache.commons.httpclient.params.HttpParams; /** * A simple custom AuthScheme example. The included auth scheme is meant * for demonstration purposes only. It does not actually implement a usable * authentication method. * *
 Login Configuration file bcsLogin.conf for JAAS.
 -----------------------------------------------
   com.sun.security.jgss.initiate {
     com.sun.security.auth.module.Krb5LoginModule 
         required 
         client=TRUE 
         useTicketCache="true" 
         ticketCache="${user.krb5cc}" 
         debug=true;
   };

   com.sun.security.jgss.accept {
     com.sun.security.auth.module.Krb5LoginModule 
         required 
         client=TRUE 
         useTicketCache="true" 
         ticketCache="${user.krb5cc}" 
         debug=true;
   };
 -----------------------------------------------
 
   java  -Djava.security.krb5.realm=REALM \
      -Djava.security.krb5.kdc=kdc.domain \
      -Djavax.security.auth.useSubjectCredsOnly=false \
      -Djava.security.auth.login.config=src/conf/bcsLogin.conf \
      -Duser.krb5cc="$KRB5CCNAME" \
      -classpath $CP \
      CustomAuthenticationNegotiateExample "http://localhost/gsstest/"
   
*/ public class CustomAuthenticationNegotiateExample { public static void main(String[] args) { // register the auth scheme AuthPolicy.registerAuthScheme("Negotiate", NegotiateScheme.class); // include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference ArrayList schemes = new ArrayList(); schemes.add("Negotiate"); HttpParams params = DefaultHttpParams.getDefaultParams(); params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes); // now that our scheme has been registered we can execute methods against // servers that require "Negotiate" authentication... HttpClient client = new HttpClient(); // The Negotiate scheme uses JAAS as credential provider but the // httpclient api require us to supply cred anyway. // a work around is to provide an empty set of creds. Credentials use_jaas_creds = new Credentials() {}; client.getState().setCredentials( new AuthScope(null, -1, null), use_jaas_creds); GetMethod httpget = new GetMethod(args[0]); try { client.executeMethod(httpget); //System.out.println(httpget.getStatusLine()); //System.out.println(httpget.getResponseBodyAsString()); } catch (Exception e) { e.printStackTrace(); } finally { // release any connection resources used by the method httpget.releaseConnection(); } } } commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/auth/NegotiateScheme.java100644 0 0 24503 10661532626 30766 0ustar 0 0 /* * $Header:$ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.auth; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.auth.AuthChallengeException; import org.apache.commons.httpclient.auth.AuthScheme; import org.apache.commons.httpclient.auth.AuthenticationException; import org.apache.commons.httpclient.auth.CredentialsNotAvailableException; import org.apache.commons.httpclient.auth.InvalidCredentialsException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSName; import org.ietf.jgss.Oid; /** * * @author Mikael Wilstrom * @author Mikael Wikstrom */ public class NegotiateScheme implements AuthScheme { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(NegotiateScheme.class); /** challenge string. */ private String challenge = null; private static final int UNINITIATED = 0; private static final int INITIATED = 1; private static final int NEGOTIATING = 3; private static final int ESTABLISHED = 4; private static final int FAILED = Integer.MAX_VALUE; private GSSContext context = null; /** Authentication process state */ private int state; /** base64 decoded challenge **/ byte[] token = new byte[0]; /** * Init GSSContext for negotiation. * * @param server servername only (e.g: radar.it.su.se) */ protected void init(String server) throws GSSException { LOG.debug("init " + server); /* Kerberos v5 GSS-API mechanism defined in RFC 1964. */ Oid krb5Oid = new Oid("1.2.840.113554.1.2.2"); GSSManager manager = GSSManager.getInstance(); GSSName serverName = manager.createName("HTTP/"+server, null); context = manager.createContext(serverName, krb5Oid, null, GSSContext.DEFAULT_LIFETIME); context.requestMutualAuth(true); context.requestCredDeleg(true); state = INITIATED; } /** * Default constructor for the Negotiate authentication scheme. * * @since 3.0 */ public NegotiateScheme() { super(); state = UNINITIATED; } /** * Constructor for the Negotiate authentication scheme. * * @param challenge The authentication challenge */ public NegotiateScheme(final String challenge) { super(); LOG.debug("enter NegotiateScheme("+challenge+")"); processChallenge(challenge); } /** * Processes the Negotiate challenge. * * @param challenge the challenge string * * @since 3.0 */ public void processChallenge(final String challenge){ LOG.debug("enter processChallenge(challenge=\""+challenge+"\")"); if (challenge.startsWith("Negotiate")) { if(isComplete() == false) state = NEGOTIATING; if (challenge.startsWith("Negotiate ")) token = new Base64().decode(challenge.substring(10).getBytes()); else token = new byte[0]; } } /** * Tests if the Negotiate authentication process has been completed. * * @return true if authorization has been processed, * false otherwise. * * @since 3.0 */ public boolean isComplete() { LOG.debug("enter isComplete()"); return this.state == ESTABLISHED || this.state == FAILED; } /** * Returns textual designation of the Negotiate authentication scheme. * * @return Negotiate */ public String getSchemeName() { return "Negotiate"; } /** * The concept of an authentication realm is not supported by the Negotiate * authentication scheme. Always returns null. * * @return null */ public String getRealm() { return null; } /** * Returns a String identifying the authentication challenge. This is * used, in combination with the host and port to determine if * authorization has already been attempted or not. Schemes which * require multiple requests to complete the authentication should * return a different value for each stage in the request. * *

Additionally, the ID should take into account any changes to the * authentication challenge and return a different value when appropriate. * For example when the realm changes in basic authentication it should be * considered a different authentication attempt and a different value should * be returned.

* * @return String a String identifying the authentication challenge. The * returned value may be null. * * @deprecated no longer used */ public String getID() { LOG.debug("enter getID(): " + challenge); return challenge; } /** * Returns the authentication parameter with the given name, if available. * *

There are no valid parameters for Negotiate authentication so this * method always returns null.

* * @param name The name of the parameter to be returned * * @return the parameter with the given name */ public String getParameter(String name) { LOG.debug("enter getParameter("+name+")"); if (name == null) { throw new IllegalArgumentException("Parameter name may not be null"); } return null; } /** * Returns true. * Negotiate authentication scheme is connection based. * * @return true. * * @since 3.0 */ public boolean isConnectionBased() { LOG.info("enter isConnectionBased()"); return true; } /** * Method not supported by Negotiate scheme. * * @throws AuthenticationException if called. * * @deprecated Use {@link #authenticate(Credentials, HttpMethod)} */ public String authenticate(Credentials credentials, String method, String uri) throws AuthenticationException { throw new AuthenticationException("method not supported by Negotiate scheme"); } /** * Produces Negotiate authorization string based on token created by * processChallenge. * * @param credentials Never used be the Negotiate scheme but must be provided to * satisfy common-httpclient API. Credentials from JAAS will be used insted. * @param method The method being authenticated * * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return an Negotiate authorization string * * @since 3.0 */ public String authenticate( Credentials credentials, HttpMethod method ) throws AuthenticationException { LOG.debug("enter NegotiateScheme.authenticate(Credentials, HttpMethod)"); if (state == UNINITIATED) { throw new IllegalStateException( "Negotiation authentication process has not been initiated"); } try { try { if(context==null) { LOG.info("host: " + method.getURI().getHost()); init( method.getURI().getHost() ); } } catch (org.apache.commons.httpclient.URIException urie) { LOG.error(urie.getMessage()); state = FAILED; throw new AuthenticationException(urie.getMessage()); } // HTTP 1.1 issue: // Mutual auth will never complete do to 200 insted of 401 in // return from server. "state" will never reach ESTABLISHED // but it works anyway token = context.initSecContext(token, 0, token.length); LOG.info("got token, sending " + token.length + " to server"); } catch (GSSException gsse) { LOG.fatal(gsse.getMessage()); state = FAILED; if( gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED ) throw new InvalidCredentialsException(gsse.getMessage(),gsse); if( gsse.getMajor() == GSSException.NO_CRED ) throw new CredentialsNotAvailableException(gsse.getMessage(),gsse); if( gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN ) throw new AuthChallengeException(gsse.getMessage(),gsse); // other error throw new AuthenticationException(gsse.getMessage()); } return "Negotiate " + new String(new Base64().encode(token)); } } ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/benchmark/BenchmarkWorker.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/benchmark/BenchmarkWorker.j100644 0 0 11416 10661532626 31306 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/contrib/org/apache/commons/httpclient/contrib/benchmark/BenchmarkWorker.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.benchmark; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; /** *

Benchmark worker that can execute an HTTP method given number of times

* * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class BenchmarkWorker { private byte[] buffer = new byte[4096]; private final int verbosity; private final HttpClient httpexecutor; public BenchmarkWorker(final HttpClient httpexecutor, int verbosity) { super(); this.httpexecutor = httpexecutor; this.verbosity = verbosity; } public Stats execute( final HostConfiguration hostconf, final HttpMethod method, int count, boolean keepalive) throws HttpException { Stats stats = new Stats(); stats.start(); for (int i = 0; i < count; i++) { try { this.httpexecutor.executeMethod(hostconf, method); if (this.verbosity >= 4) { System.out.println(">> " + method.getName() + " " + method.getURI() + " " + method.getParams().getVersion()); Header[] headers = method.getRequestHeaders(); for (int h = 0; h < headers.length; h++) { System.out.print(">> " + headers[h].toString()); } System.out.println(); } if (this.verbosity >= 3) { System.out.println(method.getStatusLine().getStatusCode()); } if (this.verbosity >= 4) { System.out.println("<< " + method.getStatusLine().toString()); Header[] headers = method.getResponseHeaders(); for (int h = 0; h < headers.length; h++) { System.out.print("<< " + headers[h].toString()); } System.out.println(); } InputStream instream = method.getResponseBodyAsStream(); long contentlen = 0; if (instream != null) { int l = 0; while ((l = instream.read(this.buffer)) != -1) { stats.incTotal(l); contentlen += l; } } stats.setContentLength(contentlen); stats.incSuccessCount(); } catch (IOException ex) { stats.incFailureCount(); if (this.verbosity >= 2) { System.err.println("I/O error: " + ex.getMessage()); } } finally { method.releaseConnection(); } if (!keepalive) { this.httpexecutor.getHttpConnectionManager().closeIdleConnections(0); } } stats.finish(); Header header = method.getResponseHeader("Server"); if (header != null) { stats.setServerName(header.getValue()); } return stats; } } ././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/benchmark/HttpBenchmark.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/benchmark/HttpBenchmark.jav100644 0 0 23150 10661532626 31301 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/contrib/org/apache/commons/httpclient/contrib/benchmark/HttpBenchmark.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.benchmark; import java.io.File; import java.net.URL; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.methods.FileRequestEntity; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; /** *

A simple HTTP benchmark tool, which implements a subset of AB (Apache Benchmark) interface

* * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class HttpBenchmark { private static HttpClient createRequestExecutor() { HttpClient httpclient = new HttpClient(); httpclient.getParams().setVersion(HttpVersion.HTTP_1_1); httpclient.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); httpclient.getHttpConnectionManager().getParams().setStaleCheckingEnabled(false); return httpclient; } public static void main(String[] args) throws Exception { Option iopt = new Option("i", false, "Do HEAD requests instead of GET."); iopt.setRequired(false); 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); 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"); Option popt = new Option("p", true, "File containing data to POST."); popt.setRequired(false); popt.setArgName("POST-file"); Option Topt = new Option("T", true, "Content-type header to use for POST data."); Topt.setRequired(false); Topt.setArgName("content-type"); Option vopt = new Option("v", true, "Set verbosity level - 4 and above prints " + "information on headers, 3 and above prints response codes (404, 200, " + "etc.), 2 and above prints warnings and info."); vopt.setRequired(false); vopt.setArgName("verbosity"); Option hopt = new Option("h", false, "Display usage information."); nopt.setRequired(false); Options options = new Options(); options.addOption(iopt); options.addOption(kopt); options.addOption(nopt); options.addOption(popt); options.addOption(Topt); options.addOption(vopt); options.addOption(hopt); if (args.length == 0) { showUsage(options); System.exit(1); } CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { showUsage(options); System.exit(1); } int verbosity = 0; if(cmd.hasOption('v')) { String s = cmd.getOptionValue('v'); try { verbosity = Integer.parseInt(s); } catch (NumberFormatException ex) { System.err.println("Invalid verbosity level: " + s); showUsage(options); System.exit(-1); } } boolean keepAlive = false; if(cmd.hasOption('k')) { keepAlive = true; } int num = 1; if(cmd.hasOption('n')) { String s = cmd.getOptionValue('n'); try { num = Integer.parseInt(s); } catch (NumberFormatException ex) { System.err.println("Invalid number of requests: " + s); showUsage(options); System.exit(-1); } } args = cmd.getArgs(); if (args.length != 1) { showUsage(options); System.exit(-1); } // Parse the target url URL url = new URL(args[0]); // Prepare host configuration HostConfiguration hostconf = new HostConfiguration(); hostconf.setHost( url.getHost(), url.getPort(), url.getProtocol()); // Prepare request HttpMethod method = null; if (cmd.hasOption('p')) { PostMethod httppost = new PostMethod(url.getPath()); File file = new File(cmd.getOptionValue('p')); if (!file.exists()) { System.err.println("File not found: " + file); System.exit(-1); } String contenttype = null; if (cmd.hasOption('T')) { contenttype = cmd.getOptionValue('T'); } FileRequestEntity entity = new FileRequestEntity(file, contenttype); httppost.setRequestEntity(entity); if (file.length() > 100000) { httppost.setContentChunked(true); } method = httppost; } else if (cmd.hasOption('i')) { HeadMethod httphead = new HeadMethod(url.getPath()); method = httphead; } else { GetMethod httpget = new GetMethod(url.getPath()); method = httpget; } if (!keepAlive) { method.addRequestHeader("Connection", "close"); } // Prepare request executor HttpClient executor = createRequestExecutor(); BenchmarkWorker worker = new BenchmarkWorker(executor, verbosity); // Execute Stats stats = worker.execute(hostconf, method, num, keepAlive); // Show the results float totalTimeSec = (float)stats.getDuration() / 1000; float reqsPerSec = (float)stats.getSuccessCount() / totalTimeSec; float timePerReqMs = (float)stats.getDuration() / (float)stats.getSuccessCount(); System.out.print("Server Software:\t"); System.out.println(stats.getServerName()); System.out.print("Server Hostname:\t"); System.out.println(hostconf.getHost()); System.out.print("Server Port:\t\t"); if (hostconf.getPort() > 0) { System.out.println(hostconf.getPort()); } else { System.out.println(hostconf.getProtocol().getDefaultPort()); } System.out.println(); System.out.print("Document Path:\t\t"); System.out.println(method.getURI()); System.out.print("Document Length:\t"); System.out.print(stats.getContentLength()); System.out.println(" bytes"); System.out.println(); System.out.print("Time taken for tests:\t"); System.out.print(totalTimeSec); System.out.println(" seconds"); System.out.print("Complete requests:\t"); System.out.println(stats.getSuccessCount()); System.out.print("Failed requests:\t"); System.out.println(stats.getFailureCount()); System.out.print("Content transferred:\t"); System.out.print(stats.getTotal()); System.out.println(" bytes"); System.out.print("Requests per second:\t"); System.out.print(reqsPerSec); System.out.println(" [#/sec] (mean)"); System.out.print("Time per request:\t"); System.out.print(timePerReqMs); System.out.println(" [ms] (mean)"); } private static void showUsage(final Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("HttpBenchmark [options] [http://]hostname[:port]/path", options); } } commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/benchmark/Stats.java100644 0 0 6334 10661532626 27773 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/contrib/org/apache/commons/httpclient/contrib/benchmark/Stats.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.benchmark; /** *

Benchmark statistics

* * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class Stats { private long startTime = -1; private long finishTime = -1; private int successCount = 0; private int failureCount = 0; private String serverName = null; private long total = 0; private long contentLength = -1; public Stats() { super(); } public void start() { this.startTime = System.currentTimeMillis(); } public void finish() { this.finishTime = System.currentTimeMillis(); } public long getFinishTime() { return this.finishTime; } public long getStartTime() { return this.startTime; } public long getDuration() { if (this.startTime < 0 || this.finishTime < 0) { throw new IllegalStateException(); } return this.finishTime - this.startTime; } public void incSuccessCount() { this.successCount++; } public void incFailureCount() { this.failureCount++; } public int getFailureCount() { return this.failureCount; } public int getSuccessCount() { return this.successCount; } public long getTotal() { return this.total; } public void incTotal(int n) { this.total += n; } public long getContentLength() { return this.contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public String getServerName() { return this.serverName; } public void setServerName(final String serverName) { this.serverName = serverName; } } ././@LongLink100644 0 0 154 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/methods/multipart/ContentType.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/methods/multipart/ContentTy100644 0 0 22343 10661532626 31454 0ustar 0 0 /* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.contrib.methods.multipart; import java.io.File; /** * This class provides mappings from file name extensions to content types. * * @author Eric Devlin * @author Adrian Sutton * * @version $Revision: 480424 $ * * DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * to be used without additional customization. */ public final class ContentType { /** Mime Type mappings 'liberated' from Tomcat4.1.18/conf/web.xml*/ public static final String[][] MIME_TYPE_MAPPINGS = { { "abs", "audio/x-mpeg" }, { "ai", "application/postscript" }, { "aif", "audio/x-aiff" }, { "aifc", "audio/x-aiff" }, { "aiff", "audio/x-aiff" }, { "aim", "application/x-aim" }, { "art", "image/x-jg" }, { "asf", "video/x-ms-asf" }, { "asx", "video/x-ms-asf" }, { "au", "audio/basic" }, { "avi", "video/x-msvideo" }, { "avx", "video/x-rad-screenplay" }, { "bcpio", "application/x-bcpio" }, { "bin", "application/octet-stream" }, { "bmp", "image/bmp" }, { "body", "text/html" }, { "cdf", "application/x-cdf" }, { "cer", "application/x-x509-ca-cert" }, { "class", "application/java" }, { "cpio", "application/x-cpio" }, { "csh", "application/x-csh" }, { "css", "text/css" }, { "dib", "image/bmp" }, { "doc", "application/msword" }, { "dtd", "text/plain" }, { "dv", "video/x-dv" }, { "dvi", "application/x-dvi" }, { "eps", "application/postscript" }, { "etx", "text/x-setext" }, { "exe", "application/octet-stream" }, { "gif", "image/gif" }, { "gtar", "application/x-gtar" }, { "gz", "application/x-gzip" }, { "hdf", "application/x-hdf" }, { "hqx", "application/mac-binhex40" }, { "htc", "text/x-component" }, { "htm", "text/html" }, { "html", "text/html" }, { "hqx", "application/mac-binhex40" }, { "ief", "image/ief" }, { "jad", "text/vnd.sun.j2me.app-descriptor" }, { "jar", "application/java-archive" }, { "java", "text/plain" }, { "jnlp", "application/x-java-jnlp-file" }, { "jpe", "image/jpeg" }, { "jpeg", "image/jpeg" }, { "jpg", "image/jpeg" }, { "js", "text/javascript" }, { "jsf", "text/plain" }, { "jspf", "text/plain" }, { "kar", "audio/x-midi" }, { "latex", "application/x-latex" }, { "m3u", "audio/x-mpegurl" }, { "mac", "image/x-macpaint" }, { "man", "application/x-troff-man" }, { "me", "application/x-troff-me" }, { "mid", "audio/x-midi" }, { "midi", "audio/x-midi" }, { "mif", "application/x-mif" }, { "mov", "video/quicktime" }, { "movie", "video/x-sgi-movie" }, { "mp1", "audio/x-mpeg" }, { "mp2", "audio/x-mpeg" }, { "mp3", "audio/x-mpeg" }, { "mpa", "audio/x-mpeg" }, { "mpe", "video/mpeg" }, { "mpeg", "video/mpeg" }, { "mpega", "audio/x-mpeg" }, { "mpg", "video/mpeg" }, { "mpv2", "video/mpeg2" }, { "ms", "application/x-wais-source" }, { "nc", "application/x-netcdf" }, { "oda", "application/oda" }, { "pbm", "image/x-portable-bitmap" }, { "pct", "image/pict" }, { "pdf", "application/pdf" }, { "pgm", "image/x-portable-graymap" }, { "pic", "image/pict" }, { "pict", "image/pict" }, { "pls", "audio/x-scpls" }, { "png", "image/png" }, { "pnm", "image/x-portable-anymap" }, { "pnt", "image/x-macpaint" }, { "ppm", "image/x-portable-pixmap" }, { "ps", "application/postscript" }, { "psd", "image/x-photoshop" }, { "qt", "video/quicktime" }, { "qti", "image/x-quicktime" }, { "qtif", "image/x-quicktime" }, { "ras", "image/x-cmu-raster" }, { "rgb", "image/x-rgb" }, { "rm", "application/vnd.rn-realmedia" }, { "roff", "application/x-troff" }, { "rtf", "application/rtf" }, { "rtx", "text/richtext" }, { "sh", "application/x-sh" }, { "shar", "application/x-shar" }, { "smf", "audio/x-midi" }, { "snd", "audio/basic" }, { "src", "application/x-wais-source" }, { "sv4cpio", "application/x-sv4cpio" }, { "sv4crc", "application/x-sv4crc" }, { "swf", "application/x-shockwave-flash" }, { "t", "application/x-troff" }, { "tar", "application/x-tar" }, { "tcl", "application/x-tcl" }, { "tex", "application/x-tex" }, { "texi", "application/x-texinfo" }, { "texinfo", "application/x-texinfo" }, { "tif", "image/tiff" }, { "tiff", "image/tiff" }, { "tr", "application/x-troff" }, { "tsv", "text/tab-separated-values" }, { "txt", "text/plain" }, { "ulw", "audio/basic" }, { "ustar", "application/x-ustar" }, { "xbm", "image/x-xbitmap" }, { "xml", "text/xml" }, { "xpm", "image/x-xpixmap" }, { "xsl", "text/xml" }, { "xwd", "image/x-xwindowdump" }, { "wav", "audio/x-wav" }, { "svg", "image/svg+xml" }, { "svgz", "image/svg+xml" }, { "wbmp", "image/vnd.wap.wbmp" }, { "wml", "text/vnd.wap.wml" }, { "wmlc", "application/vnd.wap.wmlc" }, { "wmls", "text/vnd.wap.wmlscript" }, { "wmlscriptc", "application/vnd.wap.wmlscriptc" }, { "wrl", "x-world/x-vrml" }, { "Z", "application/x-compress" }, { "z", "application/x-compress" }, { "zip", "application/zip" } }; /** The constructor is intentionally private as the class only provides static methods. */ private ContentType() { } /** * Get the content type based on the extension of the file name<br> * * @param fileName for which the content type is to be determined. * * @return the content type for the file or null if no mapping was * possible. */ public static String get(String fileName) { String contentType = null; if (fileName != null) { int extensionIndex = fileName.lastIndexOf('.'); if (extensionIndex != -1) { if (extensionIndex + 1 < fileName.length()) { String extension = fileName.substring(extensionIndex + 1); for (int i = 0; i < MIME_TYPE_MAPPINGS.length; i++) { if (extension.equals(MIME_TYPE_MAPPINGS[i][0])) { contentType = MIME_TYPE_MAPPINGS[i][1]; break; } } } } } return contentType; } /** * Get the content type based on the extension of the file name<br> * * @param file for which the content type is to be determined. * * @return the content type for the file or null if no mapping was * possible. * * @throws IOException if the construction of the canonical path for * the file fails. */ public static String get(File file) { String contentType = null; if (file != null) { contentType = get(file.getName()); } return contentType; } } ././@LongLink100644 0 0 164 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/methods/multipart/ContentTypeFilePart.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/methods/multipart/ContentTy100644 0 0 11024 10661532626 31446 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/contrib/org/apache/commons/httpclient/contrib/methods/multipart/ContentTypeFilePart.java,v 1.2 2004/02/22 18:08:45 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.contrib.methods.multipart; import java.io.File; import java.io.FileNotFoundException; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.PartSource; /** A simple extension to {@link FilePart} that automatically determines the content type * of the file. * * @author Adrian Sutton * @version $Revision $ * * DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * to be used without additional customization. */ public class ContentTypeFilePart extends FilePart { /** * ContentTypeFilePart constructor. * * @param name the name of the part * @param partSource the source for this part * @param charset the charset encoding for this part. */ public ContentTypeFilePart(String name, PartSource partSource, String charset) { super(name, partSource, ContentType.get(partSource.getFileName()), charset); } /** * ContentTypeFilePart constructor. * * @param name the name of the part * @param partSource the source for this part */ public ContentTypeFilePart(String name, PartSource partSource) { this(name, partSource, null); } /** * ContentTypeFilePart constructor. * * @param name the name of the part * @param file the file to post * @throws FileNotFoundException if the file does not exist */ public ContentTypeFilePart(String name, File file) throws FileNotFoundException { this(name, file, null); } /** * ContentTypeFilePart constructor. * * @param name the name of the part * @param file the file to post * @param charset the charset encoding for the file * @throws FileNotFoundException */ public ContentTypeFilePart(String name, File file, String charset) throws FileNotFoundException { super(name, file, ContentType.get(file), charset); } /** * ContentTypeFilePart constructor. * * @param name the name of the part * @param fileName the file name * @param file the file to post * @throws FileNotFoundException if the file does not exist */ public ContentTypeFilePart(String name, String fileName, File file) throws FileNotFoundException { super(name, fileName, file, ContentType.get(fileName), null); } /** * ContentTypeFilePart constructor. * * @param name the name of the part * @param fileName the file name * @param file the file to post * @param charset the charset encoding for the file * @throws FileNotFoundException if the file does not exist */ public ContentTypeFilePart(String name, String fileName, File file, String charset) throws FileNotFoundException { super(name, fileName, file, ContentType.get(file), charset); } } commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/proxy/PluginProxyTest.html100644 0 0 2314 10661532632 31276 0ustar 0 0 Java Plugin Proxy Detection Test Applet Page

Java Plugin Proxy Detection Test Applet Page



././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/proxy/PluginProxyTestApplet.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/proxy/PluginProxyTestApplet100644 0 0 15523 10661532627 31533 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/contrib/org/apache/commons/httpclient/contrib/proxy/PluginProxyTestApplet.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.proxy; import java.awt.BorderLayout; import java.awt.Container; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import org.apache.commons.httpclient.ProxyHost; /** *

* DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * for use without additional customization. *

*/ public class PluginProxyTestApplet extends JApplet { private JTextField urlTextField = new JTextField(); private JPanel grid = null; private JLabel hostLabel = null; private JLabel portLabel = null; public PluginProxyTestApplet() { } public void init() { Container content = getContentPane(); content.setLayout(new BorderLayout()); // Proxy info table grid = getPanel(new GridLayout(2,3,2,2)); grid.add(getHeaderLabel("URL")); grid.add(getHeaderLabel("Proxy Host")); grid.add(getHeaderLabel("Proxy Port")); grid.add(urlTextField); hostLabel = getLabel(""); portLabel = getLabel(""); grid.add(hostLabel); grid.add(portLabel); grid.validate(); content.add(grid, BorderLayout.CENTER); // Button panel - SOUTH JPanel buttonPanel = getPanel(new FlowLayout()); JButton button = new JButton("Detect Proxy"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { detectProxy(); } }); } }); buttonPanel.add(button); content.add(buttonPanel, BorderLayout.SOUTH); // version panel - NORTH JPanel versionPanel = getPanel(new FlowLayout()); String javaVersion = System.getProperty("java.runtime.version"); JLabel versionLabel = getLabel("Java Version: "+javaVersion); versionPanel.add(versionLabel); content.add(versionPanel, BorderLayout.NORTH); validate(); super.setSize(400,100); } private JPanel getPanel(LayoutManager layout) { JPanel result = new JPanel(layout); return result; } private JLabel getHeaderLabel(String text) { JLabel result = new JLabel("" + text + ""); result.setHorizontalAlignment(JLabel.CENTER); return result; } private JLabel getLabel(String text) { JLabel result = new JLabel(text); result.setHorizontalAlignment(JLabel.CENTER); return result; } private void detectProxy() { String urlString = urlTextField.getText(); if (urlString == null || "".equals(urlString)) { JOptionPane.showMessageDialog(super.getRootPane(), "URL can't be empty", "Missing URL", JOptionPane.ERROR_MESSAGE); return; } if (!urlString.startsWith("http://")) { urlString = "http://" + urlString; } try { URL url = new URL(urlString); ProxyHost hostInfo = PluginProxyUtil.detectProxy(url); if (hostInfo != null) { hostLabel.setText(hostInfo.getHostName()); portLabel.setText(""+hostInfo.getPort()); } else { hostLabel.setText("none"); portLabel.setText("none"); } grid.validate(); } catch (ProxyDetectionException e) { JOptionPane.showMessageDialog(getRootPane(), e.getMessage() , "Proxy Detection Failed", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } catch (Exception e) { JOptionPane.showMessageDialog(getRootPane(), e.getMessage() , "Unexpected Exception", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } public String getProxyHost(String urlString) { String result = urlString; try { URL url = new URL(urlString); ProxyHost hostInfo = PluginProxyUtil.detectProxy(url); if (hostInfo != null) { result = hostInfo.getHostName(); } } catch (Exception e) { e.printStackTrace(); } return result; } public int getProxyPort(String urlString) { int result = 80; try { URL url = new URL(urlString); ProxyHost hostInfo = PluginProxyUtil.detectProxy(url); if (hostInfo != null) { result = hostInfo.getPort(); } } catch (Exception e) { e.printStackTrace(); } return result; } } commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/proxy/PluginProxyUtil.java100644 0 0 34661 10661532627 31307 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/contrib/org/apache/commons/httpclient/contrib/proxy/PluginProxyUtil.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.proxy; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.net.URL; import java.util.Properties; import org.apache.commons.httpclient.ProxyHost; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A utility class that gives applets the ability to detect proxy host settings. * This was adapted from a post from Chris Forster on 20030227 to a Sun Java * forum here: * http://forum.java.sun.com/thread.jspa?threadID=364342&tstart=120 * * The algorithm - which relies on Sun java plugin internal classes in some * cases - was maintained, but the following changes were made: * * 1. Logging was used to allow control of debug type messages. * 2. Reflection is used instead of direct references to Sun internal classes * to avoid the need to have these classes in the CLASSPATH to compile. * 3. Removed the use of global variables to allow this class to be used in * a multi-threaded environment. * 4. Add the use of exception to indicate to the caller when proxy detection * failed as opposed to when no proxy is configured. * *

* DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * for use without additional customization. *

*/ public class PluginProxyUtil { /** Log object for this class */ private static final Log LOG = LogFactory.getLog(PluginProxyUtil.class); /** * This is used internally to indicate that no proxy detection succeeded * and no proxy setting is to be used - failover is unnecessary */ private static final ProxyHost NO_PROXY_HOST = new ProxyHost("",80); /** * The system property that is used to convey proxy information in some VM's */ private static final String PLUGIN_PROXY_CONFIG_PROP = "javaplugin.proxy.config.list"; /** * Returns the Proxy Host information using settings from the java plugin. * * @param sampleURL the url target for which proxy host information is * required * @return the proxy host info (name and port) or null if a direct * connection is allowed to the target url. * @throws ProxyDetectionException if detection failed */ public static ProxyHost detectProxy(URL sampleURL) throws ProxyDetectionException { ProxyHost result = null; String javaVers = System.getProperty("java.runtime.version"); if (LOG.isDebugEnabled()) { LOG.debug("About to attempt auto proxy detection under Java " + "version:"+javaVers); } // If specific, known detection methods fail may try fallback // detection method boolean invokeFailover = false; if (javaVers.startsWith("1.3")) { result = detectProxySettingsJDK13(sampleURL); if (result == null) { invokeFailover = true; } } else if (javaVers.startsWith("1.4") || (javaVers.startsWith("1.5") || javaVers.startsWith("1.6"))) { result = detectProxySettingsJDK14_JDK15_JDK16(sampleURL); if (result == null) { invokeFailover = true; } } else { if (LOG.isDebugEnabled()) { LOG.debug("Sun Plugin reported java version not 1.3.X, " + "1.4.X, 1.5.X or 1.6.X - trying failover detection..."); } invokeFailover = true; } if (invokeFailover) { if (LOG.isDebugEnabled()) { LOG.debug("Using failover proxy detection..."); } result = getPluginProxyConfigSettings(); } if (NO_PROXY_HOST.equals(result)) { result = null; } return result; } /** * Use Sun-specific internal plugin proxy classes for 1.3.X * Look around for the 1.3.X plugin proxy detection class. Without it, * cannot autodetect... * * @param sampleURL the URL to check proxy settings for * @return ProxyHost the host and port of the proxy that should be used * @throws ProxyDetectionException if detection failed */ private static ProxyHost detectProxySettingsJDK13(URL sampleURL) throws ProxyDetectionException { ProxyHost result = null; try { // Attempt to discover proxy info by asking internal plugin // code to locate proxy path to server sampleURL... Class pluginProxyHandler = Class.forName("sun.plugin.protocol.PluginProxyHandler"); Method getDefaultProxyHandlerMethod = pluginProxyHandler.getDeclaredMethod("getDefaultProxyHandler", null); Object proxyHandlerObj = getDefaultProxyHandlerMethod.invoke(null, null); if (proxyHandlerObj != null) { Class proxyHandlerClass = proxyHandlerObj.getClass(); Method getProxyInfoMethod = proxyHandlerClass.getDeclaredMethod("getProxyInfo", new Class[]{URL.class}); Object proxyInfoObject = getProxyInfoMethod.invoke(proxyHandlerObj, new Object[] { sampleURL }); if (proxyInfoObject != null) { Class proxyInfoClass = proxyInfoObject.getClass(); Method getProxyMethod = proxyInfoClass.getDeclaredMethod("getProxy", null); boolean useProxy = (getProxyMethod.invoke(proxyInfoObject, null) != null); if (useProxy) { String proxyIP = (String)getProxyMethod.invoke(proxyInfoObject, null); Method getProxyPortMethod = proxyInfoClass.getDeclaredMethod("getPort", null); Integer portInteger = (Integer)getProxyPortMethod.invoke(proxyInfoObject, null); int proxyPort = portInteger.intValue(); if (LOG.isDebugEnabled()) { LOG.debug("1.3.X: proxy=" + proxyIP+ " port=" + proxyPort); } result = new ProxyHost(proxyIP, proxyPort); } else { if (LOG.isDebugEnabled()) { LOG.debug("1.3.X reported NULL for " + "proxyInfo.getProxy (no proxy assumed)"); } result = NO_PROXY_HOST; } } else { if (LOG.isDebugEnabled()) { LOG.debug("NULL proxyInfo in 1.3.X auto proxy " + "detection, (no proxy assumed)"); } result = NO_PROXY_HOST; } } else { throw new ProxyDetectionException( "Sun Plugin 1.3.X failed to provide a default proxy handler"); } } catch (Exception e) { LOG.warn("Sun Plugin 1.3.X proxy detection class not " + "found, will try failover detection, e:"+e); } return result; } /** * Returns the proxy information for the specified sampleURL using JRE 1.4 * specific plugin classes. * * Notes: * Plugin 1.4 Final added * com.sun.java.browser.net.* classes ProxyInfo & ProxyService... * Use those with JREs => 1.4 * * @param sampleURL the URL to check proxy settings for * @return ProxyHost the host and port of the proxy that should be used */ private static ProxyHost detectProxySettingsJDK14_JDK15_JDK16(URL sampleURL) { ProxyHost result = null; try { // Look around for the 1.4.X plugin proxy detection class... // Without it, cannot autodetect... Class ProxyServiceClass = Class.forName("com.sun.java.browser.net.ProxyService"); Method getProxyInfoMethod = ProxyServiceClass.getDeclaredMethod("getProxyInfo", new Class[] {URL.class}); Object proxyInfoArrayObj = getProxyInfoMethod.invoke(null, new Object[] {sampleURL}); if (proxyInfoArrayObj == null || Array.getLength(proxyInfoArrayObj) == 0) { if (LOG.isDebugEnabled()) { LOG.debug("1.4.X reported NULL proxy (no proxy assumed)"); } result = NO_PROXY_HOST; } else { Object proxyInfoObject = Array.get(proxyInfoArrayObj, 0); Class proxyInfoClass = proxyInfoObject.getClass(); Method getHostMethod = proxyInfoClass.getDeclaredMethod("getHost",null); String proxyIP = (String)getHostMethod.invoke(proxyInfoObject, null); Method getPortMethod = proxyInfoClass.getDeclaredMethod("getPort",null); Integer portInteger = (Integer)getPortMethod.invoke(proxyInfoObject, null); int proxyPort = portInteger.intValue(); if (LOG.isDebugEnabled()) { LOG.debug("1.4.X Proxy info geProxy:"+proxyIP+ " get Port:"+proxyPort); } result = new ProxyHost(proxyIP, proxyPort); } } catch (Exception e) { e.printStackTrace(); LOG.warn("Sun Plugin 1.4.X proxy detection class not found, " + "will try failover detection, e:"+e); } return result; } /** * Returns the proxy host information found by inspecting the system * property "javaplugin.proxy.config.list". * * @return ProxyHost the host and port of the proxy that should be used * @throws ProxyDetectionException if an exception is encountered while * parsing the value of * PLUGIN_PROXY_CONFIG_PROP */ private static ProxyHost getPluginProxyConfigSettings() throws ProxyDetectionException { ProxyHost result = null; try { Properties properties = System.getProperties(); String proxyList = properties.getProperty("javaplugin.proxy.config.list"); if (LOG.isDebugEnabled()) { LOG.debug("Plugin Proxy Config List Property:"+proxyList); } boolean useProxy = (proxyList != null); if (useProxy) { proxyList = proxyList.toUpperCase(); // Using HTTP proxy as proxy for HTTP proxy tunnelled SSL // socket (should be listed FIRST).... // 1/14/03 1.3.1_06 appears to omit HTTP portion of // reported proxy list... Mod to accomodate this... // Expecting proxyList of "HTTP=XXX.XXX.XXX.XXX:Port" OR // "XXX.XXX.XXX.XXX:Port" & assuming HTTP... String proxyIP=""; if (proxyList.indexOf("HTTP=") > -1) { proxyIP = proxyList.substring(proxyList.indexOf("HTTP=")+5, proxyList.indexOf(":")); } else { proxyIP = proxyList.substring(0, proxyList.indexOf(":")); } int endOfPort = proxyList.indexOf(","); if (endOfPort < 1) endOfPort = proxyList.length(); String portString = proxyList.substring(proxyList.indexOf(":")+1,endOfPort); int proxyPort = Integer.parseInt(portString); if (LOG.isDebugEnabled()) { LOG.debug("proxy " + proxyIP+" port " + proxyPort); } result = new ProxyHost(proxyIP, proxyPort); } else { LOG.debug("No configured plugin proxy list"); result = NO_PROXY_HOST; } } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Exception during failover auto proxy detection, " + ", e:"+e); throw new ProxyDetectionException( "Encountered unexpected exception while attempting " + "to parse proxy information stored in "+ PLUGIN_PROXY_CONFIG_PROP, e); } } return result; } } ././@LongLink100644 0 0 154 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/proxy/ProxyDetectionException.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/proxy/ProxyDetectionExcepti100644 0 0 5465 10661532627 31513 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/contrib/org/apache/commons/httpclient/contrib/proxy/ProxyDetectionException.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.proxy; import org.apache.commons.httpclient.util.ExceptionUtil; /** * Signals a problem with auto-detecting the proxy information using the java * plugin. * *

* DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * for use without additional customization. *

*/ public class ProxyDetectionException extends Exception { /** * Creates a new ProxyDetectionException with a null detail message. */ public ProxyDetectionException() { super(); } /** * Creates a new ProxyDetectionException with the specified detail message. * * @param message The exception detail message */ public ProxyDetectionException(String message) { super(message); } /** * Creates a new ProxyDetectionException with the specified detail message * and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or * null if the cause is unavailable, unknown, or not * a Throwable */ public ProxyDetectionException(String message, Throwable cause) { super(message); ExceptionUtil.initCause(this, cause); } } ././@LongLink100644 0 0 155 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/AuthSSLInitializationError.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/AuthSSLInitializationEr100644 0 0 4463 10661532627 31310 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/contrib/org/apache/commons/httpclient/contrib/ssl/AuthSSLInitializationError.java,v 1.2 2004/06/10 18:25:24 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient.contrib.ssl; /** *

* Signals fatal error in initialization of {@link AuthSSLProtocolSocketFactory}. *

* * @author Oleg Kalnichevski * *

* DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * for use without additional customization. *

*/ public class AuthSSLInitializationError extends Error { /** * Creates a new AuthSSLInitializationError. */ public AuthSSLInitializationError() { super(); } /** * Creates a new AuthSSLInitializationError with the specified message. * * @param message error message */ public AuthSSLInitializationError(String message) { super(message); } } ././@LongLink100644 0 0 157 10661532634 10264 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/AuthSSLProtocolSocketFactory.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/AuthSSLProtocolSocketFa100644 0 0 42727 10661532627 31300 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/contrib/org/apache/commons/httpclient/contrib/ssl/AuthSSLProtocolSocketFactory.java,v 1.2 2004/06/10 18:25:24 olegk Exp $ * $Revision: 514390 $ * $Date: 2007-03-04 13:37:15 +0100 (Sun, 04 Mar 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.ssl; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.URL; import java.net.UnknownHostException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Enumeration; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.net.SocketFactory; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; /** *

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

* *

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

* *

* Use JDK keytool utility to import a trusted certificate and generate a truststore file: *

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

* *

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

* *

* Use the following sequence of actions to generate a keystore file *

*
    *
  • *

    * Use JDK keytool utility to generate a new key *

    keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore
    * For simplicity use the same password for the key as that of the keystore *

    *
  • *
  • *

    * Issue a certificate signing request (CSR) *

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

    *
  • *
  • *

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

    *
  • *
  • *

    * Import the trusted CA root certificate *

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

    *
  • *
  • *

    * Import the PKCS#7 file containg the complete certificate chain *

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

    *
  • *
  • *

    * Verify the content the resultant keystore file *

    keytool -list -v -keystore my.keystore
    *

    *
  • *
*

* Example of using custom protocol socket factory for a specific host: *

 *     Protocol authhttps = new Protocol("https",  
 *          new AuthSSLProtocolSocketFactory(
 *              new URL("file:my.keystore"), "mypassword",
 *              new URL("file:my.truststore"), "mypassword"), 443); 
 *
 *     HttpClient client = new HttpClient();
 *     client.getHostConfiguration().setHost("localhost", 443, authhttps);
 *     // use relative url only
 *     GetMethod httpget = new GetMethod("/");
 *     client.executeMethod(httpget);
 *     
*

*

* Example of using custom protocol socket factory per default instead of the standard one: *

 *     Protocol authhttps = new Protocol("https",  
 *          new AuthSSLProtocolSocketFactory(
 *              new URL("file:my.keystore"), "mypassword",
 *              new URL("file:my.truststore"), "mypassword"), 443); 
 *     Protocol.registerProtocol("https", authhttps);
 *
 *     HttpClient client = new HttpClient();
 *     GetMethod httpget = new GetMethod("https://localhost/");
 *     client.executeMethod(httpget);
 *     
*

* @author Oleg Kalnichevski * *

* DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * for use without additional customization. *

*/ public class AuthSSLProtocolSocketFactory implements SecureProtocolSocketFactory { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(AuthSSLProtocolSocketFactory.class); private URL keystoreUrl = null; private String keystorePassword = null; private URL truststoreUrl = null; private String truststorePassword = null; private SSLContext sslcontext = null; /** * Constructor for AuthSSLProtocolSocketFactory. Either a keystore or truststore file * must be given. Otherwise SSL context initialization error will result. * * @param keystoreUrl URL of the keystore file. May be null if HTTPS client * authentication is not to be used. * @param keystorePassword Password to unlock the keystore. IMPORTANT: this implementation * assumes that the same password is used to protect the key and the keystore itself. * @param truststoreUrl URL of the truststore file. May be null if HTTPS server * authentication is not to be used. * @param truststorePassword Password to unlock the truststore. */ public AuthSSLProtocolSocketFactory( final URL keystoreUrl, final String keystorePassword, final URL truststoreUrl, final String truststorePassword) { super(); this.keystoreUrl = keystoreUrl; this.keystorePassword = keystorePassword; this.truststoreUrl = truststoreUrl; this.truststorePassword = truststorePassword; } private static KeyStore createKeyStore(final URL url, final String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { if (url == null) { throw new IllegalArgumentException("Keystore url may not be null"); } LOG.debug("Initializing key store"); KeyStore keystore = KeyStore.getInstance("jks"); InputStream is = null; try { is = url.openStream(); keystore.load(is, password != null ? password.toCharArray(): null); } finally { if (is != null) is.close(); } return keystore; } private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { if (keystore == null) { throw new IllegalArgumentException("Keystore may not be null"); } LOG.debug("Initializing key manager"); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, password != null ? password.toCharArray(): null); return kmfactory.getKeyManagers(); } private static TrustManager[] createTrustManagers(final KeyStore keystore) throws KeyStoreException, NoSuchAlgorithmException { if (keystore == null) { throw new IllegalArgumentException("Keystore may not be null"); } LOG.debug("Initializing trust manager"); TrustManagerFactory tmfactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(keystore); TrustManager[] trustmanagers = tmfactory.getTrustManagers(); for (int i = 0; i < trustmanagers.length; i++) { if (trustmanagers[i] instanceof X509TrustManager) { trustmanagers[i] = new AuthSSLX509TrustManager( (X509TrustManager)trustmanagers[i]); } } return trustmanagers; } private SSLContext createSSLContext() { try { KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (LOG.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String)aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { LOG.debug("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate)certs[c]; LOG.debug(" Certificate " + (c + 1) + ":"); LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore() ); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (LOG.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String)aliases.nextElement(); LOG.debug("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate)trustedcert; LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore() ); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } } private SSLContext getSSLContext() { if (this.sslcontext == null) { this.sslcontext = createSSLContext(); } return this.sslcontext; } /** * Attempts to get a new socket connection to the given host within the given time limit. *

* To circumvent the limitations of older JREs that do not support connect timeout a * controller thread is executed. The controller thread attempts to create a new socket * within the given limit of time. If socket constructor does not return until the * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException} *

* * @param host the host name/IP * @param port the port on the host * @param clientHost the local host name/IP to bind the socket to * @param clientPort the port on the local machine * @param params {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined */ public Socket createSocket( final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params ) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); SocketFactory socketfactory = getSSLContext().getSocketFactory(); if (timeout == 0) { return socketfactory.createSocket(host, port, localAddress, localPort); } else { Socket socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); return socket; } } /** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) */ public Socket createSocket( String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket( host, port, clientHost, clientPort ); } /** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int) */ public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket( host, port ); } /** * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean) */ public Socket createSocket( Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket( socket, host, port, autoClose ); } } ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/AuthSSLX509TrustManager.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/AuthSSLX509TrustManager100644 0 0 11327 10661532626 31050 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/contrib/org/apache/commons/httpclient/contrib/ssl/AuthSSLX509TrustManager.java,v 1.2 2004/06/10 18:25:24 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.ssl; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

* AuthSSLX509TrustManager can be used to extend the default {@link X509TrustManager} * with additional trust decisions. *

* * @author Oleg Kalnichevski * *

* DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * for use without additional customization. *

*/ public class AuthSSLX509TrustManager implements X509TrustManager { private X509TrustManager defaultTrustManager = null; /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(AuthSSLX509TrustManager.class); /** * Constructor for AuthSSLX509TrustManager. */ public AuthSSLX509TrustManager(final X509TrustManager defaultTrustManager) { super(); if (defaultTrustManager == null) { throw new IllegalArgumentException("Trust manager may not be null"); } this.defaultTrustManager = defaultTrustManager; } /** * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType) */ public void checkClientTrusted(X509Certificate[] certificates,String authType) throws CertificateException { if (LOG.isInfoEnabled() && certificates != null) { for (int c = 0; c < certificates.length; c++) { X509Certificate cert = certificates[c]; LOG.info(" Client certificate " + (c + 1) + ":"); LOG.info(" Subject DN: " + cert.getSubjectDN()); LOG.info(" Signature Algorithm: " + cert.getSigAlgName()); LOG.info(" Valid from: " + cert.getNotBefore() ); LOG.info(" Valid until: " + cert.getNotAfter()); LOG.info(" Issuer: " + cert.getIssuerDN()); } } defaultTrustManager.checkClientTrusted(certificates,authType); } /** * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType) */ public void checkServerTrusted(X509Certificate[] certificates,String authType) throws CertificateException { if (LOG.isInfoEnabled() && certificates != null) { for (int c = 0; c < certificates.length; c++) { X509Certificate cert = certificates[c]; LOG.info(" Server certificate " + (c + 1) + ":"); LOG.info(" Subject DN: " + cert.getSubjectDN()); LOG.info(" Signature Algorithm: " + cert.getSigAlgName()); LOG.info(" Valid from: " + cert.getNotBefore() ); LOG.info(" Valid until: " + cert.getNotAfter()); LOG.info(" Issuer: " + cert.getIssuerDN()); } } defaultTrustManager.checkServerTrusted(certificates,authType); } /** * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() */ public X509Certificate[] getAcceptedIssuers() { return this.defaultTrustManager.getAcceptedIssuers(); } } ././@LongLink100644 0 0 157 10661532634 10264 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFa100644 0 0 20026 10661532626 31263 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/contrib/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java,v 1.7 2004/06/11 19:26:27 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.ssl; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.HttpClientError; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; /** *

* EasySSLProtocolSocketFactory can be used to creats SSL {@link Socket}s * that accept self-signed certificates. *

*

* This socket factory SHOULD NOT be used for productive systems * due to security reasons, unless it is a concious decision and * you are perfectly aware of security implications of accepting * self-signed certificates *

* *

* Example of using custom protocol socket factory for a specific host: *

 *     Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
 *
 *     HttpClient client = new HttpClient();
 *     client.getHostConfiguration().setHost("localhost", 443, easyhttps);
 *     // use relative url only
 *     GetMethod httpget = new GetMethod("/");
 *     client.executeMethod(httpget);
 *     
*

*

* Example of using custom protocol socket factory per default instead of the standard one: *

 *     Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
 *     Protocol.registerProtocol("https", easyhttps);
 *
 *     HttpClient client = new HttpClient();
 *     GetMethod httpget = new GetMethod("https://localhost/");
 *     client.executeMethod(httpget);
 *     
*

* * @author Oleg Kalnichevski * *

* DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * for use without additional customization. *

*/ public class EasySSLProtocolSocketFactory implements SecureProtocolSocketFactory { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(EasySSLProtocolSocketFactory.class); private SSLContext sslcontext = null; /** * Constructor for EasySSLProtocolSocketFactory. */ public EasySSLProtocolSocketFactory() { super(); } private static SSLContext createEasySSLContext() { try { SSLContext context = SSLContext.getInstance("SSL"); context.init( null, new TrustManager[] {new EasyX509TrustManager(null)}, null); return context; } catch (Exception e) { LOG.error(e.getMessage(), e); throw new HttpClientError(e.toString()); } } private SSLContext getSSLContext() { if (this.sslcontext == null) { this.sslcontext = createEasySSLContext(); } return this.sslcontext; } /** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) */ public Socket createSocket( String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket( host, port, clientHost, clientPort ); } /** * Attempts to get a new socket connection to the given host within the given time limit. *

* To circumvent the limitations of older JREs that do not support connect timeout a * controller thread is executed. The controller thread attempts to create a new socket * within the given limit of time. If socket constructor does not return until the * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException} *

* * @param host the host name/IP * @param port the port on the host * @param clientHost the local host name/IP to bind the socket to * @param clientPort the port on the local machine * @param params {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined */ public Socket createSocket( final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params ) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); SocketFactory socketfactory = getSSLContext().getSocketFactory(); if (timeout == 0) { return socketfactory.createSocket(host, port, localAddress, localPort); } else { Socket socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); return socket; } } /** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int) */ public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket( host, port ); } /** * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean) */ public Socket createSocket( Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket( socket, host, port, autoClose ); } public boolean equals(Object obj) { return ((obj != null) && obj.getClass().equals(EasySSLProtocolSocketFactory.class)); } public int hashCode() { return EasySSLProtocolSocketFactory.class.hashCode(); } } ././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/EasyX509TrustManager.ja100644 0 0 10553 10661532626 31057 0ustar 0 0 /* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.ssl; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

* EasyX509TrustManager unlike default {@link X509TrustManager} accepts * self-signed certificates. *

*

* This trust manager SHOULD NOT be used for productive systems * due to security reasons, unless it is a concious decision and * you are perfectly aware of security implications of accepting * self-signed certificates *

* * @author Adrian Sutton * @author Oleg Kalnichevski * *

* DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * for use without additional customization. *

*/ public class EasyX509TrustManager implements X509TrustManager { private X509TrustManager standardTrustManager = null; /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(EasyX509TrustManager.class); /** * Constructor for EasyX509TrustManager. */ public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException { super(); TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(keystore); TrustManager[] trustmanagers = factory.getTrustManagers(); if (trustmanagers.length == 0) { throw new NoSuchAlgorithmException("no trust manager found"); } this.standardTrustManager = (X509TrustManager)trustmanagers[0]; } /** * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType) */ public void checkClientTrusted(X509Certificate[] certificates,String authType) throws CertificateException { standardTrustManager.checkClientTrusted(certificates,authType); } /** * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType) */ public void checkServerTrusted(X509Certificate[] certificates,String authType) throws CertificateException { if ((certificates != null) && LOG.isDebugEnabled()) { LOG.debug("Server certificate chain:"); for (int i = 0; i < certificates.length; i++) { LOG.debug("X509Certificate[" + i + "]=" + certificates[i]); } } if ((certificates != null) && (certificates.length == 1)) { certificates[0].checkValidity(); } else { standardTrustManager.checkServerTrusted(certificates,authType); } } /** * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() */ public X509Certificate[] getAcceptedIssuers() { return this.standardTrustManager.getAcceptedIssuers(); } } ././@LongLink100644 0 0 163 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/HostConfigurationWithHostFactory.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/HostConfigurationWithHo100644 0 0 3755 10661532626 31420 0ustar 0 0 package org.apache.commons.httpclient.contrib.ssl; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpURL; import org.apache.commons.httpclient.protocol.Protocol; /** * A kind of HostConfiguration that gets its Host from a factory. This is useful * for integrating a specialized Protocol or SocketFactory; for example, a * SecureSocketFactory that authenticates via SSL. Use * HttpClient.setHostConfiguration to install a HostConfigurationWithHostFactory * that contains the specialized HostFactory, Protocol or SocketFactory. *

* An alternative is to use Protocol.registerProtocol to register a specialized * Protocol. But that has drawbacks: it makes it hard to integrate modules (e.g. * web applications in a servlet container) with different strategies, because * they share the specialized Protocol (Protocol.PROTOCOLS is static). And it * can't support different Protocols for different hosts or ports (since the * host and port aren't parameters to Protocol.getProtocol). * * @author John Kristian */ class HostConfigurationWithHostFactory extends HostConfiguration { public HostConfigurationWithHostFactory(HttpHostFactory factory) { this.factory = factory; } private HostConfigurationWithHostFactory(HostConfigurationWithHostFactory that) { super(that); this.factory = that.factory; } private final HttpHostFactory factory; public Object clone() { return new HostConfigurationWithHostFactory(this); } private static final String DEFAULT_SCHEME = new String(HttpURL.DEFAULT_SCHEME); public void setHost(String host) { setHost(host, Protocol.getProtocol(DEFAULT_SCHEME).getDefaultPort()); } public void setHost(final String host, int port) { setHost(host, port, DEFAULT_SCHEME); } public synchronized void setHost(String host, int port, String scheme) { setHost(factory.getHost(this, scheme, host, port)); } } ././@LongLink100644 0 0 166 10661532634 10264 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/HostConfigurationWithStickyProtocol.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/HostConfigurationWithSt100644 0 0 5244 10661532627 31434 0ustar 0 0 package org.apache.commons.httpclient.contrib.ssl; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpHost; import org.apache.commons.httpclient.protocol.Protocol; /** * A kind of HostConfiguration that can retain its Protocol when its host name * or port changes. HttpClient may clone its HostConfigurationWithStickyProtocol * and change the host URL, without changing the specialized Protocol. *

* This is useful for integrating a specialized Protocol or SocketFactory; for * example, a SecureSocketFactory that authenticates via SSL. Use * HttpClient.setHostConfiguration to install a * HostConfigurationWithStickyProtocol that contains the specialized Protocol or * SocketFactory. *

* An alternative is to use Protocol.registerProtocol to register a specialized * Protocol. But that has drawbacks: it makes it hard to integrate modules (e.g. * web applications in a servlet container) with different strategies, because * they share the specialized Protocol (Protocol.PROTOCOLS is static). Also, it * can't handle multiple socket factories for the same host and port, since the * URL path isn't a parameter to Protocol.getProtocol or socket factory methods. * * @author John Kristian */ public class HostConfigurationWithStickyProtocol extends HostConfiguration { public HostConfigurationWithStickyProtocol() { } public HostConfigurationWithStickyProtocol(HostConfiguration hostConfiguration) { super(hostConfiguration); } public Object clone() { return new HostConfigurationWithStickyProtocol(this); } public synchronized void setHost(String host, int port, String scheme) { setHost(new HttpHost(host, port, getNewProtocol(host, port, scheme))); } /** * Select a Protocol to be used for the given host, port and scheme. The * current Protocol may be selected, if appropriate. This method need not be * thread-safe; the caller must synchronize if necessary. *

* This implementation returns the current Protocol if it has the given * scheme; otherwise it returns the Protocol registered for that scheme. */ protected Protocol getNewProtocol(String host, int port, String scheme) { final Protocol oldProtocol = getProtocol(); if (oldProtocol != null) { final String oldScheme = oldProtocol.getScheme(); if (oldScheme == scheme || (oldScheme != null && oldScheme.equalsIgnoreCase(scheme))) { // The old {rotocol has the desired scheme. return oldProtocol; // Retain it. } } return Protocol.getProtocol(scheme); } } commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/HttpHostFactory.java100644 0 0 4340 10661532626 30644 0ustar 0 0 package org.apache.commons.httpclient.contrib.ssl; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpHost; import org.apache.commons.httpclient.HttpsURL; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; /** A source of HttpHosts. */ public class HttpHostFactory { /** The default factory. */ public static final HttpHostFactory DEFAULT = new HttpHostFactory(null, // httpProtocol new Protocol(new String(HttpsURL.DEFAULT_SCHEME), (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), HttpsURL.DEFAULT_PORT)); public HttpHostFactory(Protocol httpProtocol, Protocol httpsProtocol) { this.httpProtocol = httpProtocol; this.httpsProtocol = httpsProtocol; } protected final Protocol httpProtocol; protected final Protocol httpsProtocol; /** Get a host for the given parameters. This method need not be thread-safe. */ public HttpHost getHost(HostConfiguration old, String scheme, String host, int port) { return new HttpHost(host, port, getProtocol(old, scheme, host, port)); } /** * Get a Protocol for the given parameters. The default implementation * selects a protocol based only on the scheme. Subclasses can do fancier * things, such as select SSL parameters based on the host or port. This * method must not return null. */ protected Protocol getProtocol(HostConfiguration old, String scheme, String host, int port) { final Protocol oldProtocol = old.getProtocol(); if (oldProtocol != null) { final String oldScheme = oldProtocol.getScheme(); if (oldScheme == scheme || (oldScheme != null && oldScheme.equalsIgnoreCase(scheme))) { // The old protocol has the desired scheme. return oldProtocol; // Retain it. } } Protocol newProtocol = (scheme != null && scheme.toLowerCase().endsWith("s")) ? httpsProtocol : httpProtocol; if (newProtocol == null) { newProtocol = Protocol.getProtocol(scheme); } return newProtocol; } } ././@LongLink100644 0 0 147 10661532634 10263 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/SocketFactoryWrapper.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/SocketFactoryWrapper.ja100644 0 0 10131 10661532626 31344 0ustar 0 0 /* * $Header$ * $Revision: 530846 $ * $Date: 2007-04-20 18:18:16 +0200 (Fri, 20 Apr 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.contrib.ssl; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; import javax.net.ssl.SSLSocketFactory; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; /** * Author: Mark Claassen *

* Uses some code from EasySSLProtocolSocketFactory.java * *

* Wraps a SSLSocketFactory with a SecureProtocolSocketFactory. *

* This was designed to make HttpClient work in situations where an application is being deployed by * Java Web Start. In these cases, SSL connections are negotiated by webstart implementations of the * KeyManager and TrustManager. Wrapping the socket factory obtained from * HttpsURLConnection.getDefaultSocketFactory allows the use of HttpClient while still leveraging * Java Web Start's handling of SSL certificates */ public class SocketFactoryWrapper implements SecureProtocolSocketFactory { private SSLSocketFactory socketFactory; public SocketFactoryWrapper(SSLSocketFactory socketFactory) { this.socketFactory = socketFactory; } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return socketFactory.createSocket(host, port); } public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException, UnknownHostException { return socketFactory.createSocket(host, port, localAddress, localPort); } public Socket createSocket( String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { // Based on code from EasySSLProtocolSocketFactory.java Socket rval; if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); if (timeout == 0) { rval = socketFactory.createSocket(host, port, localAddress, localPort); } else { rval = socketFactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); rval.bind(localaddr); rval.connect(remoteaddr, timeout); } return rval; } public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return socketFactory.createSocket(socket, host, port, autoClose); } } ././@LongLink100644 0 0 161 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/StrictSSLProtocolSocketFactory.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/ssl/StrictSSLProtocolSocket100644 0 0 33177 10661532626 31376 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/contrib/org/apache/commons/httpclient/contrib/ssl/StrictSSLProtocolSocketFactory.java,v 1.5 2004/06/10 18:25:24 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * * Alternatively, the contents of this file may be used under the * terms of the GNU Lesser General Public License Version 2 or later * (the "LGPL"), in which case the provisions of the LGPL are * applicable instead of those above. See terms of LGPL at * . * If you wish to allow use of your version of this file only under * the terms of the LGPL and not to allow others to use your version * of this file under the Apache Software License, indicate your * decision by deleting the provisions above and replace them with * the notice and other provisions required by the LGPL. If you do * not delete the provisions above, a recipient may use your version * of this file under either the Apache Software License or the LGPL. */ package org.apache.commons.httpclient.contrib.ssl; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; import javax.net.SocketFactory; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.security.cert.X509Certificate; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A SecureProtocolSocketFactory that uses JSSE to create * SSL sockets. It will also support host name verification to help preventing * man-in-the-middle attacks. Host name verification is turned on by * default but one will be able to turn it off, which might be a useful feature * during development. Host name verification will make sure the SSL sessions * server host name matches with the the host name returned in the * server certificates "Common Name" field of the "SubjectDN" entry. * * @author Sebastian Hauer *

* DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * for use without additional customization. *

*/ public class StrictSSLProtocolSocketFactory implements SecureProtocolSocketFactory { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(StrictSSLProtocolSocketFactory.class); /** Host name verify flag. */ private boolean verifyHostname = true; /** * Constructor for StrictSSLProtocolSocketFactory. * @param verifyHostname The host name verification flag. If set to * true the SSL sessions server host name will be compared * to the host name returned in the server certificates "Common Name" * field of the "SubjectDN" entry. If these names do not match a * Exception is thrown to indicate this. Enabling host name verification * will help to prevent from man-in-the-middle attacks. If set to * false host name verification is turned off. * * Code sample: * *
* Protocol stricthttps = new Protocol( * "https", new StrictSSLProtocolSocketFactory(true), 443); * * HttpClient client = new HttpClient(); * client.getHostConfiguration().setHost("localhost", 443, stricthttps); *
* */ public StrictSSLProtocolSocketFactory(boolean verifyHostname) { super(); this.verifyHostname = verifyHostname; } /** * Constructor for StrictSSLProtocolSocketFactory. * Host name verification will be enabled by default. */ public StrictSSLProtocolSocketFactory() { super(); } /** * Set the host name verification flag. * * @param verifyHostname The host name verification flag. If set to * true the SSL sessions server host name will be compared * to the host name returned in the server certificates "Common Name" * field of the "SubjectDN" entry. If these names do not match a * Exception is thrown to indicate this. Enabling host name verification * will help to prevent from man-in-the-middle attacks. If set to * false host name verification is turned off. */ public void setHostnameVerification(boolean verifyHostname) { this.verifyHostname = verifyHostname; } /** * Gets the status of the host name verification flag. * * @return Host name verification flag. Either true if host * name verification is turned on, or false if host name * verification is turned off. */ public boolean getHostnameVerification() { return verifyHostname; } /** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) */ public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sf.createSocket(host, port, clientHost, clientPort); verifyHostname(sslSocket); return sslSocket; } /** * Attempts to get a new socket connection to the given host within the given time limit. *

* This method employs several techniques to circumvent the limitations of older JREs that * do not support connect timeout. When running in JRE 1.4 or above reflection is used to * call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older * JREs a controller thread is executed. The controller thread attempts to create a new socket * within the given limit of time. If socket constructor does not return until the timeout * expires, the controller terminates and throws an {@link ConnectTimeoutException} *

* * @param host the host name/IP * @param port the port on the host * @param clientHost the local host name/IP to bind the socket to * @param clientPort the port on the local machine * @param params {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined */ public Socket createSocket( final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params ) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); Socket socket = null; SocketFactory socketfactory = SSLSocketFactory.getDefault(); if (timeout == 0) { socket = socketfactory.createSocket(host, port, localAddress, localPort); } else { socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); } verifyHostname((SSLSocket)socket); return socket; } /** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int) */ public Socket createSocket(String host, int port) throws IOException, UnknownHostException { SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sf.createSocket(host, port); verifyHostname(sslSocket); return sslSocket; } /** * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean) */ public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, port, autoClose); verifyHostname(sslSocket); return sslSocket; } /** * Describe verifyHostname method here. * * @param socket a SSLSocket value * @exception SSLPeerUnverifiedException If there are problems obtaining * the server certificates from the SSL session, or the server host name * does not match with the "Common Name" in the server certificates * SubjectDN. * @exception UnknownHostException If we are not able to resolve * the SSL sessions returned server host name. */ private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException { if (! verifyHostname) return; SSLSession session = socket.getSession(); String hostname = session.getPeerHost(); try { InetAddress addr = InetAddress.getByName(hostname); } catch (UnknownHostException uhe) { throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname); } X509Certificate[] certs = session.getPeerCertificateChain(); if (certs == null || certs.length == 0) throw new SSLPeerUnverifiedException("No server certificates found!"); //get the servers DN in its string representation String dn = certs[0].getSubjectDN().getName(); //might be useful to print out all certificates we receive from the //server, in case one has to debug a problem with the installed certs. if (LOG.isDebugEnabled()) { LOG.debug("Server certificate chain:"); for (int i = 0; i < certs.length; i++) { LOG.debug("X509Certificate[" + i + "]=" + certs[i]); } } //get the common name from the first cert String cn = getCN(dn); if (hostname.equalsIgnoreCase(cn)) { if (LOG.isDebugEnabled()) { LOG.debug("Target hostname valid: " + cn); } } else { throw new SSLPeerUnverifiedException( "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'"); } } /** * Parses a X.500 distinguished name for the value of the * "Common Name" field. * This is done a bit sloppy right now and should probably be done a bit * more according to RFC 2253. * * @param dn a X.500 distinguished name. * @return the value of the "Common Name" field. */ private String getCN(String dn) { int i = 0; i = dn.indexOf("CN="); if (i == -1) { return null; } //get the remaining DN without CN= dn = dn.substring(i + 3); // System.out.println("dn=" + dn); char[] dncs = dn.toCharArray(); for (i = 0; i < dncs.length; i++) { if (dncs[i] == ',' && i > 0 && dncs[i - 1] != '\\') { break; } } return dn.substring(0, i); } public boolean equals(Object obj) { if ((obj != null) && obj.getClass().equals(StrictSSLProtocolSocketFactory.class)) { return ((StrictSSLProtocolSocketFactory) obj).getHostnameVerification() == this.verifyHostname; } else { return false; } } public int hashCode() { return StrictSSLProtocolSocketFactory.class.hashCode(); } } ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/utils/HttpMethodCloner.javacommons-httpclient-3.1/src/contrib/org/apache/commons/httpclient/contrib/utils/HttpMethodCloner.java100644 0 0 10210 10661532626 31332 0ustar 0 0 /* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.contrib.utils; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.methods.EntityEnclosingMethod; import org.apache.commons.httpclient.params.HttpMethodParams; /** * In this class are only methods to copy a HttpMethod: * PUT, GET, POST,DELETE, TRACE, ... * * @author Thomas Mathis * * @deprecated * * DISCLAIMER: HttpClient developers DO NOT actively support this component. * The component is provided as a reference material, which may be inappropriate * to be used without additional customization. */ public class HttpMethodCloner { private static void copyEntityEnclosingMethod( EntityEnclosingMethod m, EntityEnclosingMethod copy ) throws java.io.IOException { copy.setRequestEntity(m.getRequestEntity()); } private static void copyHttpMethodBase( HttpMethodBase m, HttpMethodBase copy) { try { copy.setParams((HttpMethodParams)m.getParams().clone()); } catch (CloneNotSupportedException e) { // Should never happen } } /** * Clones a HttpMethod.
* Attention: You have to clone a method before it has * been executed, because the URI can change if followRedirects * is set to true. * * @param m the HttpMethod to clone * * @return the cloned HttpMethod, null if the HttpMethod could * not be instantiated * * @throws java.io.IOException if the request body couldn't be read */ public static HttpMethod clone(HttpMethod m) throws java.io.IOException { HttpMethod copy = null; // copy the HttpMethod try { copy = (HttpMethod) m.getClass().newInstance(); } catch (InstantiationException iEx) { } catch (IllegalAccessException iaEx) { } if ( copy == null ) { return null; } copy.setDoAuthentication(m.getDoAuthentication()); copy.setFollowRedirects(m.getFollowRedirects()); copy.setPath( m.getPath() ); copy.setQueryString(m.getQueryString()); // clone the headers Header[] h = m.getRequestHeaders(); int size = (h == null) ? 0 : h.length; for (int i = 0; i < size; i++) { copy.setRequestHeader( new Header(h[i].getName(), h[i].getValue())); } copy.setStrictMode(m.isStrictMode()); if (m instanceof HttpMethodBase) { copyHttpMethodBase( (HttpMethodBase)m, (HttpMethodBase)copy); } if (m instanceof EntityEnclosingMethod) { copyEntityEnclosingMethod( (EntityEnclosingMethod)m, (EntityEnclosingMethod)copy); } return copy; } } commons-httpclient-3.1/src/examples/AlternateAuthenticationExample.java100644 0 0 7267 10661532626 23761 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/examples/AlternateAuthenticationExample.java,v 1.3 2004/06/12 22:47:23 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthPolicy; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; /** *

A simple example that uses alternate authentication scheme selection * if several authentication challenges are returned. *

* *

Per default HttpClient picks the authentication challenge in the following * order of preference: NTLM, Digest, Basic. In certain cases it may be desirable to * force the use of a weaker authentication scheme. *

* * @author Oleg Kalnichevski */ public class AlternateAuthenticationExample { /** * Constructor for BasicAuthenticatonExample. */ public AlternateAuthenticationExample() { super(); } public static void main(String[] args) throws Exception { HttpClient client = new HttpClient(); client.getState().setCredentials( new AuthScope("myhost", 80, "myrealm"), new UsernamePasswordCredentials("username", "password")); // Suppose the site supports several authetication schemes: NTLM and Basic // Basic authetication is considered inherently insecure. Hence, NTLM authentication // is used per default // This is to make HttpClient pick the Basic authentication scheme over NTLM & Digest List authPrefs = new ArrayList(3); authPrefs.add(AuthPolicy.BASIC); authPrefs.add(AuthPolicy.NTLM); authPrefs.add(AuthPolicy.DIGEST); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); GetMethod httpget = new GetMethod("http://myhost/protected/auth-required.html"); try { int status = client.executeMethod(httpget); // print the status and response System.out.println(httpget.getStatusLine()); System.out.println(httpget.getResponseBodyAsString()); } finally { // release any connection resources used by the method httpget.releaseConnection(); } } } commons-httpclient-3.1/src/examples/BasicAuthenticationExample.java100644 0 0 7246 10661532626 23060 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/examples/BasicAuthenticationExample.java,v 1.4 2004/06/12 22:47:23 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; /** * A simple example that uses HttpClient to perform a GET using Basic * Authentication. Can be run standalone without parameters. * * You need to have JSSE on your classpath for JDK prior to 1.4 * * @author Michael Becke */ public class BasicAuthenticationExample { /** * Constructor for BasicAuthenticatonExample. */ public BasicAuthenticationExample() { super(); } public static void main(String[] args) throws Exception { HttpClient client = new HttpClient(); // pass our credentials to HttpClient, they will only be used for // authenticating to servers with realm "realm" on the host // "www.verisign.com", to authenticate against // an arbitrary realm or host change the appropriate argument to null. client.getState().setCredentials( new AuthScope("www.verisign.com", 443, "realm"), new UsernamePasswordCredentials("username", "password") ); // create a GET method that reads a file over HTTPS, we're assuming // that this file requires basic authentication using the realm above. GetMethod get = new GetMethod("https://www.verisign.com/products/index.html"); // Tell the GET method to automatically handle authentication. The // method will use any appropriate credentials to handle basic // authentication requests. Setting this value to false will cause // any request for authentication to return with a status of 401. // It will then be up to the client to handle the authentication. get.setDoAuthentication( true ); try { // execute the GET int status = client.executeMethod( get ); // print the status and response System.out.println(status + "\n" + get.getResponseBodyAsString()); } finally { // release any connection resources used by the method get.releaseConnection(); } } } commons-httpclient-3.1/src/examples/ChunkEncodedPost.java100644 0 0 5434 10661532627 21021 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/examples/ChunkEncodedPost.java,v 1.6 2004/05/12 20:43:53 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ import java.io.File; import java.io.FileInputStream; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; /** * Example how to use unbuffered chunk-encoded POST request. * * @author Oleg Kalnichevski */ public class ChunkEncodedPost { public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: ChunkEncodedPost "); System.out.println(" - full path to a file to be posted"); System.exit(1); } HttpClient client = new HttpClient(); PostMethod httppost = new PostMethod("http://localhost:8080/httpclienttest/body"); File file = new File(args[0]); httppost.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(file))); httppost.setContentChunked(true); try { client.executeMethod(httppost); if (httppost.getStatusCode() == HttpStatus.SC_OK) { System.out.println(httppost.getResponseBodyAsString()); } else { System.out.println("Unexpected failure: " + httppost.getStatusLine().toString()); } } finally { httppost.releaseConnection(); } } } commons-httpclient-3.1/src/examples/ClientApp.java100644 0 0 17166 10661532626 17524 0ustar 0 0 /* * $Header$ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.text.BadLocationException; import javax.swing.text.html.HTMLDocument; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.methods.GetMethod; /** * A simple Swing application that demonstrates how to use the Jakarta * HttpClient API. This application loads HTML from servers and displays the * content as text and as rendered HTML. * * @author Sean C. Sullivan * @author Ortwin Glck * @author Michael Becke */ public class ClientApp { public static void main(String[] args) { HttpClientFrame f = new HttpClientFrame(); f.setTitle("HttpClient demo application"); f.setSize(700, 500); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); f.setVisible(true); } public static class HttpClientFrame extends JFrame { private JComboBox cmbURL; private JTextArea taTextResponse; private JEditorPane htmlPane; private HttpClient client; public HttpClientFrame() { client = new HttpClient(new MultiThreadedHttpConnectionManager()); client.getHttpConnectionManager(). getParams().setConnectionTimeout(30000); JPanel panInput = new JPanel(new FlowLayout()); String[] aURLs = { "http://www.apache.org/", "http://www.google.com/", "http://www.opensource.org/", "http://www.anybrowser.org/", "http://jakarta.apache.org/", "http://www.w3.org/" }; final JButton btnGET = new JButton("GET"); btnGET.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { String url = (String) cmbURL.getSelectedItem(); if (url != null && url.length() > 0) { loadPage(url); } } } ); cmbURL = new JComboBox(aURLs); cmbURL.setToolTipText("Enter a URL"); cmbURL.setEditable(true); cmbURL.setSelectedIndex(0); JLabel lblURL = new JLabel("URL:"); panInput.add(lblURL); panInput.add(cmbURL); panInput.add(btnGET); taTextResponse = new JTextArea(); taTextResponse.setEditable(false); taTextResponse.setCaretPosition(0); htmlPane = new JEditorPane(); htmlPane.setContentType("text/html"); htmlPane.setEditable(false); JSplitPane splitResponsePane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(taTextResponse), new JScrollPane(htmlPane) ); splitResponsePane.setOneTouchExpandable(false); splitResponsePane.setDividerLocation(350); // it would be better to set resizeWeight, but this method does // not exist in JRE 1.2.2 // splitResponsePane.setResizeWeight(0.5); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add(panInput, BorderLayout.NORTH); this.getContentPane().add(splitResponsePane, BorderLayout.CENTER); } /** * Sets the HTML content to be displayed. * * @param content an HTML document */ private void setDocumentContent(String content) { HTMLDocument doc = new HTMLDocument(); try { doc.remove(0, doc.getLength()); } catch (BadLocationException e) { e.printStackTrace(); } doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE); try { htmlPane.read(new ByteArrayInputStream(content.getBytes()), doc); } catch (IOException e) { e.printStackTrace(); } htmlPane.setDocument(doc); htmlPane.setCaretPosition(0); taTextResponse.setText(content); taTextResponse.setCaretPosition(0); taTextResponse.requestFocus(); } /** * Loads the page at the given URL from a separate thread. * @param url */ private void loadPage(final String url) { // create a new thread to load the URL from new Thread() { public void run() { GetMethod get = new GetMethod(url); get.setFollowRedirects(true); try { int iGetResultCode = client.executeMethod(get); final String strGetResponseBody = get.getResponseBodyAsString(); if (strGetResponseBody != null) { // set the HTML on the UI thread SwingUtilities.invokeLater( new Runnable() { public void run() { setDocumentContent(strGetResponseBody); } } ); } } catch (Exception ex) { ex.printStackTrace(); } finally { get.releaseConnection(); } } }.start(); } } } commons-httpclient-3.1/src/examples/CookieDemoApp.java100644 0 0 11236 10661532626 20314 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/examples/CookieDemoApp.java,v 1.14 2004/02/22 18:08:45 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.GetMethod; /** * * This is a sample application that demonstrates * how to use the Jakarta HttpClient API. * * This application sets an HTTP cookie and * updates the cookie's value across multiple * HTTP GET requests. * * @author Sean C. Sullivan * @author Oleg Kalnichevski * */ public class CookieDemoApp { /** * * Usage: * java CookieDemoApp http://mywebserver:80/ * * @param args command line arguments * Argument 0 is a URL to a web server * * */ public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java CookieDemoApp "); System.err.println(" The url of a webpage"); System.exit(1); } // Get target URL String strURL = args[0]; System.out.println("Target URL: " + strURL); // Get initial state object HttpState initialState = new HttpState(); // Initial set of cookies can be retrieved from persistent storage and // re-created, using a persistence mechanism of choice, Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null, false); // and then added to your HTTP state instance initialState.addCookie(mycookie); // Get HTTP client instance HttpClient httpclient = new HttpClient(); httpclient.getHttpConnectionManager(). getParams().setConnectionTimeout(30000); httpclient.setState(initialState); // RFC 2101 cookie management spec is used per default // to parse, validate, format & match cookies httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); // A different cookie management spec can be selected // when desired //httpclient.getParams().setCookiePolicy(CookiePolicy.NETSCAPE); // Netscape Cookie Draft spec is provided for completeness // You would hardly want to use this spec in real life situations //httppclient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // Compatibility policy is provided in order to mimic cookie // management of popular web browsers that is in some areas // not 100% standards compliant // Get HTTP GET method GetMethod httpget = new GetMethod(strURL); // Execute HTTP GET int result = httpclient.executeMethod(httpget); // Display status code System.out.println("Response status code: " + result); // Get all the cookies Cookie[] cookies = httpclient.getState().getCookies(); // Display the cookies System.out.println("Present cookies: "); for (int i = 0; i < cookies.length; i++) { System.out.println(" - " + cookies[i].toExternalForm()); } // Release current connection to the connection pool once you are done httpget.releaseConnection(); } } commons-httpclient-3.1/src/examples/CustomAuthenticationExample.java100644 0 0 11101 10661532626 23312 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/examples/CustomAuthenticationExample.java,v 1.1 2004/09/06 20:10:02 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ import java.util.ArrayList; import java.util.Collection; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.auth.AuthPolicy; import org.apache.commons.httpclient.auth.AuthScheme; import org.apache.commons.httpclient.auth.AuthenticationException; import org.apache.commons.httpclient.auth.MalformedChallengeException; import org.apache.commons.httpclient.params.DefaultHttpParams; import org.apache.commons.httpclient.params.HttpParams; /** * A simple custom AuthScheme example. The included auth scheme is meant * for demonstration purposes only. It does not actually implement a usable * authentication method. */ public class CustomAuthenticationExample { public static void main(String[] args) { // register the auth scheme AuthPolicy.registerAuthScheme(SecretAuthScheme.NAME, SecretAuthScheme.class); // include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference, // this can be done on a per-client or per-method basis but we'll do it // globally for this example HttpParams params = DefaultHttpParams.getDefaultParams(); ArrayList schemes = new ArrayList(); schemes.add(SecretAuthScheme.NAME); schemes.addAll((Collection) params.getParameter(AuthPolicy.AUTH_SCHEME_PRIORITY)); params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes); // now that our scheme has been registered we can execute methods against // servers that require "Secret" authentication... } /** * A custom auth scheme that just uses "Open Sesame" as the authentication * string. */ private class SecretAuthScheme implements AuthScheme { public static final String NAME = "Secret"; public SecretAuthScheme() { // All auth schemes must have a no arg constructor. } public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException { return "Open Sesame"; } public String authenticate(Credentials credentials, String method, String uri) throws AuthenticationException { return "Open Sesame"; } public String getID() { return NAME; } public String getParameter(String name) { // this scheme does not use parameters, see RFC2617Scheme for an example return null; } public String getRealm() { // this scheme does not use realms return null; } public String getSchemeName() { return NAME; } public boolean isConnectionBased() { return false; } public void processChallenge(String challenge) throws MalformedChallengeException { // Nothing to do here, this is not a challenge based // auth scheme. See NTLMScheme for a good example. } public boolean isComplete() { // again we're not a challenge based scheme so this is always true return true; } } } commons-httpclient-3.1/src/examples/FormLoginDemo.java100644 0 0 13017 10661532627 20336 0ustar 0 0 /* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.methods.*; /** *

* A example that demonstrates how HttpClient APIs can be used to perform * form-based logon. *

* * @author Oleg Kalnichevski * */ public class FormLoginDemo { static final String LOGON_SITE = "developer.java.sun.com"; static final int LOGON_PORT = 80; public FormLoginDemo() { super(); } public static void main(String[] args) throws Exception { HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // 'developer.java.sun.com' has cookie compliance problems // Their session cookie's domain attribute is in violation of the RFC2109 // We have to resort to using compatibility cookie policy GetMethod authget = new GetMethod("/servlet/SessionServlet"); client.executeMethod(authget); System.out.println("Login form get: " + authget.getStatusLine().toString()); // release any connection resources used by the method authget.releaseConnection(); // See if we got any cookies CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] initcookies = cookiespec.match( LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Initial set of cookies:"); if (initcookies.length == 0) { System.out.println("None"); } else { for (int i = 0; i < initcookies.length; i++) { System.out.println("- " + initcookies[i].toString()); } } PostMethod authpost = new PostMethod("/servlet/SessionServlet"); // Prepare login parameters NameValuePair action = new NameValuePair("action", "login"); NameValuePair url = new NameValuePair("url", "/index.html"); NameValuePair userid = new NameValuePair("UserId", "userid"); NameValuePair password = new NameValuePair("Password", "password"); authpost.setRequestBody( new NameValuePair[] {action, url, userid, password}); client.executeMethod(authpost); System.out.println("Login form post: " + authpost.getStatusLine().toString()); // release any connection resources used by the method authpost.releaseConnection(); // See if we got any cookies // The only way of telling whether logon succeeded is // by finding a session cookie Cookie[] logoncookies = cookiespec.match( LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Logon cookies:"); if (logoncookies.length == 0) { System.out.println("None"); } else { for (int i = 0; i < logoncookies.length; i++) { System.out.println("- " + logoncookies[i].toString()); } } // Usually a successful form-based login results in a redicrect to // another url int statuscode = authpost.getStatusCode(); if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = authpost.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } System.out.println("Redirect target: " + newuri); GetMethod redirect = new GetMethod(newuri); client.executeMethod(redirect); System.out.println("Redirect: " + redirect.getStatusLine().toString()); // release any connection resources used by the method redirect.releaseConnection(); } else { System.out.println("Invalid redirect"); System.exit(1); } } } } commons-httpclient-3.1/src/examples/InteractiveAuthenticationExample.java100644 0 0 12777 10661532627 24342 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/examples/InteractiveAuthenticationExample.java,v 1.2 2004/02/22 18:08:45 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NTCredentials; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScheme; import org.apache.commons.httpclient.auth.CredentialsProvider; import org.apache.commons.httpclient.auth.CredentialsNotAvailableException; import org.apache.commons.httpclient.auth.NTLMScheme; import org.apache.commons.httpclient.auth.RFC2617Scheme; import org.apache.commons.httpclient.methods.GetMethod; /** * A simple example that uses HttpClient to perform interactive * authentication. * * @author Oleg Kalnichevski */ public class InteractiveAuthenticationExample { /** * Constructor for InteractiveAuthenticationExample. */ public InteractiveAuthenticationExample() { super(); } public static void main(String[] args) throws Exception { InteractiveAuthenticationExample demo = new InteractiveAuthenticationExample(); demo.doDemo(); } private void doDemo() throws IOException { HttpClient client = new HttpClient(); client.getParams().setParameter( CredentialsProvider.PROVIDER, new ConsoleAuthPrompter()); GetMethod httpget = new GetMethod("http://target-host/requires-auth.html"); httpget.setDoAuthentication(true); try { // execute the GET int status = client.executeMethod(httpget); // print the status and response System.out.println(httpget.getStatusLine().toString()); System.out.println(httpget.getResponseBodyAsString()); } finally { // release any connection resources used by the method httpget.releaseConnection(); } } public class ConsoleAuthPrompter implements CredentialsProvider { private BufferedReader in = null; public ConsoleAuthPrompter() { super(); this.in = new BufferedReader(new InputStreamReader(System.in)); } private String readConsole() throws IOException { return this.in.readLine(); } public Credentials getCredentials( final AuthScheme authscheme, final String host, int port, boolean proxy) throws CredentialsNotAvailableException { if (authscheme == null) { return null; } try{ if (authscheme instanceof NTLMScheme) { System.out.println(host + ":" + port + " requires Windows authentication"); System.out.print("Enter domain: "); String domain = readConsole(); System.out.print("Enter username: "); String user = readConsole(); System.out.print("Enter password: "); String password = readConsole(); return new NTCredentials(user, password, host, domain); } else if (authscheme instanceof RFC2617Scheme) { System.out.println(host + ":" + port + " requires authentication with the realm '" + authscheme.getRealm() + "'"); System.out.print("Enter username: "); String user = readConsole(); System.out.print("Enter password: "); String password = readConsole(); return new UsernamePasswordCredentials(user, password); } else { throw new CredentialsNotAvailableException("Unsupported authentication scheme: " + authscheme.getSchemeName()); } } catch (IOException e) { throw new CredentialsNotAvailableException(e.getMessage(), e); } } } } commons-httpclient-3.1/src/examples/MultiThreadedExample.java100644 0 0 11117 10661532627 21703 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/examples/MultiThreadedExample.java,v 1.3 2004/02/22 18:08:45 olegk Exp $ * $Revision: 554236 $ * $Date: 2007-07-07 20:15:09 +0200 (Sat, 07 Jul 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.methods.GetMethod; /** * An example that performs GETs from multiple threads. * * @author Michael Becke */ public class MultiThreadedExample { /** * Constructor for MultiThreadedExample. */ public MultiThreadedExample() { super(); } public static void main(String[] args) { // Create an HttpClient with the MultiThreadedHttpConnectionManager. // This connection manager must be used if more than one thread will // be using the HttpClient. HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); // Set the default host/protocol for the methods to connect to. // This value will only be used if the methods are not given an absolute URI httpClient.getHostConfiguration().setHost("jakarta.apache.org", 80, "http"); // create an array of URIs to perform GETs on String[] urisToGet = { "/", "/commons/", "/commons/httpclient/", "http://svn.apache.org/viewvc/jakarta/httpcomponents/oac.hc3x/" }; // create a thread for each URI GetThread[] threads = new GetThread[urisToGet.length]; for (int i = 0; i < threads.length; i++) { GetMethod get = new GetMethod(urisToGet[i]); get.setFollowRedirects(true); threads[i] = new GetThread(httpClient, get, i + 1); } // start the threads for (int j = 0; j < threads.length; j++) { threads[j].start(); } } /** * A thread that performs a GET. */ static class GetThread extends Thread { private HttpClient httpClient; private GetMethod method; private int id; public GetThread(HttpClient httpClient, GetMethod method, int id) { this.httpClient = httpClient; this.method = method; this.id = id; } /** * Executes the GetMethod and prints some satus information. */ public void run() { try { System.out.println(id + " - about to get something from " + method.getURI()); // execute the method httpClient.executeMethod(method); System.out.println(id + " - get executed"); // get the response body as an array of bytes byte[] bytes = method.getResponseBody(); System.out.println(id + " - " + bytes.length + " bytes read"); } catch (Exception e) { System.out.println(id + " - error: " + e); } finally { // always release the connection after we're done method.releaseConnection(); System.out.println(id + " - connection released"); } } } } commons-httpclient-3.1/src/examples/MultipartFileUploadApp.java100644 0 0 23676 10661532627 22240 0ustar 0 0 /* * $Header$ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.params.HttpMethodParams; /** * * This is a Swing application that demonstrates * how to use the Jakarta HttpClient multipart POST method * for uploading files * * @author Sean C. Sullivan * @author Michael Becke * */ public class MultipartFileUploadApp { public static void main(String[] args) { MultipartFileUploadFrame f = new MultipartFileUploadFrame(); f.setTitle("HTTP multipart file upload application"); f.pack(); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); f.setVisible(true); } public static class MultipartFileUploadFrame extends JFrame { private File targetFile; private JTextArea taTextResponse; private DefaultComboBoxModel cmbURLModel; public MultipartFileUploadFrame() { String[] aURLs = { "http://localhost:8080/httpclienttest/fileupload" }; cmbURLModel = new DefaultComboBoxModel(aURLs); final JComboBox cmbURL = new JComboBox(cmbURLModel); cmbURL.setToolTipText("Enter a URL"); cmbURL.setEditable(true); cmbURL.setSelectedIndex(0); JLabel lblTargetFile = new JLabel("Selected file:"); final JTextField tfdTargetFile = new JTextField(30); tfdTargetFile.setEditable(false); final JCheckBox cbxExpectHeader = new JCheckBox("Use Expect header"); cbxExpectHeader.setSelected(false); final JButton btnDoUpload = new JButton("Upload"); btnDoUpload.setEnabled(false); final JButton btnSelectFile = new JButton("Select a file..."); btnSelectFile.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evt) { JFileChooser chooser = new JFileChooser(); chooser.setFileHidingEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setMultiSelectionEnabled(false); chooser.setDialogType(JFileChooser.OPEN_DIALOG); chooser.setDialogTitle("Choose a file..."); if ( chooser.showOpenDialog(MultipartFileUploadFrame.this) == JFileChooser.APPROVE_OPTION ) { targetFile = chooser.getSelectedFile(); tfdTargetFile.setText(targetFile.toString()); btnDoUpload.setEnabled(true); } } } ); taTextResponse = new JTextArea(10, 40); taTextResponse.setEditable(false); final JLabel lblURL = new JLabel("URL:"); btnDoUpload.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String targetURL = cmbURL.getSelectedItem().toString(); // add the URL to the combo model if it's not already there if (!targetURL .equals( cmbURLModel.getElementAt( cmbURL.getSelectedIndex()))) { cmbURLModel.addElement(targetURL); } PostMethod filePost = new PostMethod(targetURL); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, cbxExpectHeader.isSelected()); try { appendMessage("Uploading " + targetFile.getName() + " to " + targetURL); Part[] parts = { new FilePart(targetFile.getName(), targetFile) }; filePost.setRequestEntity( new MultipartRequestEntity(parts, filePost.getParams()) ); HttpClient client = new HttpClient(); client.getHttpConnectionManager(). getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { appendMessage( "Upload complete, response=" + filePost.getResponseBodyAsString() ); } else { appendMessage( "Upload failed, response=" + HttpStatus.getStatusText(status) ); } } catch (Exception ex) { appendMessage("ERROR: " + ex.getClass().getName() + " "+ ex.getMessage()); ex.printStackTrace(); } finally { filePost.releaseConnection(); } } }); getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE; c.gridheight = 1; c.gridwidth = 1; c.gridx = 0; c.gridy = 0; c.insets = new Insets(10, 5, 5, 0); c.weightx = 1; c.weighty = 1; getContentPane().add(lblURL, c); c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.HORIZONTAL; c.gridwidth = 2; c.gridx = 1; c.insets = new Insets(5, 5, 5, 10); getContentPane().add(cmbURL, c); c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE; c.insets = new Insets(10, 5, 5, 0); c.gridwidth = 1; c.gridx = 0; c.gridy = 1; getContentPane().add(lblTargetFile, c); c.anchor = GridBagConstraints.CENTER; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(5, 5, 5, 5); c.gridwidth = 1; c.gridx = 1; getContentPane().add(tfdTargetFile, c); c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.NONE; c.insets = new Insets(5, 5, 5, 10); c.gridwidth = 1; c.gridx = 2; getContentPane().add(btnSelectFile, c); c.anchor = GridBagConstraints.CENTER; c.fill = GridBagConstraints.NONE; c.insets = new Insets(10, 10, 10, 10); c.gridwidth = 3; c.gridx = 0; c.gridy = 2; getContentPane().add(cbxExpectHeader, c); c.anchor = GridBagConstraints.CENTER; c.fill = GridBagConstraints.NONE; c.insets = new Insets(10, 10, 10, 10); c.gridwidth = 3; c.gridx = 0; c.gridy = 3; getContentPane().add(btnDoUpload, c); c.anchor = GridBagConstraints.CENTER; c.fill = GridBagConstraints.BOTH; c.insets = new Insets(10, 10, 10, 10); c.gridwidth = 3; c.gridheight = 3; c.weighty = 3; c.gridx = 0; c.gridy = 4; getContentPane().add(new JScrollPane(taTextResponse), c); } private void appendMessage(String m) { taTextResponse.append(m + "\n"); } } } commons-httpclient-3.1/src/examples/PostSOAP.java100644 0 0 10143 10661532626 17241 0ustar 0 0 /* * $Header$ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ import java.io.File; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.FileRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; /** * * This is a sample application that demonstrates * how to use the Jakarta HttpClient API. * * This application sends an XML document * to a remote web server using HTTP POST * * @author Sean C. Sullivan * @author Ortwin Glueck * @author Oleg Kalnichevski * @author Paul King */ public class PostSOAP { /** * * Usage: * java PostSOAP http://mywebserver:80/ SOAPAction c:\foo.xml * * @param args command line arguments * Argument 0 is a URL to a web server * Argument 1 is the SOAP Action * Argument 2 is a local filename * */ public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("Usage: java -classpath [-Dorg.apache.commons.logging.simplelog.defaultlog=] PostSOAP ]"); System.out.println(" - must contain the commons-httpclient.jar and commons-logging.jar"); System.out.println(" - one of error, warn, info, debug, trace"); System.out.println(" - the URL to post the file to"); System.out.println(" - the SOAP action header value"); System.out.println(" - file to post to the URL"); System.out.println(); System.exit(1); } // Get target URL String strURL = args[0]; // Get SOAP action String strSoapAction = args[1]; // Get file to be posted String strXMLFilename = args[2]; File input = new File(strXMLFilename); // Prepare HTTP post PostMethod post = new PostMethod(strURL); // Request content will be retrieved directly // from the input stream RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); // consult documentation for your web service post.setRequestHeader("SOAPAction", strSoapAction); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { int result = httpclient.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response System.out.println("Response body: "); System.out.println(post.getResponseBodyAsString()); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } } } commons-httpclient-3.1/src/examples/PostXML.java100644 0 0 7733 10661532626 17132 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/examples/PostXML.java,v 1.13 2004/05/12 20:43:53 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ import java.io.File; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.FileRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; /** * * This is a sample application that demonstrates * how to use the Jakarta HttpClient API. * * This application sends an XML document * to a remote web server using HTTP POST * * @author Sean C. Sullivan * @author Ortwin Glueck * @author Oleg Kalnichevski */ public class PostXML { /** * * Usage: * java PostXML http://mywebserver:80/ c:\foo.xml * * @param args command line arguments * Argument 0 is a URL to a web server * Argument 1 is a local filename * */ public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Usage: java -classpath [-Dorg.apache.commons.logging.simplelog.defaultlog=] PostXML ]"); System.out.println(" - must contain the commons-httpclient.jar and commons-logging.jar"); System.out.println(" - one of error, warn, info, debug, trace"); System.out.println(" - the URL to post the file to"); System.out.println(" - file to post to the URL"); System.out.println(); System.exit(1); } // Get target URL String strURL = args[0]; // Get file to be posted String strXMLFilename = args[1]; File input = new File(strXMLFilename); // Prepare HTTP post PostMethod post = new PostMethod(strURL); // Request content will be retrieved directly // from the input stream RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { int result = httpclient.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response System.out.println("Response body: "); System.out.println(post.getResponseBodyAsString()); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } } } commons-httpclient-3.1/src/examples/ProxyTunnelDemo.java100644 0 0 10236 10661532626 20750 0ustar 0 0 import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.Socket; import org.apache.commons.httpclient.ProxyClient; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/examples/ProxyTunnelDemo.java,v 1.2 2004/06/12 22:47:23 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ /** * Example code for using {@link org.apache.commons.httpclient.ProxyClient}. * * @author Oleg Kalnichevski * @author Michael Becke */ public class ProxyTunnelDemo { public static void main(String[] args) throws Exception { ProxyClient proxyclient = new ProxyClient(); // set the host the proxy should create a connection to // // Note: By default port 80 will be used. Some proxies only allow conections // to ports 443 and 8443. This is because the HTTP CONNECT method was intented // to be used for tunneling HTTPS. proxyclient.getHostConfiguration().setHost("www.yahoo.com"); // set the proxy host and port proxyclient.getHostConfiguration().setProxy("10.0.1.1", 3128); // set the proxy credentials, only necessary for authenticating proxies proxyclient.getState().setProxyCredentials( new AuthScope("10.0.1.1", 3128, null), new UsernamePasswordCredentials("proxy", "proxy")); // create the socket ProxyClient.ConnectResponse response = proxyclient.connect(); if (response.getSocket() != null) { Socket socket = response.getSocket(); try { // go ahead and do an HTTP GET using the socket Writer out = new OutputStreamWriter( socket.getOutputStream(), "ISO-8859-1"); out.write("GET http://www.yahoo.com/ HTTP/1.1\r\n"); out.write("Host: www.yahoo.com\r\n"); out.write("Agent: whatever\r\n"); out.write("\r\n"); out.flush(); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream(), "ISO-8859-1")); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } } finally { // be sure to close the socket when we're done socket.close(); } } else { // the proxy connect was not successful, check connect method for reasons why System.out.println("Connect failed: " + response.getConnectMethod().getStatusLine()); System.out.println(response.getConnectMethod().getResponseBodyAsString()); } } } commons-httpclient-3.1/src/examples/TrivialApp.java100644 0 0 12523 10661532626 17710 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/examples/TrivialApp.java,v 1.18 2004/06/12 22:47:23 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ import java.io.IOException; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; /** * * This is a simple text mode application that demonstrates * how to use the Jakarta HttpClient API. * * @author Jeff Dever * @author Ortwin Glck */ public class TrivialApp { private static final void printUsage() { System.out.println(); System.out.println("Usage: java -classpath [-Dorg.apache.commons.logging.simplelog.defaultlog=] TrivialApp [ ]"); System.out.println(" - must contain the commons-httpclient.jar and commons-logging.jar"); System.out.println(" - one of error, warn, info, debug, trace"); System.out.println(" - some valid URL"); System.out.println(" - username for protected page"); System.out.println(" - password for protected page"); System.out.println(); } public static void main(String[] args) { if ((args.length != 1) && (args.length != 3)) { printUsage(); System.exit(-1); } Credentials creds = null; if (args.length >= 3) { creds = new UsernamePasswordCredentials(args[1], args[2]); } //create a singular HttpClient object HttpClient client = new HttpClient(); //establish a connection within 5 seconds client.getHttpConnectionManager(). getParams().setConnectionTimeout(5000); //set the default credentials if (creds != null) { client.getState().setCredentials(AuthScope.ANY, creds); } String url = args[0]; HttpMethod method = null; //create a method object method = new GetMethod(url); method.setFollowRedirects(true); //} catch (MalformedURLException murle) { // System.out.println(" argument '" + url // + "' is not a valid URL"); // System.exit(-2); //} //execute the method String responseBody = null; try{ client.executeMethod(method); responseBody = method.getResponseBodyAsString(); } catch (HttpException he) { System.err.println("Http error connecting to '" + url + "'"); System.err.println(he.getMessage()); System.exit(-4); } catch (IOException ioe){ System.err.println("Unable to connect to '" + url + "'"); System.exit(-3); } //write out the request headers System.out.println("*** Request ***"); System.out.println("Request Path: " + method.getPath()); System.out.println("Request Query: " + method.getQueryString()); Header[] requestHeaders = method.getRequestHeaders(); for (int i=0; i. * * [Additional notices, if required by prior licensing conditions] * */ import java.io.File; import java.io.FileInputStream; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; /** * Example how to use unbuffered POST request. * * @author Oleg Kalnichevski */ public class UnbufferedPost { public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: ChunkEncodedPost "); System.out.println(" - full path to a file to be posted"); System.exit(1); } HttpClient client = new HttpClient(); PostMethod httppost = new PostMethod("http://localhost:8080/httpclienttest/body"); File file = new File(args[0]); httppost.setRequestEntity(new InputStreamRequestEntity( new FileInputStream(file), file.length())); try { client.executeMethod(httppost); if (httppost.getStatusCode() == HttpStatus.SC_OK) { System.out.println(httppost.getResponseBodyAsString()); } else { System.out.println("Unexpected failure: " + httppost.getStatusLine().toString()); } } finally { httppost.releaseConnection(); } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/AutoCloseInputStream.java100644 0 0 14257 10661532626 26701 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/AutoCloseInputStream.java,v 1.9 2004/04/18 23:51:34 jsdever Exp $ * $Revision: 505890 $ * $Date: 2007-02-11 12:25:25 +0100 (Sun, 11 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * Closes an underlying stream as soon as the end of the stream is reached, and * notifies a client when it has done so. * * @author Ortwin Glueck * @author Eric Johnson * @author Mike Bowler * * @since 2.0 */ class AutoCloseInputStream extends FilterInputStream { /** * True if this stream is open. Assume that the underlying stream * is open until we get an EOF indication. */ private boolean streamOpen = true; /** True if the stream closed itself. */ private boolean selfClosed = false; /** * The watcher is notified when the contents of the stream have * been exhausted */ private ResponseConsumedWatcher watcher = null; /** * Create a new auto closing stream for the provided connection * * @param in the input stream to read from * @param watcher To be notified when the contents of the stream have been * consumed. */ public AutoCloseInputStream( final InputStream in, final ResponseConsumedWatcher watcher) { super(in); this.watcher = watcher; } /** * Reads the next byte of data from the input stream. * * @throws IOException when there is an error reading * @return the character read, or -1 for EOF */ public int read() throws IOException { int l = -1; if (isReadAllowed()) { // underlying stream not closed, go ahead and read. l = super.read(); checkClose(l); } return l; } /** * Reads up to len bytes of data from the stream. * * @param b a byte array to read data into * @param off an offset within the array to store data * @param len the maximum number of bytes to read * @return the number of bytes read or -1 for EOF * @throws IOException if there are errors reading */ public int read(byte[] b, int off, int len) throws IOException { int l = -1; if (isReadAllowed()) { l = super.read(b, off, len); checkClose(l); } return l; } /** * Reads some number of bytes from the input stream and stores them into the * buffer array b. * * @param b a byte array to read data into * @return the number of bytes read or -1 for EOF * @throws IOException if there are errors reading */ public int read(byte[] b) throws IOException { int l = -1; if (isReadAllowed()) { l = super.read(b); checkClose(l); } return l; } /** * Obtains the number of bytes that can be read without blocking. * * @return the number of bytes available without blocking * @throws IOException in case of a problem */ public int available() throws IOException { int a = 0; // not -1 if (isReadAllowed()) { a = super.available(); // no checkClose() here, available() can't trigger EOF } return a; } /** * Close the stream, and also close the underlying stream if it is not * already closed. * @throws IOException If an IO problem occurs. */ public void close() throws IOException { if (!selfClosed) { selfClosed = true; notifyWatcher(); } } /** * Close the underlying stream should the end of the stream arrive. * * @param readResult The result of the read operation to check. * @throws IOException If an IO problem occurs. */ private void checkClose(int readResult) throws IOException { if (readResult == -1) { notifyWatcher(); } } /** * See whether a read of the underlying stream should be allowed, and if * not, check to see whether our stream has already been closed! * * @return true if it is still OK to read from the stream. * @throws IOException If an IO problem occurs. */ private boolean isReadAllowed() throws IOException { if (!streamOpen && selfClosed) { throw new IOException("Attempted read on closed stream."); } return streamOpen; } /** * Notify the watcher that the contents have been consumed. * @throws IOException If an IO problem occurs. */ private void notifyWatcher() throws IOException { if (streamOpen) { super.close(); streamOpen = false; if (watcher != null) { watcher.responseConsumed(); } } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/ChunkedInputStream.java100644 0 0 30411 10661532627 26353 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ChunkedInputStream.java,v 1.24 2004/10/10 15:18:55 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.util.EncodingUtil; import org.apache.commons.httpclient.util.ExceptionUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

Transparently coalesces chunks of a HTTP stream that uses * Transfer-Encoding chunked.

* *

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 invocation of subsequent HTTP 1.1 calls, while * not requiring the client to remember to read the entire contents of the * response.

* * @author Ortwin Glueck * @author Sean C. Sullivan * @author Martin Elwin * @author Eric Johnson * @author Mike Bowler * @author Michael Becke * @author Oleg Kalnichevski * * @since 2.0 * */ public class ChunkedInputStream extends InputStream { /** The inputstream that we're wrapping */ private InputStream in; /** The chunk size */ private int chunkSize; /** The current position within the current chunk */ private int pos; /** True if we'are at the beginning of stream */ private boolean bof = true; /** True if we've reached the end of stream */ private boolean eof = false; /** True if this stream is closed */ private boolean closed = false; /** The method that this stream came from */ private HttpMethod method = null; /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(ChunkedInputStream.class); /** * ChunkedInputStream constructor that associates the chunked input stream with a * {@link HttpMethod HTTP method}. Usually it should be the same {@link HttpMethod * HTTP method} the chunked input stream originates from. If chunked input stream * contains any footers (trailing headers), they will be added to the associated * {@link HttpMethod HTTP method}. * * @param in the raw input stream * @param method the HTTP method to associate this input stream with. Can be null. * * @throws IOException If an IO error occurs */ public ChunkedInputStream( final InputStream in, final HttpMethod method) throws IOException { if (in == null) { throw new IllegalArgumentException("InputStream parameter may not be null"); } this.in = in; this.method = method; this.pos = 0; } /** * ChunkedInputStream constructor * * @param in the raw input stream * * @throws IOException If an IO error occurs */ public ChunkedInputStream(final InputStream in) throws IOException { this(in, null); } /** *

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 automcatically 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 If an IO problem occurs * * @see HttpMethod#getResponseFooters() */ public int read() throws IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (eof) { return -1; } if (pos >= chunkSize) { nextChunk(); if (eof) { return -1; } } pos++; return in.read(); } /** * 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. * @see java.io.InputStream#read(byte[], int, int) * @throws IOException if an IO problem occurs. */ public int read (byte[] b, int off, int len) throws IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (eof) { return -1; } if (pos >= chunkSize) { nextChunk(); if (eof) { return -1; } } len = Math.min(len, chunkSize - pos); int count = in.read(b, off, len); pos += count; return count; } /** * 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. * @see java.io.InputStream#read(byte[]) * @throws IOException if an IO problem occurs. */ public int read (byte[] b) throws IOException { return read(b, 0, b.length); } /** * Read the CRLF terminator. * @throws IOException If an IO error occurs. */ private void readCRLF() throws IOException { int cr = in.read(); int lf = in.read(); if ((cr != '\r') || (lf != '\n')) { throw new IOException( "CRLF expected at end of chunk: " + cr + "/" + lf); } } /** * Read the next chunk. * @throws IOException If an IO error occurs. */ private void nextChunk() throws IOException { if (!bof) { readCRLF(); } chunkSize = getChunkSizeFromInputStream(in); bof = false; pos = 0; if (chunkSize == 0) { eof = true; parseTrailerHeaders(); } } /** * Expects the stream to start with a chunksize in hex with optional * comments after a semicolon. The line must end with a CRLF: "a3; some * comment\r\n" Positions the stream at the start of the next line. * * @param in The new input stream. * @param required true if a valid chunk must be present, * false otherwise. * * @return the chunk size as integer * * @throws IOException when the chunk size could not be parsed */ private static int getChunkSizeFromInputStream(final InputStream in) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); // States: 0=normal, 1=\r was scanned, 2=inside quoted string, -1=end int state = 0; while (state != -1) { int b = in.read(); if (b == -1) { throw new IOException("chunked stream ended unexpectedly"); } switch (state) { case 0: switch (b) { case '\r': state = 1; break; case '\"': state = 2; /* fall through */ default: baos.write(b); } break; case 1: if (b == '\n') { state = -1; } else { // this was not CRLF throw new IOException("Protocol violation: Unexpected" + " single newline character in chunk size"); } break; case 2: switch (b) { case '\\': b = in.read(); baos.write(b); break; case '\"': state = 0; /* fall through */ default: baos.write(b); } break; default: throw new RuntimeException("assertion failed"); } } //parse data String dataString = EncodingUtil.getAsciiString(baos.toByteArray()); int separator = dataString.indexOf(';'); dataString = (separator > 0) ? dataString.substring(0, separator).trim() : dataString.trim(); int result; try { result = Integer.parseInt(dataString.trim(), 16); } catch (NumberFormatException e) { throw new IOException ("Bad chunk size: " + dataString); } return result; } /** * Reads and stores the Trailer headers. * @throws IOException If an IO problem occurs */ private void parseTrailerHeaders() throws IOException { Header[] footers = null; try { String charset = "US-ASCII"; if (this.method != null) { charset = this.method.getParams().getHttpElementCharset(); } footers = HttpParser.parseHeaders(in, charset); } catch(HttpException e) { LOG.error("Error parsing trailer headers", e); IOException ioe = new IOException(e.getMessage()); ExceptionUtil.initCause(ioe, e); throw ioe; } if (this.method != null) { for (int i = 0; i < footers.length; i++) { this.method.addResponseFooter(footers[i]); } } } /** * 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 If an IO problem occurs. */ public void close() throws IOException { if (!closed) { try { if (!eof) { exhaustInputStream(this); } } finally { eof = true; closed = true; } } } /** * Exhaust an input stream, reading until EOF has been encountered. * *

Note that this function is intended as a non-public utility. * This is a little weird, but it seemed silly to make a utility * class for this one function, so instead it is just static and * shared that way.

* * @param inStream The {@link InputStream} to exhaust. * @throws IOException If an IO problem occurs */ static void exhaustInputStream(InputStream inStream) throws IOException { // read and discard the remainder of the message byte buffer[] = new byte[1024]; while (inStream.read(buffer) >= 0) { ; } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/ChunkedOutputStream.java100644 0 0 15335 10661532626 26563 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ChunkedOutputStream.java,v 1.16 2004/05/13 04:03:25 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.httpclient.util.EncodingUtil; /** * Implements HTTP chunking support. Writes are buffered to an internal buffer (2048 default size). * Chunks are guaranteed to be at least as large as the buffer size (except for the last chunk). * * @author Mohammad Rezaei, Goldman, Sachs & Co. */ public class ChunkedOutputStream extends OutputStream { // ------------------------------------------------------- Static Variables private static final byte CRLF[] = new byte[] {(byte) 13, (byte) 10}; /** End chunk */ private static final byte ENDCHUNK[] = CRLF; /** 0 */ private static final byte ZERO[] = new byte[] {(byte) '0'}; // ----------------------------------------------------- Instance Variables private OutputStream stream = null; private byte[] cache; private int cachePosition = 0; private boolean wroteLastChunk = false; // ----------------------------------------------------------- Constructors /** * Wraps a stream and chunks the output. * @param stream to wrap * @param bufferSize minimum chunk size (excluding last chunk) * @throws IOException * * @since 3.0 */ public ChunkedOutputStream(OutputStream stream, int bufferSize) throws IOException { this.cache = new byte[bufferSize]; this.stream = stream; } /** * Wraps a stream and chunks the output. The default buffer size of 2048 was chosen because * the chunk overhead is less than 0.5% * @param stream * @throws IOException */ public ChunkedOutputStream(OutputStream stream) throws IOException { this(stream, 2048); } // ----------------------------------------------------------- Internal methods /** * Writes the cache out onto the underlying stream * @throws IOException * * @since 3.0 */ protected void flushCache() throws IOException { if (cachePosition > 0) { byte chunkHeader[] = EncodingUtil.getAsciiBytes( Integer.toHexString(cachePosition) + "\r\n"); stream.write(chunkHeader, 0, chunkHeader.length); stream.write(cache, 0, cachePosition); stream.write(ENDCHUNK, 0, ENDCHUNK.length); cachePosition = 0; } } /** * Writes the cache and bufferToAppend to the underlying stream * as one large chunk * @param bufferToAppend * @param off * @param len * @throws IOException * * @since 3.0 */ protected void flushCacheWithAppend(byte bufferToAppend[], int off, int len) throws IOException { byte chunkHeader[] = EncodingUtil.getAsciiBytes( Integer.toHexString(cachePosition + len) + "\r\n"); stream.write(chunkHeader, 0, chunkHeader.length); stream.write(cache, 0, cachePosition); stream.write(bufferToAppend, off, len); stream.write(ENDCHUNK, 0, ENDCHUNK.length); cachePosition = 0; } protected void writeClosingChunk() throws IOException { // Write the final chunk. stream.write(ZERO, 0, ZERO.length); stream.write(CRLF, 0, CRLF.length); stream.write(ENDCHUNK, 0, ENDCHUNK.length); } // ----------------------------------------------------------- Public Methods /** * Must be called to ensure the internal cache is flushed and the closing chunk is written. * @throws IOException * * @since 3.0 */ public void finish() throws IOException { if (!wroteLastChunk) { flushCache(); writeClosingChunk(); wroteLastChunk = true; } } // -------------------------------------------- OutputStream Methods /** * Write the specified byte to our output stream. * * Note: Avoid this method as it will cause an inefficient single byte chunk. * Use write (byte[], int, int) instead. * * @param b The byte to be written * @throws IOException if an input/output error occurs */ public void write(int b) throws IOException { cache[cachePosition] = (byte) b; cachePosition++; if (cachePosition == 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. * @param b * @throws IOException * * @since 3.0 */ public void write(byte b[]) throws IOException { this.write(b, 0, b.length); } public void write(byte src[], int off, int len) throws IOException { if (len >= cache.length - cachePosition) { flushCacheWithAppend(src, off, len); } else { System.arraycopy(src, off, cache, cachePosition, len); cachePosition += len; } } /** * Flushes the underlying stream, but leaves the internal buffer alone. * @throws IOException */ public void flush() throws IOException { stream.flush(); } /** * Finishes writing to the underlying stream, but does NOT close the underlying stream. * @throws IOException */ public void close() throws IOException { finish(); super.close(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/CircularRedirectException.java100644 0 0 5004 10661532626 27662 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/CircularRedirectException.java,v 1.1 2005/01/14 19:40:39 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * Signals a circular redirect * * @author Oleg Kalnichevski * * @since 3.0 */ public class CircularRedirectException extends RedirectException { /** * Creates a new CircularRedirectException with a null detail message. */ public CircularRedirectException() { super(); } /** * Creates a new CircularRedirectException with the specified detail message. * * @param message The exception detail message */ public CircularRedirectException(String message) { super(message); } /** * Creates a new CircularRedirectException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public CircularRedirectException(String message, Throwable cause) { super(message, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/ConnectMethod.java100644 0 0 21501 10661532626 25327 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ConnectMethod.java,v 1.29 2004/06/24 21:39:52 mbecke Exp $ * $Revision: 483949 $ * $Date: 2006-12-08 12:34:50 +0100 (Fri, 08 Dec 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Establishes a tunneled HTTP connection via the CONNECT method. * * @author Ortwin Gl???ck * @author dIon Gillard * @author Mike Bowler * @author Oleg Kalnichevski * @since 2.0 * @version $Revision: 483949 $ $Date: 2006-12-08 12:34:50 +0100 (Fri, 08 Dec 2006) $ */ public class ConnectMethod extends HttpMethodBase { /** the name of this method */ public static final String NAME = "CONNECT"; private final HostConfiguration targethost; /** * @deprecated use #ConnectMethod(HttpHost); * * Create a connect method. * * @since 3.0 */ public ConnectMethod() { super(); this.targethost = null; } /** * @deprecated the wrapped method is no longer used * * Create a connect method wrapping the existing method * * @param method the {@link HttpMethod method} to execute after connecting * to the server */ public ConnectMethod(HttpMethod method) { super(); this.targethost = null; } /** * Create a connect method. * * @since 3.0 */ public ConnectMethod(final HostConfiguration targethost) { super(); if (targethost == null) { throw new IllegalArgumentException("Target host may not be null"); } this.targethost = targethost; } /** * Provide the {@link #NAME name} of this method. * * @return the String "CONNECT" */ public String getName() { return NAME; } public String getPath() { if (this.targethost != null) { StringBuffer buffer = new StringBuffer(); buffer.append(this.targethost.getHost()); int port = this.targethost.getPort(); if (port == -1) { port = this.targethost.getProtocol().getDefaultPort(); } buffer.append(':'); buffer.append(port); return buffer.toString(); } else { return "/"; } } public URI getURI() throws URIException { String charset = getParams().getUriCharset(); return new URI(getPath(), true, charset); } /** * This method does nothing. CONNECT request is not supposed * to contain Cookie request header. * * @param state current state of http requests * @param conn the connection to use for I/O * * @throws IOException when errors occur reading or writing to/from the * connection * @throws HttpException when a recoverable error occurs * * @see HttpMethodBase#addCookieRequestHeader(HttpState, HttpConnection) */ protected void addCookieRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { // Do nothing. Not applicable to CONNECT method } /** * Populates the request headers map to with additional {@link Header * headers} to be submitted to the given {@link HttpConnection}. * *

* This implementation adds User-Agent, Host, * and Proxy-Authorization headers, when appropriate. *

* * @param state the client state * @param conn the {@link HttpConnection} the headers will eventually be * written to * @throws IOException when an error occurs writing the request * @throws HttpException when a HTTP protocol error occurs * * @see #writeRequestHeaders */ protected void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter ConnectMethod.addRequestHeaders(HttpState, " + "HttpConnection)"); addUserAgentRequestHeader(state, conn); addHostRequestHeader(state, conn); addProxyConnectionHeader(state, conn); } /** * Execute this method and create a tunneled HttpConnection. If the method * is successful (i.e. the status is a 2xx) tunnelCreated() will be called * on the connection. * * @param state the current http state * @param conn the connection to write to * @return the http status code from execution * @throws HttpException when an error occurs writing the headers * @throws IOException when an error occurs writing the headers * * @see HttpConnection#tunnelCreated() */ public int execute(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter ConnectMethod.execute(HttpState, HttpConnection)"); int code = super.execute(state, conn); if (LOG.isDebugEnabled()) { LOG.debug("CONNECT status code " + code); } return code; } /** * Special Connect request. * * @param state the current http state * @param conn the connection to write to * @throws IOException when an error occurs writing the request * @throws HttpException when an error occurs writing the request */ protected void writeRequestLine(HttpState state, HttpConnection conn) throws IOException, HttpException { StringBuffer buffer = new StringBuffer(); buffer.append(getName()); buffer.append(' '); if (this.targethost != null) { buffer.append(getPath()); } else { int port = conn.getPort(); if (port == -1) { port = conn.getProtocol().getDefaultPort(); } buffer.append(conn.getHost()); buffer.append(':'); buffer.append(port); } buffer.append(" "); buffer.append(getEffectiveVersion()); String line = buffer.toString(); conn.printLine(line, getParams().getHttpElementCharset()); if (Wire.HEADER_WIRE.enabled()) { Wire.HEADER_WIRE.output(line); } } /** * Returns true if the status code is anything other than * SC_OK, false otherwise. * * @see HttpMethodBase#shouldCloseConnection(HttpConnection) * @see HttpStatus#SC_OK * * @return true if the connection should be closed */ protected boolean shouldCloseConnection(HttpConnection conn) { if (getStatusCode() == HttpStatus.SC_OK) { Header connectionHeader = null; if (!conn.isTransparent()) { connectionHeader = getResponseHeader("proxy-connection"); } if (connectionHeader == null) { connectionHeader = getResponseHeader("connection"); } if (connectionHeader != null) { if (connectionHeader.getValue().equalsIgnoreCase("close")) { if (LOG.isWarnEnabled()) { LOG.warn("Invalid header encountered '" + connectionHeader.toExternalForm() + "' in response " + getStatusLine().toString()); } } } return false; } else { return super.shouldCloseConnection(conn); } } /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(ConnectMethod.class); } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/ConnectTimeoutException.java100644 0 0 5450 10661532626 27401 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ConnectTimeoutException.java,v 1.5 2004/07/05 22:46:58 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.InterruptedIOException; import org.apache.commons.httpclient.util.ExceptionUtil; /** * A timeout while connecting to an HTTP server or waiting for an * available connection from an HttpConnectionManager. * * @author Laura Werner * * @since 3.0 */ public class ConnectTimeoutException extends InterruptedIOException { /** * Creates a ConnectTimeoutException with a null detail message. */ public ConnectTimeoutException() { super(); } /** * Creates a ConnectTimeoutException with the specified detail message. * * @param message The exception detail message */ public ConnectTimeoutException(String message) { super(message); } /** * Creates a new ConnectTimeoutException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public ConnectTimeoutException(String message, Throwable cause) { super(message); // If we're running on JDK 1.4 or later, tell Throwable what the cause was ExceptionUtil.initCause(this, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/ConnectionPoolTimeoutException.java100644 0 0 5134 10661532627 30741 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ConnectionPoolTimeoutException.java,v 1.1 2004/07/05 22:46:58 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * A timeout while connecting waiting for an available connection * from an HttpConnectionManager. * * @author Laura Werner * * @since 3.0 */ public class ConnectionPoolTimeoutException extends ConnectTimeoutException { /** * Creates a ConnectTimeoutException with a null detail message. */ public ConnectionPoolTimeoutException() { super(); } /** * Creates a ConnectTimeoutException with the specified detail message. * * @param message The exception detail message */ public ConnectionPoolTimeoutException(String message) { super(message); } /** * Creates a new ConnectTimeoutException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public ConnectionPoolTimeoutException(String message, Throwable cause) { super(message, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/ContentLengthInputStream.java100644 0 0 17100 10661532626 27545 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ContentLengthInputStream.java,v 1.12 2004/10/04 22:05:44 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InputStream; /** * Cuts the wrapped InputStream off after a specified number of bytes. * *

Implementation note: Choices abound. One approach would pass * through the {@link InputStream#mark} and {@link InputStream#reset} calls to * the underlying stream. That's tricky, though, because you then have to * start duplicating the work of keeping track of how much a reset rewinds. * Further, you have to watch out for the "readLimit", and since the semantics * for the readLimit leave room for differing implementations, you might get * into a lot of trouble.

* *

Alternatively, you could make this class extend {@link java.io.BufferedInputStream} * and then use the protected members of that class to avoid duplicated effort. * That solution has the side effect of adding yet another possible layer of * buffering.

* *

Then, there is the simple choice, which this takes - simply don't * support {@link InputStream#mark} and {@link InputStream#reset}. That choice * has the added benefit of keeping this class very simple.

* * @author Ortwin Glueck * @author Eric Johnson * @author Mike Bowler * @since 2.0 */ public class ContentLengthInputStream extends InputStream { /** * The maximum number of bytes that can be read from the stream. Subsequent * read operations will return -1. */ private 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 InputStream wrappedStream = null; /** * @deprecated use {@link #ContentLengthInputStream(InputStream, long)} * * Creates a new length limited stream * * @param in The stream to wrap * @param contentLength The maximum number of bytes that can be read from * the stream. Subsequent read operations will return -1. */ public ContentLengthInputStream(InputStream in, int contentLength) { this(in, (long)contentLength); } /** * Creates a new length limited stream * * @param in The stream to wrap * @param contentLength The maximum number of bytes that can be read from * the stream. Subsequent read operations will return -1. * * @since 3.0 */ public ContentLengthInputStream(InputStream in, long contentLength) { super(); this.wrappedStream = in; this.contentLength = contentLength; } /** *

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. */ public void close() throws IOException { if (!closed) { try { ChunkedInputStream.exhaustInputStream(this); } finally { // close after above so that we don't throw an exception trying // to read after closed! closed = true; } } } /** * 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() */ public int read() throws IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (pos >= contentLength) { return -1; } pos++; return this.wrappedStream.read(); } /** * 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. */ public int read (byte[] b, int off, int len) throws java.io.IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (pos >= contentLength) { return -1; } if (pos + len > contentLength) { len = (int) (contentLength - pos); } int count = this.wrappedStream.read(b, off, len); 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[]) */ public int read(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) */ public long skip(long n) throws IOException { // make sure we don't skip more bytes than are // still available long length = Math.min(n, contentLength - pos); // skip and keep track of the bytes actually skipped length = this.wrappedStream.skip(length); // only add the skipped bytes to the current position // if bytes were actually skipped if (length > 0) { pos += length; } return length; } public int available() throws IOException { if (this.closed) { return 0; } int avail = this.wrappedStream.available(); if (this.pos + avail > this.contentLength ) { avail = (int)(this.contentLength - this.pos); } return avail; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/Cookie.java100644 0 0 41242 10661532626 24012 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Cookie.java,v 1.44 2004/06/05 16:49:20 olegk Exp $ * $Revision: 531354 $ * $Date: 2007-04-23 08:53:20 +0200 (Mon, 23 Apr 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.Serializable; import java.util.Comparator; import java.util.Date; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.util.LangUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

* HTTP "magic-cookie" represents a piece of state information * that the HTTP agent and the target server can exchange to maintain * a session. *

* * @author B.C. Holmes * @author Park, Sung-Gu * @author Doug Sale * @author Rod Waldhoff * @author dIon Gillard * @author Sean C. Sullivan * @author John Evans * @author Marc A. Saegesser * @author Oleg Kalnichevski * @author Mike Bowler * * @version $Revision: 531354 $ $Date: 2007-04-23 08:53:20 +0200 (Mon, 23 Apr 2007) $ */ public class Cookie extends NameValuePair implements Serializable, Comparator { // ----------------------------------------------------------- Constructors /** * Default constructor. Creates a blank cookie */ public Cookie() { this(null, "noname", null, null, null, false); } /** * Creates a cookie with the given name, value and domain attribute. * * @param name the cookie name * @param value the cookie value * @param domain the domain this cookie can be sent to */ public Cookie(String domain, String name, String value) { this(domain, name, value, null, null, false); } /** * Creates a cookie with the given name, value, domain attribute, * path attribute, expiration attribute, and secure attribute * * @param name the cookie name * @param value the cookie value * @param domain the domain this cookie can be sent to * @param path the path prefix for which this cookie can be sent * @param expires the {@link Date} at which this cookie expires, * or null if the cookie expires at the end * of the session * @param secure if true this cookie can only be sent over secure * connections * @throws IllegalArgumentException If cookie name is null or blank, * cookie name contains a blank, or cookie name starts with character $ * */ public Cookie(String domain, String name, String value, String path, Date expires, boolean secure) { super(name, value); LOG.trace("enter Cookie(String, String, String, String, Date, boolean)"); if (name == null) { throw new IllegalArgumentException("Cookie name may not be null"); } if (name.trim().equals("")) { throw new IllegalArgumentException("Cookie name may not be blank"); } this.setPath(path); this.setDomain(domain); this.setExpiryDate(expires); this.setSecure(secure); } /** * Creates a cookie with the given name, value, domain attribute, * path attribute, maximum age attribute, and secure attribute * * @param name the cookie name * @param value the cookie value * @param domain the domain this cookie can be sent to * @param path the path prefix for which this cookie can be sent * @param maxAge the number of seconds for which this cookie is valid. * maxAge is expected to be a non-negative number. * -1 signifies that the cookie should never expire. * @param secure if true this cookie can only be sent over secure * connections */ public Cookie(String domain, String name, String value, String path, int maxAge, boolean secure) { this(domain, name, value, path, null, secure); if (maxAge < -1) { throw new IllegalArgumentException("Invalid max age: " + Integer.toString(maxAge)); } if (maxAge >= 0) { setExpiryDate(new Date(System.currentTimeMillis() + maxAge * 1000L)); } } /** * Returns the comment describing the purpose of this cookie, or * null if no such comment has been defined. * * @return comment * * @see #setComment(String) */ public String getComment() { return cookieComment; } /** * If a user agent (web browser) presents this cookie to a user, the * cookie's purpose will be described using this comment. * * @param comment * * @see #getComment() */ public void setComment(String comment) { cookieComment = comment; } /** * Returns the expiration {@link Date} of the cookie, or null * if none exists. *

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

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

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

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

* When true the cookie should only be sent * using a secure protocol (https). This should only be set when * the cookie's originating server used a secure protocol to set the * cookie's value. * * @param secure The value of the secure attribute * * @see #getSecure() */ public void setSecure (boolean secure) { isSecure = secure; } /** * Returns the version of the cookie specification to which this * cookie conforms. * * @return the version of the cookie. * * @see #setVersion(int) * */ public int getVersion() { return cookieVersion; } /** * Sets the version of the cookie specification to which this * cookie conforms. * * @param version the version of the cookie. * * @see #getVersion */ public void setVersion(int version) { cookieVersion = version; } /** * Returns true if this cookie has expired. * * @return true if the cookie has expired. */ public boolean isExpired() { return (cookieExpiryDate != null && cookieExpiryDate.getTime() <= System.currentTimeMillis()); } /** * Returns true if this cookie has expired according to the time passed in. * * @param now The current time. * * @return true if the cookie expired. */ public boolean isExpired(Date now) { return (cookieExpiryDate != null && cookieExpiryDate.getTime() <= now.getTime()); } /** * Indicates whether the cookie had a path specified in a * path attribute of the Set-Cookie header. This value * is important for generating the Cookie header because * some cookie specifications require that the Cookie header * should only include a path attribute if the cookie's path * was specified in the Set-Cookie header. * * @param value true if the cookie's path was explicitly * set, false otherwise. * * @see #isPathAttributeSpecified */ public void setPathAttributeSpecified(boolean value) { hasPathAttribute = value; } /** * Returns true if cookie's path was set via a path attribute * in the Set-Cookie header. * * @return value true if the cookie's path was explicitly * set, false otherwise. * * @see #setPathAttributeSpecified */ public boolean isPathAttributeSpecified() { return hasPathAttribute; } /** * Indicates whether the cookie had a domain specified in a * domain attribute of the Set-Cookie header. This value * is important for generating the Cookie header because * some cookie specifications require that the Cookie header * should only include a domain attribute if the cookie's domain * was specified in the Set-Cookie header. * * @param value true if the cookie's domain was explicitly * set, false otherwise. * * @see #isDomainAttributeSpecified */ public void setDomainAttributeSpecified(boolean value) { hasDomainAttribute = value; } /** * Returns true if cookie's domain was set via a domain * attribute in the Set-Cookie header. * * @return value true if the cookie's domain was explicitly * set, false otherwise. * * @see #setDomainAttributeSpecified */ public boolean isDomainAttributeSpecified() { return hasDomainAttribute; } /** * Returns a hash code in keeping with the * {@link Object#hashCode} general hashCode contract. * @return A hash code */ public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.getName()); hash = LangUtils.hashCode(hash, this.cookieDomain); hash = LangUtils.hashCode(hash, this.cookiePath); return hash; } /** * Two cookies are equal if the name, path and domain match. * @param obj The object to compare against. * @return true if the two objects are equal. */ public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (obj instanceof Cookie) { Cookie that = (Cookie) obj; return LangUtils.equals(this.getName(), that.getName()) && LangUtils.equals(this.cookieDomain, that.cookieDomain) && LangUtils.equals(this.cookiePath, that.cookiePath); } else { return false; } } /** * Return a textual representation of the cookie. * * @return string. */ public String toExternalForm() { CookieSpec spec = null; if (getVersion() > 0) { spec = CookiePolicy.getDefaultSpec(); } else { spec = CookiePolicy.getCookieSpec(CookiePolicy.NETSCAPE); } return spec.formatCookie(this); } /** *

Compares two cookies to determine order for cookie header.

*

Most specific should be first.

*

This method is implemented so a cookie can be used as a comparator for * a SortedSet of cookies. Specifically it's used above in the * createCookieHeader method.

* @param o1 The first object to be compared * @param o2 The second object to be compared * @return See {@link java.util.Comparator#compare(Object,Object)} */ public int compare(Object o1, Object o2) { LOG.trace("enter Cookie.compare(Object, Object)"); if (!(o1 instanceof Cookie)) { throw new ClassCastException(o1.getClass().getName()); } if (!(o2 instanceof Cookie)) { throw new ClassCastException(o2.getClass().getName()); } Cookie c1 = (Cookie) o1; Cookie c2 = (Cookie) o2; if (c1.getPath() == null && c2.getPath() == null) { return 0; } else if (c1.getPath() == null) { // null is assumed to be "/" if (c2.getPath().equals(CookieSpec.PATH_DELIM)) { return 0; } else { return -1; } } else if (c2.getPath() == null) { // null is assumed to be "/" if (c1.getPath().equals(CookieSpec.PATH_DELIM)) { return 0; } else { return 1; } } else { return c1.getPath().compareTo(c2.getPath()); } } /** * Return a textual representation of the cookie. * * @return string. * * @see #toExternalForm */ public String toString() { return toExternalForm(); } // ----------------------------------------------------- Instance Variables /** Comment attribute. */ private String cookieComment; /** Domain attribute. */ private String cookieDomain; /** Expiration {@link Date}. */ private Date cookieExpiryDate; /** Path attribute. */ private String cookiePath; /** My secure flag. */ private boolean isSecure; /** * Specifies if the set-cookie header included a Path attribute for this * cookie */ private boolean hasPathAttribute = false; /** * Specifies if the set-cookie header included a Domain attribute for this * cookie */ private boolean hasDomainAttribute = false; /** The version of the cookie specification I was created from. */ private int cookieVersion = 0; // -------------------------------------------------------------- Constants /** Log object for this class */ private static final Log LOG = LogFactory.getLog(Cookie.class); } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/Credentials.java100644 0 0 3520 10661532626 25013 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Credentials.java,v 1.9 2004/04/18 23:51:34 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** *

Authentication credentials.

*

* This is just a marker interface, the current implementation has no methods. *

* @author Unascribed * @author Mike Bowler * * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ */ public interface Credentials { } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/DefaultHttpMethodRetryHandler.java100644 0 0 12641 10661532627 30514 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/DefaultHttpMethodRetryHandler.java,v 1.3 2004/12/20 11:47:46 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InterruptedIOException; import java.net.NoRouteToHostException; import java.net.UnknownHostException; /** * The default {@link HttpMethodRetryHandler} used by {@link HttpMethod}s. * * @author Michael Becke * @author Oleg Kalnichevski */ public class DefaultHttpMethodRetryHandler implements HttpMethodRetryHandler { private static Class SSL_HANDSHAKE_EXCEPTION = null; static { try { SSL_HANDSHAKE_EXCEPTION = Class.forName("javax.net.ssl.SSLHandshakeException"); } catch (ClassNotFoundException ignore) { } } /** the number of times a method will be retried */ private int retryCount; /** Whether or not methods that have successfully sent their request will be retried */ private boolean requestSentRetryEnabled; /** * Creates a new DefaultHttpMethodRetryHandler. * @param retryCount the number of times a method will be retried * @param requestSentRetryEnabled if true, methods that have successfully sent their request will be retried */ public DefaultHttpMethodRetryHandler(int retryCount, boolean requestSentRetryEnabled) { super(); this.retryCount = retryCount; this.requestSentRetryEnabled = requestSentRetryEnabled; } /** * Creates a new DefaultHttpMethodRetryHandler that retries up to 3 times * but does not retry methods that have successfully sent their requests. */ public DefaultHttpMethodRetryHandler() { this(3, false); } /** * Used retryCount and requestSentRetryEnabled to determine * if the given method should be retried. * * @see HttpMethodRetryHandler#retryMethod(HttpMethod, IOException, int) */ public boolean retryMethod( final HttpMethod method, final IOException exception, int executionCount) { if (method == null) { throw new IllegalArgumentException("HTTP method may not be null"); } if (exception == null) { throw new IllegalArgumentException("Exception parameter may not be null"); } // HttpMethod interface is the WORST thing ever done to HttpClient if (method instanceof HttpMethodBase) { if (((HttpMethodBase)method).isAborted()) { return false; } } if (executionCount > this.retryCount) { // Do not retry if over max retry count return false; } if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } if (exception instanceof InterruptedIOException) { // Timeout return false; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof NoRouteToHostException) { // Host unreachable return false; } if (SSL_HANDSHAKE_EXCEPTION != null && SSL_HANDSHAKE_EXCEPTION.isInstance(exception)) { // SSL handshake exception return false; } if (!method.isRequestSent() || this.requestSentRetryEnabled) { // Retry if the request has not been sent fully or // if it's OK to retry methods that have been sent return true; } // otherwise do not retry return false; } /** * @return true if this handler will retry methods that have * successfully sent their request, false otherwise */ public boolean isRequestSentRetryEnabled() { return requestSentRetryEnabled; } /** * @return the maximum number of times a method will be retried */ public int getRetryCount() { return retryCount; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/DefaultMethodRetryHandler.java100644 0 0 7175 10661532626 27641 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/DefaultMethodRetryHandler.java,v 1.4 2004/07/05 22:46:58 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * The default MethodRetryHandler used by HttpMethodBase. * * @author Michael Becke * * @see HttpMethodBase#setMethodRetryHandler(MethodRetryHandler) * * @deprecated use {@link org.apache.commons.httpclient.DefaultHttpMethodRetryHandler} */ public class DefaultMethodRetryHandler implements MethodRetryHandler { /** the number of times a method will be retried */ private int retryCount; /** Whether or not methods that have successfully sent their request will be retried */ private boolean requestSentRetryEnabled; /** */ public DefaultMethodRetryHandler() { this.retryCount = 3; this.requestSentRetryEnabled = false; } /** * Used retryCount and requestSentRetryEnabled to determine * if the given method should be retried. * * @see MethodRetryHandler#retryMethod(HttpMethod, HttpConnection, HttpRecoverableException, int, boolean) */ public boolean retryMethod( HttpMethod method, HttpConnection connection, HttpRecoverableException recoverableException, int executionCount, boolean requestSent ) { return ((!requestSent || requestSentRetryEnabled) && (executionCount <= retryCount)); } /** * @return true if this handler will retry methods that have * successfully sent their request, false otherwise */ public boolean isRequestSentRetryEnabled() { return requestSentRetryEnabled; } /** * @return the maximum number of times a method will be retried */ public int getRetryCount() { return retryCount; } /** * @param requestSentRetryEnabled a flag indicating if methods that have * successfully sent their request should be retried */ public void setRequestSentRetryEnabled(boolean requestSentRetryEnabled) { this.requestSentRetryEnabled = requestSentRetryEnabled; } /** * @param retryCount the maximum number of times a method can be retried */ public void setRetryCount(int retryCount) { this.retryCount = retryCount; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/Header.java100644 0 0 10445 10661532626 23772 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Header.java,v 1.17 2004/09/15 20:42:17 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** *

An HTTP header.

* * @author Remy Maucherat * @author Mike Bowler * @author Oleg Kalnichevski * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ */ public class Header extends NameValuePair { // ----------------------------------------------------------- Constructors /** * Autogenerated header flag. */ private boolean isAutogenerated = false; /** * Default constructor. */ public Header() { this(null, null); } /** * Constructor with name and value * * @param name the header name * @param value the header value */ public Header(String name, String value) { super(name, value); } /** * Constructor with name and value * * @param name the header name * @param value the header value * @param isAutogenerated true if the header is autogenerated, * false otherwise. * * @since 3.0 */ public Header(String name, String value, boolean isAutogenerated) { super(name, value); this.isAutogenerated = isAutogenerated; } // --------------------------------------------------------- Public Methods /** * Returns a {@link String} representation of the header. * * @return stringHEAD */ public String toExternalForm() { return ((null == getName() ? "" : getName()) + ": " + (null == getValue() ? "" : getValue()) + "\r\n"); } /** * Returns a {@link String} representation of the header. * * @return stringHEAD */ public String toString() { return toExternalForm(); } /** * Returns an array of {@link HeaderElement}s * constructed from my value. * * @see HeaderElement#parse * @throws HttpException if the header cannot be parsed * @return an array of header elements * * @deprecated Use #getElements */ public HeaderElement[] getValues() throws HttpException { return HeaderElement.parse(getValue()); } /** * Returns an array of {@link HeaderElement}s * constructed from my value. * * @see HeaderElement#parseElements(String) * * @return an array of header elements * * @since 3.0 */ public HeaderElement[] getElements() { return HeaderElement.parseElements(getValue()); } /** * Returns the value of the auto-generated header flag. * * @return true if the header is autogenerated, * false otherwise. * * @since 3.0 */ public boolean isAutogenerated() { return isAutogenerated; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HeaderElement.java100644 0 0 23127 10661532626 25305 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HeaderElement.java,v 1.23 2004/05/13 04:03:25 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.util.ParameterParser; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

One element of an HTTP header's value.

*

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

*

* This class represents an individual header element, containing * both a name/value pair (value may be null) and optionally * a set of additional parameters. *

*

* This class also exposes a {@link #parse} method for parsing a * {@link Header} value into an array of elements. *

* * @see Header * * @author B.C. Holmes * @author Park, Sung-Gu * @author Mike Bowler * @author Oleg Kalnichevski * * @since 1.0 * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ */ public class HeaderElement extends NameValuePair { // ----------------------------------------------------------- Constructors /** * Default constructor. */ public HeaderElement() { this(null, null, null); } /** * Constructor. * @param name my name * @param value my (possibly null) value */ public HeaderElement(String name, String value) { this(name, value, null); } /** * Constructor with name, value and parameters. * * @param name my name * @param value my (possibly null) value * @param parameters my (possibly null) parameters */ public HeaderElement(String name, String value, NameValuePair[] parameters) { super(name, value); this.parameters = parameters; } /** * Constructor with array of characters. * * @param chars the array of characters * @param offset - the initial offset. * @param length - the length. * * @since 3.0 */ public HeaderElement(char[] chars, int offset, int length) { this(); if (chars == null) { return; } ParameterParser parser = new ParameterParser(); List params = parser.parse(chars, offset, length, ';'); if (params.size() > 0) { NameValuePair element = (NameValuePair) params.remove(0); setName(element.getName()); setValue(element.getValue()); if (params.size() > 0) { this.parameters = (NameValuePair[]) params.toArray(new NameValuePair[params.size()]); } } } /** * Constructor with array of characters. * * @param chars the array of characters * * @since 3.0 */ public HeaderElement(char[] chars) { this(chars, 0, chars.length); } // -------------------------------------------------------- Constants /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HeaderElement.class); // ----------------------------------------------------- Instance Variables /** My parameters, if any. */ private NameValuePair[] parameters = null; // ------------------------------------------------------------- Properties /** * Get parameters, if any. * * @since 2.0 * @return parameters as an array of {@link NameValuePair}s */ public NameValuePair[] getParameters() { return this.parameters; } // --------------------------------------------------------- Public Methods /** * This parses the value part of a header. The result is an array of * HeaderElement objects. * * @param headerValue the array of char representation of the header value * (as received from the web server). * @return array of {@link HeaderElement}s. * * @since 3.0 */ public static final HeaderElement[] parseElements(char[] headerValue) { LOG.trace("enter HeaderElement.parseElements(char[])"); if (headerValue == null) { return new HeaderElement[] {}; } List elements = new ArrayList(); int i = 0; int from = 0; int len = headerValue.length; boolean qouted = false; while (i < len) { char ch = headerValue[i]; if (ch == '"') { qouted = !qouted; } HeaderElement element = null; if ((!qouted) && (ch == ',')) { element = new HeaderElement(headerValue, from, i); from = i + 1; } else if (i == len - 1) { element = new HeaderElement(headerValue, from, len); } if ((element != null) && (element.getName() != null)) { elements.add(element); } i++; } return (HeaderElement[]) elements.toArray(new HeaderElement[elements.size()]); } /** * This parses the value part of a header. The result is an array of * HeaderElement objects. * * @param headerValue the string representation of the header value * (as received from the web server). * @return array of {@link HeaderElement}s. * * @since 3.0 */ public static final HeaderElement[] parseElements(String headerValue) { LOG.trace("enter HeaderElement.parseElements(String)"); if (headerValue == null) { return new HeaderElement[] {}; } return parseElements(headerValue.toCharArray()); } /** * This parses the value part of a header. The result is an array of * HeaderElement objects. * * @param headerValue the string representation of the header value * (as received from the web server). * @return array of {@link HeaderElement}s. * @throws HttpException if the above syntax rules are violated. * * @deprecated Use #parseElements(String). */ public static final HeaderElement[] parse(String headerValue) throws HttpException { LOG.trace("enter HeaderElement.parse(String)"); if (headerValue == null) { return new HeaderElement[] {}; } return parseElements(headerValue.toCharArray()); } /** * Returns parameter with the given name, if found. Otherwise null * is returned * * @param name The name to search by. * @return NameValuePair parameter with the given name */ public NameValuePair getParameterByName(String name) { LOG.trace("enter HeaderElement.getParameterByName(String)"); if (name == null) { throw new IllegalArgumentException("Name may not be null"); } NameValuePair found = null; NameValuePair parameters[] = getParameters(); if (parameters != null) { for (int i = 0; i < parameters.length; i++) { NameValuePair current = parameters[ i ]; if (current.getName().equalsIgnoreCase(name)) { found = current; break; } } } return found; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HeaderGroup.java100644 0 0 16272 10661532626 25013 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HeaderGroup.java,v 1.8 2004/05/13 04:03:25 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * 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. * * @author Michael Becke * * @since 2.0beta1 */ public class HeaderGroup { /** The list of headers for this group, in the order in which they were added */ private List headers; /** * Constructor for HeaderGroup. */ public HeaderGroup() { this.headers = new ArrayList(); } /** * 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(Header header) { headers.add(header); } /** * Removes the given header. * * @param header the header to remove */ public void removeHeader(Header header) { headers.remove(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(Header[] headers) { clear(); for (int i = 0; i < headers.length; i++) { addHeader(headers[i]); } } /** * Gets a header representing all of the header values with the given name. * If more that one header with the given name exists the values will be * combined with a "," as per RFC 2616. * *

Header name comparison is case insensitive. * * @param name the name of the header(s) to get * @return a header with a condensed value or null if no * headers by the given name are present */ public Header getCondensedHeader(String name) { Header[] headers = getHeaders(name); if (headers.length == 0) { return null; } else if (headers.length == 1) { return new Header(headers[0].getName(), headers[0].getValue()); } else { StringBuffer valueBuffer = new StringBuffer(headers[0].getValue()); for (int i = 1; i < headers.length; i++) { valueBuffer.append(", "); valueBuffer.append(headers[i].getValue()); } return new Header(name.toLowerCase(), 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(String name) { ArrayList headersFound = new ArrayList(); for (Iterator headerIter = headers.iterator(); headerIter.hasNext();) { Header header = (Header) headerIter.next(); if (header.getName().equalsIgnoreCase(name)) { headersFound.add(header); } } return (Header[]) headersFound.toArray(new Header[headersFound.size()]); } /** * Gets the first header with the given name. * *

Header name comparison is case insensitive. * * @param name the name of the header to get * @return the first header or null */ public Header getFirstHeader(String name) { for (Iterator headerIter = headers.iterator(); headerIter.hasNext();) { Header header = (Header) headerIter.next(); if (header.getName().equalsIgnoreCase(name)) { return header; } } return null; } /** * Gets the last header with the given name. * *

Header name comparison is case insensitive. * * @param name the name of the header to get * @return the last header or null */ public Header getLastHeader(String name) { // start at the end of the list and work backwards for (int i = headers.size() - 1; i >= 0; i--) { Header 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 (Header[]) headers.toArray(new Header[headers.size()]); } /** * Tests if headers with the given name are contained within this group. * *

Header name comparison is case insensitive. * * @param name the header name to test for * @return true if at least one header with the name is * contained, false otherwise */ public boolean containsHeader(String name) { for (Iterator headerIter = headers.iterator(); headerIter.hasNext();) { Header header = (Header) headerIter.next(); 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 3.0 */ public Iterator getIterator() { return this.headers.iterator(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HostConfiguration.java100644 0 0 40217 10661532627 26250 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HostConfiguration.java,v 1.23 2005/01/14 21:16:40 olegk Exp $ * $Revision: 510585 $ * $Date: 2007-02-22 17:52:16 +0100 (Thu, 22 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.params.HostParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.util.LangUtils; import java.net.InetAddress; /** * Holds all of the variables needed to describe an HTTP connection to a host. This includes * remote host, port and protocol, proxy host and port, local address, and virtual host. * * @author Michael Becke * @author Mike Bowler * @author Oleg Kalnichevski * @author Laura Werner * * @since 2.0 */ public class HostConfiguration implements Cloneable { /** * A value to represent any host configuration, instead of using something like * null. This value should be treated as immutable and only used in * lookups and other such places to represent "any" host config. */ public static final HostConfiguration ANY_HOST_CONFIGURATION = new HostConfiguration(); /** The host to use. */ private HttpHost host = null; /** The host name of the proxy server */ private ProxyHost proxyHost = null; /** The local address to use when creating the socket, or null to use the default */ private InetAddress localAddress = null; /** Parameters specific to this host */ private HostParams params = new HostParams(); /** * Constructor for HostConfiguration. */ public HostConfiguration() { super(); } /** * Copy constructor for HostConfiguration * * @param hostConfiguration the hostConfiguration to copy */ public HostConfiguration (final HostConfiguration hostConfiguration) { init(hostConfiguration); } private void init(final HostConfiguration hostConfiguration) { // wrap all of the assignments in a synchronized block to avoid // having to negotiate the monitor for each method call synchronized (hostConfiguration) { try { if (hostConfiguration.host != null) { this.host = (HttpHost) hostConfiguration.host.clone(); } else { this.host = null; } if (hostConfiguration.proxyHost != null) { this.proxyHost = (ProxyHost) hostConfiguration.proxyHost.clone(); } else { this.proxyHost = null; } this.localAddress = hostConfiguration.getLocalAddress(); this.params = (HostParams)hostConfiguration.getParams().clone(); } catch (CloneNotSupportedException e) { throw new IllegalArgumentException("Host configuration could not be cloned"); } } } /** * @see java.lang.Object#clone() */ public Object clone() { HostConfiguration copy; try { copy = (HostConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalArgumentException("Host configuration could not be cloned"); } copy.init(this); return copy; } /** * @see java.lang.Object#toString() */ public synchronized String toString() { boolean appendComma = false; StringBuffer b = new StringBuffer(50); b.append("HostConfiguration["); if (this.host != null) { appendComma = true; b.append("host=").append(this.host); } if (this.proxyHost != null) { if (appendComma) { b.append(", "); } else { appendComma = true; } b.append("proxyHost=").append(this.proxyHost); } if (this.localAddress != null) { if (appendComma) { b.append(", "); } else { appendComma = true; } b.append("localAddress=").append(this.localAddress); if (appendComma) { b.append(", "); } else { appendComma = true; } b.append("params=").append(this.params); } b.append("]"); return b.toString(); } /** * Tests if the host configuration equals the configuration set on the * connection. True only if the host, port, protocol, local address and virtual address * are equal. If no host configuration has been set false will be returned. * * @param connection the connection to test against * @return true if the connection's host information equals that of this * configuration * * @see #proxyEquals(HttpConnection) */ public synchronized boolean hostEquals(final HttpConnection connection) { if (connection == null) { throw new IllegalArgumentException("Connection may not be null"); } if (this.host != null) { if (!this.host.getHostName().equalsIgnoreCase(connection.getHost())) { return false; } if (this.host.getPort() != connection.getPort()) { return false; } if (!this.host.getProtocol().equals(connection.getProtocol())) { return false; } if (this.localAddress != null) { if (!this.localAddress.equals(connection.getLocalAddress())) { return false; } } else { if (connection.getLocalAddress() != null) { return false; } } return true; } else { return false; } } /** * Tests if the proxy configuration equals the configuration set on the * connection. True only if the proxyHost and proxyPort are equal. * * @param connection the connection to test against * @return true if the connection's proxy information equals that of this * configuration * * @see #hostEquals(HttpConnection) */ public synchronized boolean proxyEquals(final HttpConnection connection) { if (connection == null) { throw new IllegalArgumentException("Connection may not be null"); } if (this.proxyHost != null) { return this.proxyHost.getHostName().equalsIgnoreCase(connection.getProxyHost()) && this.proxyHost.getPort() == connection.getProxyPort(); } else { return connection.getProxyHost() == null; } } /** * Returns true if the host is set. * @return true if the host is set. * * @deprecated no longer used */ public synchronized boolean isHostSet() { return this.host != null; } /** * Sets the given host * * @param host the host */ public synchronized void setHost(final HttpHost host) { this.host = host; } /** * Sets the given host, port and protocol * * @param host the host(IP or DNS name) * @param port The port * @param protocol The protocol. */ public synchronized void setHost(final String host, int port, final String protocol) { this.host = new HttpHost(host, port, Protocol.getProtocol(protocol)); } /** * Sets the given host, virtual host, port and protocol. * * @param host the host(IP or DNS name) * @param virtualHost the virtual host name or null * @param port the host port or -1 to use protocol default * @param protocol the protocol * * @deprecated #setHost(String, int, Protocol) */ public synchronized void setHost(final String host, final String virtualHost, int port, final Protocol protocol) { setHost(host, port, protocol); this.params.setVirtualHost(virtualHost); } /** * Sets the given host, port and protocol. * * @param host the host(IP or DNS name) * @param port The port * @param protocol the protocol */ public synchronized void setHost(final String host, int port, final Protocol protocol) { if (host == null) { throw new IllegalArgumentException("host must not be null"); } if (protocol == null) { throw new IllegalArgumentException("protocol must not be null"); } this.host = new HttpHost(host, port, protocol); } /** * Sets the given host and port. Uses the default protocol "http". * * @param host the host(IP or DNS name) * @param port The port */ public synchronized void setHost(final String host, int port) { setHost(host, port, Protocol.getProtocol("http")); } /** * Set the given host. Uses the default protocol("http") and its port. * * @param host The host(IP or DNS name). */ public synchronized void setHost(final String host) { Protocol defaultProtocol = Protocol.getProtocol("http"); setHost(host, defaultProtocol.getDefaultPort(), defaultProtocol); } /** * Sets the protocol, host and port from the given URI. * @param uri the URI. */ public synchronized void setHost(final URI uri) { try { setHost(uri.getHost(), uri.getPort(), uri.getScheme()); } catch (URIException e) { throw new IllegalArgumentException(e.toString()); } } /** * Return the host url. * * @return The host url. */ public synchronized String getHostURL() { if (this.host == null) { throw new IllegalStateException("Host must be set to create a host URL"); } else { return this.host.toURI(); } } /** * Returns the host. * * @return the host(IP or DNS name), or null if not set * * @see #isHostSet() */ public synchronized String getHost() { if (this.host != null) { return this.host.getHostName(); } else { return null; } } /** * Returns the virtual host. * * @return the virtual host name, or null if not set * * @deprecated use HostParams */ public synchronized String getVirtualHost() { return this.params.getVirtualHost(); } /** * Returns the port. * * @return the host port, or -1 if not set * * @see #isHostSet() */ public synchronized int getPort() { if (this.host != null) { return this.host.getPort(); } else { return -1; } } /** * Returns the protocol. * @return The protocol. */ public synchronized Protocol getProtocol() { if (this.host != null) { return this.host.getProtocol(); } else { return null; } } /** * Tests if the proxy host/port have been set. * * @return true if a proxy server has been set. * * @see #setProxy(String, int) * * @deprecated no longer used */ public synchronized boolean isProxySet() { return this.proxyHost != null; } /** * Sets the given proxy host * * @param proxyHost the proxy host */ public synchronized void setProxyHost(final ProxyHost proxyHost) { this.proxyHost = proxyHost; } /** * Set the proxy settings. * @param proxyHost The proxy host * @param proxyPort The proxy port */ public synchronized void setProxy(final String proxyHost, int proxyPort) { this.proxyHost = new ProxyHost(proxyHost, proxyPort); } /** * Returns the proxyHost. * * @return the proxy host, or null if not set * * @see #isProxySet() */ public synchronized String getProxyHost() { if (this.proxyHost != null) { return this.proxyHost.getHostName(); } else { return null; } } /** * Returns the proxyPort. * * @return the proxy port, or -1 if not set * * @see #isProxySet() */ public synchronized int getProxyPort() { if (this.proxyHost != null) { return this.proxyHost.getPort(); } else { return -1; } } /** * Set the local address to be used when creating connections. * If this is unset, the default address will be used. * This is useful for specifying the interface to use on multi-homed or clustered systems. * * @param localAddress the local address to use */ public synchronized void setLocalAddress(InetAddress localAddress) { this.localAddress = localAddress; } /** * Return the local address to be used when creating connections. * If this is unset, the default address should be used. * * @return the local address to be used when creating Sockets, or null */ public synchronized InetAddress getLocalAddress() { return this.localAddress; } /** * Returns {@link HostParams HTTP protocol parameters} associated with this host. * * @return HTTP parameters. * * @since 3.0 */ public HostParams getParams() { return this.params; } /** * Assigns {@link HostParams HTTP protocol parameters} specific to this host. * * @since 3.0 * * @see HostParams */ public void setParams(final HostParams params) { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } this.params = params; } /** * @see java.lang.Object#equals(java.lang.Object) */ public synchronized boolean equals(final Object o) { if (o instanceof HostConfiguration) { // shortcut if we're comparing with ourselves if (o == this) { return true; } HostConfiguration that = (HostConfiguration) o; return LangUtils.equals(this.host, that.host) && LangUtils.equals(this.proxyHost, that.proxyHost) && LangUtils.equals(this.localAddress, that.localAddress); } else { return false; } } /** * @see java.lang.Object#hashCode() */ public synchronized int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.host); hash = LangUtils.hashCode(hash, this.proxyHost); hash = LangUtils.hashCode(hash, this.localAddress); return hash; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpClient.java100644 0 0 43413 10661532626 24661 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpClient.java,v 1.98 2004/10/07 16:14:15 olegk Exp $ * $Revision: 509577 $ * $Date: 2007-02-20 15:28:18 +0100 (Tue, 20 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.security.Provider; import java.security.Security; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

* An HTTP "user-agent", containing an {@link HttpState HTTP state} and * one or more {@link HttpConnection HTTP connections}, to which * {@link HttpMethod HTTP methods} can be applied. *

* @author Remy Maucherat * @author Rodney Waldhoff * @author Sean C. Sullivan * @author dIon Gillard * @author Ortwin Gl?ck * @author Michael Becke * @author Mike Bowler * @author Sam Maloney * @author Laura Werner * @author Oleg Kalnichevski * * @version $Revision: 509577 $ $Date: 2007-02-20 15:28:18 +0100 (Tue, 20 Feb 2007) $ */ public class HttpClient { // -------------------------------------------------------------- Constants /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HttpClient.class); static { if (LOG.isDebugEnabled()) { try { LOG.debug("Java version: " + System.getProperty("java.version")); LOG.debug("Java vendor: " + System.getProperty("java.vendor")); LOG.debug("Java class path: " + System.getProperty("java.class.path")); LOG.debug("Operating system name: " + System.getProperty("os.name")); LOG.debug("Operating system architecture: " + System.getProperty("os.arch")); LOG.debug("Operating system version: " + System.getProperty("os.version")); Provider[] providers = Security.getProviders(); for (int i = 0; i < providers.length; i++) { Provider provider = providers[i]; LOG.debug(provider.getName() + " " + provider.getVersion() + ": " + provider.getInfo()); } } catch (SecurityException ignore) { } } } // ----------------------------------------------------------- Constructors /** * Creates an instance of HttpClient using default {@link HttpClientParams parameter set}. * * @see HttpClientParams */ public HttpClient() { this(new HttpClientParams()); } /** * Creates an instance of HttpClient using the given * {@link HttpClientParams parameter set}. * * @param params The {@link HttpClientParams parameters} to use. * * @see HttpClientParams * * @since 3.0 */ public HttpClient(HttpClientParams params) { super(); if (params == null) { throw new IllegalArgumentException("Params may not be null"); } this.params = params; this.httpConnectionManager = null; Class clazz = params.getConnectionManagerClass(); if (clazz != null) { try { this.httpConnectionManager = (HttpConnectionManager) clazz.newInstance(); } catch (Exception e) { LOG.warn("Error instantiating connection manager class, defaulting to" + " SimpleHttpConnectionManager", e); } } if (this.httpConnectionManager == null) { this.httpConnectionManager = new SimpleHttpConnectionManager(); } if (this.httpConnectionManager != null) { this.httpConnectionManager.getParams().setDefaults(this.params); } } /** * Creates an instance of HttpClient with a user specified * {@link HttpClientParams parameter set} and * {@link HttpConnectionManager HTTP connection manager}. * * @param params The {@link HttpClientParams parameters} to use. * @param httpConnectionManager The {@link HttpConnectionManager connection manager} * to use. * * @since 3.0 */ public HttpClient(HttpClientParams params, HttpConnectionManager httpConnectionManager) { super(); if (httpConnectionManager == null) { throw new IllegalArgumentException("httpConnectionManager cannot be null"); } if (params == null) { throw new IllegalArgumentException("Params may not be null"); } this.params = params; this.httpConnectionManager = httpConnectionManager; this.httpConnectionManager.getParams().setDefaults(this.params); } /** * Creates an instance of HttpClient with a user specified * {@link HttpConnectionManager HTTP connection manager}. * * @param httpConnectionManager The {@link HttpConnectionManager connection manager} * to use. * * @since 2.0 */ public HttpClient(HttpConnectionManager httpConnectionManager) { this(new HttpClientParams(), httpConnectionManager); } // ----------------------------------------------------- Instance Variables /** * The {@link HttpConnectionManager connection manager} being used to manage * connections for this HttpClient */ private HttpConnectionManager httpConnectionManager; /** * The {@link HttpState HTTP state} associated with this HttpClient. */ private HttpState state = new HttpState(); /** * The {@link HttpClientParams collection of parameters} associated with this HttpClient. */ private HttpClientParams params = null; /** * The {@link HostConfiguration host configuration} associated with * the HttpClient */ private HostConfiguration hostConfiguration = new HostConfiguration(); // ------------------------------------------------------------- Properties /** * Returns {@link HttpState HTTP state} associated with the HttpClient. * * @see #setState(HttpState) * @return the shared client state */ public synchronized HttpState getState() { return state; } /** * Assigns {@link HttpState HTTP state} for the HttpClient. * * @see #getState() * @param state the new {@link HttpState HTTP state} for the client */ public synchronized void setState(HttpState state) { this.state = state; } /** * Defines how strictly the method follows the HTTP protocol specification * (see RFC 2616 and other relevant RFCs). * * In the strict mode the method precisely * implements the requirements of the specification, whereas in non-strict mode * it attempts to mimic the exact behaviour of commonly used HTTP agents, * which many HTTP servers expect. * * @param strictMode true for strict mode, false otherwise * * @see #isStrictMode() * * @deprecated Use {@link HttpClientParams#setParameter(String, Object)} * to exercise a more granular control over HTTP protocol strictness. */ public synchronized void setStrictMode(boolean strictMode) { if (strictMode) { this.params.makeStrict(); } else { this.params.makeLenient(); } } /** * Returns the value of the strict mode flag. * * @return true if strict mode is enabled, false otherwise * * @see #setStrictMode(boolean) * * @deprecated Use * {@link org.apache.commons.httpclient.params.HttpClientParams#getParameter(String)} * to exercise a more granular control over HTTP protocol strictness. */ public synchronized boolean isStrictMode() { return false; } /** * Sets the socket timeout (SO_TIMEOUT) in milliseconds which is the * timeout for waiting for data. A timeout value of zero is interpreted as an * infinite timeout. * * @param newTimeoutInMilliseconds Timeout in milliseconds * * @deprecated Use * {@link org.apache.commons.httpclient.params.HttpConnectionManagerParams#setSoTimeout(int)}, * {@link HttpConnectionManager#getParams()}. * */ public synchronized void setTimeout(int newTimeoutInMilliseconds) { this.params.setSoTimeout(newTimeoutInMilliseconds); } /** * Sets the timeout in milliseconds used when retrieving an * {@link HttpConnection HTTP connection} from the * {@link HttpConnectionManager HTTP connection manager}. * * @param timeout the timeout in milliseconds * * @see HttpConnectionManager#getConnection(HostConfiguration, long) * * @deprecated Use * {@link org.apache.commons.httpclient.params.HttpClientParams#setConnectionManagerTimeout(long)}, * {@link HttpClient#getParams()} */ public synchronized void setHttpConnectionFactoryTimeout(long timeout) { this.params.setConnectionManagerTimeout(timeout); } /** * Sets the timeout until a connection is etablished. A value of zero * means the timeout is not used. The default value is zero. * * @see HttpConnection#setConnectionTimeout(int) * @param newTimeoutInMilliseconds Timeout in milliseconds. * * @deprecated Use * {@link org.apache.commons.httpclient.params.HttpConnectionManagerParams#setConnectionTimeout(int)}, * {@link HttpConnectionManager#getParams()}. */ public synchronized void setConnectionTimeout(int newTimeoutInMilliseconds) { this.httpConnectionManager.getParams().setConnectionTimeout(newTimeoutInMilliseconds); } // --------------------------------------------------------- Public Methods /** * Executes the given {@link HttpMethod HTTP method}. * * @param method the {@link HttpMethod HTTP method} to execute. * @return the method's response code * * @throws IOException If an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException If a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ public int executeMethod(HttpMethod method) throws IOException, HttpException { LOG.trace("enter HttpClient.executeMethod(HttpMethod)"); // execute this method and use its host configuration, if it has one return executeMethod(null, method, null); } /** * Executes the given {@link HttpMethod HTTP method} using custom * {@link HostConfiguration host configuration}. * * @param hostConfiguration The {@link HostConfiguration host configuration} to use. * If null, the host configuration returned by {@link #getHostConfiguration} will be used. * @param method the {@link HttpMethod HTTP method} to execute. * @return the method's response code * * @throws IOException If an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException If a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * @since 2.0 */ public int executeMethod(final HostConfiguration hostConfiguration, final HttpMethod method) throws IOException, HttpException { LOG.trace("enter HttpClient.executeMethod(HostConfiguration,HttpMethod)"); return executeMethod(hostConfiguration, method, null); } /** * Executes the given {@link HttpMethod HTTP method} using the given custom * {@link HostConfiguration host configuration} with the given custom * {@link HttpState HTTP state}. * * @param hostconfig The {@link HostConfiguration host configuration} to use. * If null, the host configuration returned by {@link #getHostConfiguration} will be used. * @param method the {@link HttpMethod HTTP method} to execute. * @param state the {@link HttpState HTTP state} to use when executing the method. * If null, the state returned by {@link #getState} will be used. * * @return the method's response code * * @throws IOException If an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException If a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * @since 2.0 */ public int executeMethod(HostConfiguration hostconfig, final HttpMethod method, final HttpState state) throws IOException, HttpException { LOG.trace("enter HttpClient.executeMethod(HostConfiguration,HttpMethod,HttpState)"); if (method == null) { throw new IllegalArgumentException("HttpMethod parameter may not be null"); } HostConfiguration defaulthostconfig = getHostConfiguration(); if (hostconfig == null) { hostconfig = defaulthostconfig; } URI uri = method.getURI(); if (hostconfig == defaulthostconfig || uri.isAbsoluteURI()) { // make a deep copy of the host defaults hostconfig = (HostConfiguration) hostconfig.clone(); if (uri.isAbsoluteURI()) { hostconfig.setHost(uri); } } HttpMethodDirector methodDirector = new HttpMethodDirector( getHttpConnectionManager(), hostconfig, this.params, (state == null ? getState() : state)); methodDirector.executeMethod(method); return method.getStatusCode(); } /** * Returns the default host. * * @return The default host. * * @deprecated use #getHostConfiguration() */ public String getHost() { return hostConfiguration.getHost(); } /** * Returns the default port. * * @return The default port. * * @deprecated use #getHostConfiguration() */ public int getPort() { return hostConfiguration.getPort(); } /** * Returns the {@link HostConfiguration host configuration} associated with the * HttpClient. * * @return {@link HostConfiguration host configuration} * * @since 2.0 */ public synchronized HostConfiguration getHostConfiguration() { return hostConfiguration; } /** * Assigns the {@link HostConfiguration host configuration} to use with the * HttpClient. * * @param hostConfiguration The {@link HostConfiguration host configuration} to set * * @since 2.0 */ public synchronized void setHostConfiguration(HostConfiguration hostConfiguration) { this.hostConfiguration = hostConfiguration; } /** * Returns the {@link HttpConnectionManager HTTP connection manager} associated * with the HttpClient. * * @return {@link HttpConnectionManager HTTP connection manager} * * @since 2.0 */ public synchronized HttpConnectionManager getHttpConnectionManager() { return httpConnectionManager; } /** * Assigns the {@link HttpConnectionManager HTTP connection manager} to use with * the HttpClient. * * @param httpConnectionManager The {@link HttpConnectionManager HTTP connection manager} * to set * * @since 2.0 */ public synchronized void setHttpConnectionManager( HttpConnectionManager httpConnectionManager ) { this.httpConnectionManager = httpConnectionManager; if (this.httpConnectionManager != null) { this.httpConnectionManager.getParams().setDefaults(this.params); } } /** * Returns {@link HttpClientParams HTTP protocol parameters} associated with this HttpClient. * * @since 3.0 * * @see HttpClientParams */ public HttpClientParams getParams() { return this.params; } /** * Assigns {@link HttpClientParams HTTP protocol parameters} for this HttpClient. * * @since 3.0 * * @see HttpClientParams */ public void setParams(final HttpClientParams params) { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } this.params = params; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpClientError.java100644 0 0 4047 10661532626 25653 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpClientError.java,v 1.4 2004/05/13 04:03:25 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * Signals that an error has occurred. * * @author Ortwin Gl?ck * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * @since 3.0 */ public class HttpClientError extends Error { /** * Creates a new HttpClientError with a null detail message. */ public HttpClientError() { super(); } /** * Creates a new HttpClientError with the specified detail message. * @param message The error message */ public HttpClientError(String message) { super(message); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpConnection.java100644 0 0 134257 10661532627 25572 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpConnection.java,v 1.107 2005/01/14 21:30:59 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; import org.apache.commons.httpclient.util.EncodingUtil; import org.apache.commons.httpclient.util.ExceptionUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * An abstraction of an HTTP {@link InputStream} and {@link OutputStream} * pair, together with the relevant attributes. *

* The following options are set on the socket before getting the input/output * streams in the {@link #open()} method: * * * * * *
Socket Method * Sockets Option * Configuration *
{@link java.net.Socket#setTcpNoDelay(boolean)} * SO_NODELAY * {@link HttpConnectionParams#setTcpNoDelay(boolean)} *
{@link java.net.Socket#setSoTimeout(int)} * SO_TIMEOUT * {@link HttpConnectionParams#setSoTimeout(int)} *
{@link java.net.Socket#setSendBufferSize(int)} * SO_SNDBUF * {@link HttpConnectionParams#setSendBufferSize(int)} *
{@link java.net.Socket#setReceiveBufferSize(int)} * SO_RCVBUF * {@link HttpConnectionParams#setReceiveBufferSize(int)} *
* * @author Rod Waldhoff * @author Sean C. Sullivan * @author Ortwin Glueck * @author Jeff Dever * @author Mike Bowler * @author Oleg Kalnichevski * @author Michael Becke * @author Eric E Johnson * @author Laura Werner * * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ */ public class HttpConnection { // ----------------------------------------------------------- Constructors /** * Creates a new HTTP connection for the given host and port. * * @param host the host to connect to * @param port the port to connect to */ public HttpConnection(String host, int port) { this(null, -1, host, null, port, Protocol.getProtocol("http")); } /** * Creates a new HTTP connection for the given host and port * using the given protocol. * * @param host the host to connect to * @param port the port to connect to * @param protocol the protocol to use */ public HttpConnection(String host, int port, Protocol protocol) { this(null, -1, host, null, port, protocol); } /** * Creates a new HTTP connection for the given host with the virtual * alias and port using given protocol. * * @param host the host to connect to * @param virtualHost the virtual host requests will be sent to * @param port the port to connect to * @param protocol the protocol to use */ public HttpConnection(String host, String virtualHost, int port, Protocol protocol) { this(null, -1, host, virtualHost, port, protocol); } /** * Creates a new HTTP connection for the given host and port via the * given proxy host and port using the default protocol. * * @param proxyHost the host to proxy via * @param proxyPort the port to proxy via * @param host the host to connect to * @param port the port to connect to */ public HttpConnection( String proxyHost, int proxyPort, String host, int port) { this(proxyHost, proxyPort, host, null, port, Protocol.getProtocol("http")); } /** * Creates a new HTTP connection for the given host configuration. * * @param hostConfiguration the host/proxy/protocol to use */ public HttpConnection(HostConfiguration hostConfiguration) { this(hostConfiguration.getProxyHost(), hostConfiguration.getProxyPort(), hostConfiguration.getHost(), hostConfiguration.getPort(), hostConfiguration.getProtocol()); this.localAddress = hostConfiguration.getLocalAddress(); } /** * Creates a new HTTP connection for the given host with the virtual * alias and port via the given proxy host and port using the given * protocol. * * @param proxyHost the host to proxy via * @param proxyPort the port to proxy via * @param host the host to connect to. Parameter value must be non-null. * @param virtualHost No longer applicable. * @param port the port to connect to * @param protocol The protocol to use. Parameter value must be non-null. * * @deprecated use #HttpConnection(String, int, String, int, Protocol) */ public HttpConnection( String proxyHost, int proxyPort, String host, String virtualHost, int port, Protocol protocol) { this(proxyHost, proxyPort, host, port, protocol); } /** * Creates a new HTTP connection for the given host with the virtual * alias and port via the given proxy host and port using the given * protocol. * * @param proxyHost the host to proxy via * @param proxyPort the port to proxy via * @param host the host to connect to. Parameter value must be non-null. * @param port the port to connect to * @param protocol The protocol to use. Parameter value must be non-null. */ public HttpConnection( String proxyHost, int proxyPort, String host, int port, Protocol protocol) { if (host == null) { throw new IllegalArgumentException("host parameter is null"); } if (protocol == null) { throw new IllegalArgumentException("protocol is null"); } proxyHostName = proxyHost; proxyPortNumber = proxyPort; hostName = host; portNumber = protocol.resolvePort(port); protocolInUse = protocol; } // ------------------------------------------ Attribute Setters and Getters /** * Returns the connection socket. * * @return the socket. * * @since 3.0 */ protected Socket getSocket() { return this.socket; } /** * Returns the host. * * @return the host. */ public String getHost() { return hostName; } /** * Sets the host to connect to. * * @param host the host to connect to. Parameter value must be non-null. * @throws IllegalStateException if the connection is already open */ public void setHost(String host) throws IllegalStateException { if (host == null) { throw new IllegalArgumentException("host parameter is null"); } assertNotOpen(); hostName = host; } /** * Returns the target virtual host. * * @return the virtual host. * * @deprecated no longer applicable */ public String getVirtualHost() { return this.hostName; } /** * Sets the virtual host to target. * * @param host the virtual host name that should be used instead of * physical host name when sending HTTP requests. Virtual host * name can be set to null if virtual host name is not * to be used * * @throws IllegalStateException if the connection is already open * * @deprecated no longer applicable */ public void setVirtualHost(String host) throws IllegalStateException { assertNotOpen(); } /** * Returns the port of the host. * * If the port is -1 (or less than 0) the default port for * the current protocol is returned. * * @return the port. */ public int getPort() { if (portNumber < 0) { return isSecure() ? 443 : 80; } else { return portNumber; } } /** * Sets the port to connect to. * * @param port the port to connect to * * @throws IllegalStateException if the connection is already open */ public void setPort(int port) throws IllegalStateException { assertNotOpen(); portNumber = port; } /** * Returns the proxy host. * * @return the proxy host. */ public String getProxyHost() { return proxyHostName; } /** * Sets the host to proxy through. * * @param host the host to proxy through. * * @throws IllegalStateException if the connection is already open */ public void setProxyHost(String host) throws IllegalStateException { assertNotOpen(); proxyHostName = host; } /** * Returns the port of the proxy host. * * @return the proxy port. */ public int getProxyPort() { return proxyPortNumber; } /** * Sets the port of the host to proxy through. * * @param port the port of the host to proxy through. * * @throws IllegalStateException if the connection is already open */ public void setProxyPort(int port) throws IllegalStateException { assertNotOpen(); proxyPortNumber = port; } /** * Returns true if the connection is established over * a secure protocol. * * @return true if connected over a secure protocol. */ public boolean isSecure() { return protocolInUse.isSecure(); } /** * Returns the protocol used to establish the connection. * @return The protocol */ public Protocol getProtocol() { return protocolInUse; } /** * Sets the protocol used to establish the connection * * @param protocol The protocol to use. * * @throws IllegalStateException if the connection is already open */ public void setProtocol(Protocol protocol) { assertNotOpen(); if (protocol == null) { throw new IllegalArgumentException("protocol is null"); } protocolInUse = protocol; } /** * Return the local address used when creating the connection. * If null, the default address is used. * * @return InetAddress the local address to be used when creating Sockets */ public InetAddress getLocalAddress() { return this.localAddress; } /** * Set the local address used when creating the connection. * If unset or null, the default address is used. * * @param localAddress the local address to use */ public void setLocalAddress(InetAddress localAddress) { assertNotOpen(); this.localAddress = localAddress; } /** * Tests if the connection is open. * * @return true if the connection is open */ public boolean isOpen() { return isOpen; } /** * Closes the connection if stale. * * @return true if the connection was stale and therefore closed, * false otherwise. * * @see #isStale() * * @since 3.0 */ public boolean closeIfStale() throws IOException { if (isOpen && isStale()) { LOG.debug("Connection is stale, closing..."); close(); return true; } return false; } /** * Tests if stale checking is enabled. * * @return true if enabled * * @see #isStale() * * @deprecated Use {@link HttpConnectionParams#isStaleCheckingEnabled()}, * {@link HttpConnection#getParams()}. */ public boolean isStaleCheckingEnabled() { return this.params.isStaleCheckingEnabled(); } /** * Sets whether or not isStale() will be called when testing if this connection is open. * *

Setting this flag to false will increase performance when reusing * connections, but it will also make them less reliable. Stale checking ensures that * connections are viable before they are used. When set to false some * method executions will result in IOExceptions and they will have to be retried.

* * @param staleCheckEnabled true to enable isStale() * * @see #isStale() * @see #isOpen() * * @deprecated Use {@link HttpConnectionParams#setStaleCheckingEnabled(boolean)}, * {@link HttpConnection#getParams()}. */ public void setStaleCheckingEnabled(boolean staleCheckEnabled) { this.params.setStaleCheckingEnabled(staleCheckEnabled); } /** * Determines whether this connection is "stale", which is to say that either * it is no longer open, or an attempt to read the connection would fail. * *

Unfortunately, due to the limitations of the JREs prior to 1.4, it is * not possible to test a connection to see if both the read and write channels * are open - except by reading and writing. This leads to a difficulty when * some connections leave the "write" channel open, but close the read channel * and ignore the request. This function attempts to ameliorate that * problem by doing a test read, assuming that the caller will be doing a * write followed by a read, rather than the other way around. *

* *

To avoid side-effects, the underlying connection is wrapped by a * {@link BufferedInputStream}, so although data might be read, what is visible * to clients of the connection will not change with this call.true if the connection is already closed, or a read would * fail. */ protected boolean isStale() throws IOException { boolean isStale = true; if (isOpen) { // the connection is open, but now we have to see if we can read it // assume the connection is not stale. isStale = false; try { if (inputStream.available() <= 0) { try { socket.setSoTimeout(1); inputStream.mark(1); int byteRead = inputStream.read(); if (byteRead == -1) { // again - if the socket is reporting all data read, // probably stale isStale = true; } else { inputStream.reset(); } } finally { socket.setSoTimeout(this.params.getSoTimeout()); } } } catch (InterruptedIOException e) { if (!ExceptionUtil.isSocketTimeoutException(e)) { throw e; } // aha - the connection is NOT stale - continue on! } catch (IOException e) { // oops - the connection is stale, the read or soTimeout failed. LOG.debug( "An error occurred while reading from the socket, is appears to be stale", e ); isStale = true; } } return isStale; } /** * Returns true if the connection is established via a proxy, * false otherwise. * * @return true if a proxy is used to establish the connection, * false otherwise. */ public boolean isProxied() { return (!(null == proxyHostName || 0 >= proxyPortNumber)); } /** * Set the state to keep track of the last response for the last request. * *

The connection managers use this to ensure that previous requests are * properly closed before a new request is attempted. That way, a GET * request need not be read in its entirety before a new request is issued. * Instead, this stream can be closed as appropriate.

* * @param inStream The stream associated with an HttpMethod. */ public void setLastResponseInputStream(InputStream inStream) { lastResponseInputStream = inStream; } /** * Returns the stream used to read the last response's body. * *

Clients will generally not need to call this function unless * using HttpConnection directly, instead of calling {@link HttpClient#executeMethod}. * For those clients, call this function, and if it returns a non-null stream, * close the stream before attempting to execute a method. Note that * calling "close" on the stream returned by this function may close * the connection if the previous response contained a "Connection: close" header.

* * @return An {@link InputStream} corresponding to the body of the last * response. */ public InputStream getLastResponseInputStream() { return lastResponseInputStream; } // --------------------------------------------------- Other Public Methods /** * Returns {@link HttpConnectionParams HTTP protocol parameters} associated with this method. * * @return HTTP parameters. * * @since 3.0 */ public HttpConnectionParams getParams() { return this.params; } /** * Assigns {@link HttpConnectionParams HTTP protocol parameters} for this method. * * @since 3.0 * * @see HttpConnectionParams */ public void setParams(final HttpConnectionParams params) { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } this.params = params; } /** * Set the {@link Socket}'s timeout, via {@link Socket#setSoTimeout}. If the * connection is already open, the SO_TIMEOUT is changed. If no connection * is open, then subsequent connections will use the timeout value. *

* Note: This is not a connection timeout but a timeout on network traffic! * * @param timeout the timeout value * @throws SocketException - if there is an error in the underlying * protocol, such as a TCP error. * * @deprecated Use {@link HttpConnectionParams#setSoTimeout(int)}, * {@link HttpConnection#getParams()}. */ public void setSoTimeout(int timeout) throws SocketException, IllegalStateException { this.params.setSoTimeout(timeout); if (this.socket != null) { this.socket.setSoTimeout(timeout); } } /** * Sets SO_TIMEOUT value directly on the underlying {@link Socket socket}. * This method does not change the default read timeout value set via * {@link HttpConnectionParams}. * * @param timeout the timeout value * @throws SocketException - if there is an error in the underlying * protocol, such as a TCP error. * @throws IllegalStateException if not connected * * @since 3.0 */ public void setSocketTimeout(int timeout) throws SocketException, IllegalStateException { assertOpen(); if (this.socket != null) { this.socket.setSoTimeout(timeout); } } /** * Returns the {@link Socket}'s timeout, via {@link Socket#getSoTimeout}, if the * connection is already open. If no connection is open, return the value subsequent * connection will use. *

* Note: This is not a connection timeout but a timeout on network traffic! * * @return the timeout value * * @deprecated Use {@link HttpConnectionParams#getSoTimeout()}, * {@link HttpConnection#getParams()}. */ public int getSoTimeout() throws SocketException { return this.params.getSoTimeout(); } /** * Sets the connection timeout. This is the maximum time that may be spent * until a connection is established. The connection will fail after this * amount of time. * @param timeout The timeout in milliseconds. 0 means timeout is not used. * * @deprecated Use {@link HttpConnectionParams#setConnectionTimeout(int)}, * {@link HttpConnection#getParams()}. */ public void setConnectionTimeout(int timeout) { this.params.setConnectionTimeout(timeout); } /** * Establishes a connection to the specified host and port * (via a proxy if specified). * The underlying socket is created from the {@link ProtocolSocketFactory}. * * @throws IOException if an attempt to establish the connection results in an * I/O error. */ public void open() throws IOException { LOG.trace("enter HttpConnection.open()"); final String host = (proxyHostName == null) ? hostName : proxyHostName; final int port = (proxyHostName == null) ? portNumber : proxyPortNumber; assertNotOpen(); if (LOG.isDebugEnabled()) { LOG.debug("Open connection to " + host + ":" + port); } try { if (this.socket == null) { usingSecureSocket = isSecure() && !isProxied(); // use the protocol's socket factory unless this is a secure // proxied connection ProtocolSocketFactory socketFactory = null; if (isSecure() && isProxied()) { Protocol defaultprotocol = Protocol.getProtocol("http"); socketFactory = defaultprotocol.getSocketFactory(); } else { socketFactory = this.protocolInUse.getSocketFactory(); } this.socket = socketFactory.createSocket( host, port, localAddress, 0, this.params); } /* "Nagling has been broadly implemented across networks, including the Internet, and is generally performed by default - although it is sometimes considered to be undesirable in highly interactive environments, such as some client/server situations. In such cases, nagling may be turned off through use of the TCP_NODELAY sockets option." */ socket.setTcpNoDelay(this.params.getTcpNoDelay()); socket.setSoTimeout(this.params.getSoTimeout()); int linger = this.params.getLinger(); if (linger >= 0) { socket.setSoLinger(linger > 0, linger); } int sndBufSize = this.params.getSendBufferSize(); if (sndBufSize >= 0) { socket.setSendBufferSize(sndBufSize); } int rcvBufSize = this.params.getReceiveBufferSize(); if (rcvBufSize >= 0) { socket.setReceiveBufferSize(rcvBufSize); } int outbuffersize = socket.getSendBufferSize(); if ((outbuffersize > 2048) || (outbuffersize <= 0)) { outbuffersize = 2048; } int inbuffersize = socket.getReceiveBufferSize(); if ((inbuffersize > 2048) || (inbuffersize <= 0)) { inbuffersize = 2048; } inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize); outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize); isOpen = true; } catch (IOException e) { // Connection wasn't opened properly // so close everything out closeSocketAndStreams(); throw e; } } /** * Instructs the proxy to establish a secure tunnel to the host. The socket will * be switched to the secure socket. Subsequent communication is done via the secure * socket. The method can only be called once on a proxied secure connection. * * @throws IllegalStateException if connection is not secure and proxied or * if the socket is already secure. * @throws IOException if an attempt to establish the secure tunnel results in an * I/O error. */ public void tunnelCreated() throws IllegalStateException, IOException { LOG.trace("enter HttpConnection.tunnelCreated()"); if (!isSecure() || !isProxied()) { throw new IllegalStateException( "Connection must be secure " + "and proxied to use this feature"); } if (usingSecureSocket) { throw new IllegalStateException("Already using a secure socket"); } if (LOG.isDebugEnabled()) { LOG.debug("Secure tunnel to " + this.hostName + ":" + this.portNumber); } SecureProtocolSocketFactory socketFactory = (SecureProtocolSocketFactory) protocolInUse.getSocketFactory(); socket = socketFactory.createSocket(socket, hostName, portNumber, true); int sndBufSize = this.params.getSendBufferSize(); if (sndBufSize >= 0) { socket.setSendBufferSize(sndBufSize); } int rcvBufSize = this.params.getReceiveBufferSize(); if (rcvBufSize >= 0) { socket.setReceiveBufferSize(rcvBufSize); } int outbuffersize = socket.getSendBufferSize(); if (outbuffersize > 2048) { outbuffersize = 2048; } int inbuffersize = socket.getReceiveBufferSize(); if (inbuffersize > 2048) { inbuffersize = 2048; } inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize); outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize); usingSecureSocket = true; tunnelEstablished = true; } /** * Indicates if the connection is completely transparent from end to end. * * @return true if conncetion is not proxied or tunneled through a transparent * proxy; false otherwise. */ public boolean isTransparent() { return !isProxied() || tunnelEstablished; } /** * Flushes the output request stream. This method should be called to * ensure that data written to the request OutputStream is sent to the server. * * @throws IOException if an I/O problem occurs */ public void flushRequestOutputStream() throws IOException { LOG.trace("enter HttpConnection.flushRequestOutputStream()"); assertOpen(); outputStream.flush(); } /** * Returns an {@link OutputStream} suitable for writing the request. * * @throws IllegalStateException if the connection is not open * @throws IOException if an I/O problem occurs * @return a stream to write the request to */ public OutputStream getRequestOutputStream() throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.getRequestOutputStream()"); assertOpen(); OutputStream out = this.outputStream; if (Wire.CONTENT_WIRE.enabled()) { out = new WireLogOutputStream(out, Wire.CONTENT_WIRE); } return out; } /** * Return a {@link InputStream} suitable for reading the response. * @return InputStream The response input stream. * @throws IOException If an IO problem occurs * @throws IllegalStateException If the connection isn't open. */ public InputStream getResponseInputStream() throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.getResponseInputStream()"); assertOpen(); return inputStream; } /** * Tests if input data avaialble. This method returns immediately * and does not perform any read operations on the input socket * * @return boolean true if input data is available, * false otherwise. * * @throws IOException If an IO problem occurs * @throws IllegalStateException If the connection isn't open. */ public boolean isResponseAvailable() throws IOException { LOG.trace("enter HttpConnection.isResponseAvailable()"); if (this.isOpen) { return this.inputStream.available() > 0; } else { return false; } } /** * Tests if input data becomes available within the given period time in milliseconds. * * @param timeout The number milliseconds to wait for input data to become available * @return boolean true if input data is availble, * false otherwise. * * @throws IOException If an IO problem occurs * @throws IllegalStateException If the connection isn't open. */ public boolean isResponseAvailable(int timeout) throws IOException { LOG.trace("enter HttpConnection.isResponseAvailable(int)"); assertOpen(); boolean result = false; if (this.inputStream.available() > 0) { result = true; } else { try { this.socket.setSoTimeout(timeout); inputStream.mark(1); int byteRead = inputStream.read(); if (byteRead != -1) { inputStream.reset(); LOG.debug("Input data available"); result = true; } else { LOG.debug("Input data not available"); } } catch (InterruptedIOException e) { if (!ExceptionUtil.isSocketTimeoutException(e)) { throw e; } if (LOG.isDebugEnabled()) { LOG.debug("Input data not available after " + timeout + " ms"); } } finally { try { socket.setSoTimeout(this.params.getSoTimeout()); } catch (IOException ioe) { LOG.debug("An error ocurred while resetting soTimeout, we will assume that" + " no response is available.", ioe); result = false; } } } return result; } /** * Writes the specified bytes to the output stream. * * @param data the data to be written * @throws IllegalStateException if not connected * @throws IOException if an I/O problem occurs * @see #write(byte[],int,int) */ public void write(byte[] data) throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.write(byte[])"); this.write(data, 0, data.length); } /** * Writes length bytes in data starting at * offset to the output stream. * * The general contract for * write(b, off, len) is that some of the bytes in the array b are written * to the output stream in order; element b[off] is the first byte written * and b[off+len-1] is the last byte written by this operation. * * @param data array containing the data to be written. * @param offset the start offset in the data. * @param length the number of bytes to write. * @throws IllegalStateException if not connected * @throws IOException if an I/O problem occurs */ public void write(byte[] data, int offset, int length) throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.write(byte[], int, int)"); if (offset < 0) { throw new IllegalArgumentException("Array offset may not be negative"); } if (length < 0) { throw new IllegalArgumentException("Array length may not be negative"); } if (offset + length > data.length) { throw new IllegalArgumentException("Given offset and length exceed the array length"); } assertOpen(); this.outputStream.write(data, offset, length); } /** * Writes the specified bytes, followed by "\r\n".getBytes() to the * output stream. * * @param data the bytes to be written * @throws IllegalStateException if the connection is not open * @throws IOException if an I/O problem occurs */ public void writeLine(byte[] data) throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.writeLine(byte[])"); write(data); writeLine(); } /** * Writes "\r\n".getBytes() to the output stream. * * @throws IllegalStateException if the connection is not open * @throws IOException if an I/O problem occurs */ public void writeLine() throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.writeLine()"); write(CRLF); } /** * @deprecated Use {@link #print(String, String)} * * Writes the specified String (as bytes) to the output stream. * * @param data the string to be written * @throws IllegalStateException if the connection is not open * @throws IOException if an I/O problem occurs */ public void print(String data) throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.print(String)"); write(EncodingUtil.getBytes(data, "ISO-8859-1")); } /** * Writes the specified String (as bytes) to the output stream. * * @param data the string to be written * @param charset the charset to use for writing the data * @throws IllegalStateException if the connection is not open * @throws IOException if an I/O problem occurs * * @since 3.0 */ public void print(String data, String charset) throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.print(String)"); write(EncodingUtil.getBytes(data, charset)); } /** * @deprecated Use {@link #printLine(String, String)} * * Writes the specified String (as bytes), followed by * "\r\n".getBytes() to the output stream. * * @param data the data to be written * @throws IllegalStateException if the connection is not open * @throws IOException if an I/O problem occurs */ public void printLine(String data) throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.printLine(String)"); writeLine(EncodingUtil.getBytes(data, "ISO-8859-1")); } /** * Writes the specified String (as bytes), followed by * "\r\n".getBytes() to the output stream. * * @param data the data to be written * @param charset the charset to use for writing the data * @throws IllegalStateException if the connection is not open * @throws IOException if an I/O problem occurs * * @since 3.0 */ public void printLine(String data, String charset) throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.printLine(String)"); writeLine(EncodingUtil.getBytes(data, charset)); } /** * Writes "\r\n".getBytes() to the output stream. * * @throws IllegalStateException if the connection is not open * @throws IOException if an I/O problem occurs */ public void printLine() throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.printLine()"); writeLine(); } /** * Reads up to "\n" from the (unchunked) input stream. * If the stream ends before the line terminator is found, * the last part of the string will still be returned. * * @throws IllegalStateException if the connection is not open * @throws IOException if an I/O problem occurs * @return a line from the response * * @deprecated use #readLine(String) */ public String readLine() throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.readLine()"); assertOpen(); return HttpParser.readLine(inputStream); } /** * Reads up to "\n" from the (unchunked) input stream. * If the stream ends before the line terminator is found, * the last part of the string will still be returned. * * @param charset the charset to use for reading the data * * @throws IllegalStateException if the connection is not open * @throws IOException if an I/O problem occurs * @return a line from the response * * @since 3.0 */ public String readLine(final String charset) throws IOException, IllegalStateException { LOG.trace("enter HttpConnection.readLine()"); assertOpen(); return HttpParser.readLine(inputStream, charset); } /** * Attempts to shutdown the {@link Socket}'s output, via Socket.shutdownOutput() * when running on JVM 1.3 or higher. * * @deprecated unused */ public void shutdownOutput() { LOG.trace("enter HttpConnection.shutdownOutput()"); try { // Socket.shutdownOutput is a JDK 1.3 // method. We'll use reflection in case // we're running in an older VM Class[] paramsClasses = new Class[0]; Method shutdownOutput = socket.getClass().getMethod("shutdownOutput", paramsClasses); Object[] params = new Object[0]; shutdownOutput.invoke(socket, params); } catch (Exception ex) { LOG.debug("Unexpected Exception caught", ex); // Ignore, and hope everything goes right } // close output stream? } /** * Closes the socket and streams. */ public void close() { LOG.trace("enter HttpConnection.close()"); closeSocketAndStreams(); } /** * Returns the httpConnectionManager. * @return HttpConnectionManager */ public HttpConnectionManager getHttpConnectionManager() { return httpConnectionManager; } /** * Sets the httpConnectionManager. * @param httpConnectionManager The httpConnectionManager to set */ public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager) { this.httpConnectionManager = httpConnectionManager; } /** * Releases the connection. If the connection is locked or does not have a connection * manager associated with it, this method has no effect. Note that it is completely safe * to call this method multiple times. */ public void releaseConnection() { LOG.trace("enter HttpConnection.releaseConnection()"); if (locked) { LOG.debug("Connection is locked. Call to releaseConnection() ignored."); } else if (httpConnectionManager != null) { LOG.debug("Releasing connection back to connection manager."); httpConnectionManager.releaseConnection(this); } else { LOG.warn("HttpConnectionManager is null. Connection cannot be released."); } } /** * Tests if the connection is locked. Locked connections cannot be released. * An attempt to release a locked connection will have no effect. * * @return true if the connection is locked, false otherwise. * * @since 3.0 */ protected boolean isLocked() { return locked; } /** * Locks or unlocks the connection. Locked connections cannot be released. * An attempt to release a locked connection will have no effect. * * @param locked true to lock the connection, false to unlock * the connection. * * @since 3.0 */ protected void setLocked(boolean locked) { this.locked = locked; } // ------------------------------------------------------ Protected Methods /** * Closes everything out. */ protected void closeSocketAndStreams() { LOG.trace("enter HttpConnection.closeSockedAndStreams()"); isOpen = false; // no longer care about previous responses... lastResponseInputStream = null; if (null != outputStream) { OutputStream temp = outputStream; outputStream = null; try { temp.close(); } catch (Exception ex) { LOG.debug("Exception caught when closing output", ex); // ignored } } if (null != inputStream) { InputStream temp = inputStream; inputStream = null; try { temp.close(); } catch (Exception ex) { LOG.debug("Exception caught when closing input", ex); // ignored } } if (null != socket) { Socket temp = socket; socket = null; try { temp.close(); } catch (Exception ex) { LOG.debug("Exception caught when closing socket", ex); // ignored } } tunnelEstablished = false; usingSecureSocket = false; } /** * Throws an {@link IllegalStateException} if the connection is already open. * * @throws IllegalStateException if connected */ protected void assertNotOpen() throws IllegalStateException { if (isOpen) { throw new IllegalStateException("Connection is open"); } } /** * Throws an {@link IllegalStateException} if the connection is not open. * * @throws IllegalStateException if not connected */ protected void assertOpen() throws IllegalStateException { if (!isOpen) { throw new IllegalStateException("Connection is not open"); } } /** * Gets the socket's sendBufferSize. * * @return the size of the buffer for the socket OutputStream, -1 if the value * has not been set and the socket has not been opened * * @throws SocketException if an error occurs while getting the socket value * * @see Socket#getSendBufferSize() */ public int getSendBufferSize() throws SocketException { if (socket == null) { return -1; } else { return socket.getSendBufferSize(); } } /** * Sets the socket's sendBufferSize. * * @param sendBufferSize the size to set for the socket OutputStream * * @throws SocketException if an error occurs while setting the socket value * * @see Socket#setSendBufferSize(int) * * @deprecated Use {@link HttpConnectionParams#setSendBufferSize(int)}, * {@link HttpConnection#getParams()}. */ public void setSendBufferSize(int sendBufferSize) throws SocketException { this.params.setSendBufferSize(sendBufferSize); } // ------------------------------------------------------- Static Variable /** "\r\n", as bytes. */ private static final byte[] CRLF = new byte[] {(byte) 13, (byte) 10}; /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HttpConnection.class); // ----------------------------------------------------- Instance Variables /** My host. */ private String hostName = null; /** My port. */ private int portNumber = -1; /** My proxy host. */ private String proxyHostName = null; /** My proxy port. */ private int proxyPortNumber = -1; /** My client Socket. */ private Socket socket = null; /** My InputStream. */ private InputStream inputStream = null; /** My OutputStream. */ private OutputStream outputStream = null; /** An {@link InputStream} for the response to an individual request. */ private InputStream lastResponseInputStream = null; /** Whether or not the connection is connected. */ protected boolean isOpen = false; /** the protocol being used */ private Protocol protocolInUse; /** Collection of HTTP parameters associated with this HTTP connection*/ private HttpConnectionParams params = new HttpConnectionParams(); /** flag to indicate if this connection can be released, if locked the connection cannot be * released */ private boolean locked = false; /** Whether or not the socket is a secure one. */ private boolean usingSecureSocket = false; /** Whether the connection is open via a secure tunnel or not */ private boolean tunnelEstablished = false; /** the connection manager that created this connection or null */ private HttpConnectionManager httpConnectionManager; /** The local interface on which the connection is created, or null for the default */ private InetAddress localAddress; } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpConnectionManager.java100644 0 0 13207 10661532627 27034 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpConnectionManager.java,v 1.24 2004/07/05 22:46:58 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; /** * An interface for classes that manage HttpConnections. * * @see org.apache.commons.httpclient.HttpConnection * @see org.apache.commons.httpclient.HttpClient#HttpClient(HttpConnectionManager) * * @author Michael Becke * @author Mike Bowler * @author Oleg Kalnichevski * * @since 2.0 */ public interface HttpConnectionManager { /** * Gets an HttpConnection for a given host configuration. If a connection is * not available this method will block until one is. * * The connection manager should be registered with any HttpConnection that * is created. * * @param hostConfiguration the host configuration to use to configure the * connection * * @return an HttpConnection for the given configuration * * @see HttpConnection#setHttpConnectionManager(HttpConnectionManager) */ HttpConnection getConnection(HostConfiguration hostConfiguration); /** * Gets an HttpConnection for a given host configuration. If a connection is * not available, this method will block for at most the specified number of * milliseconds or until a connection becomes available. * * The connection manager should be registered with any HttpConnection that * is created. * * @param hostConfiguration the host configuration to use to configure the * connection * @param timeout - the time (in milliseconds) to wait for a connection to * become available, 0 to specify an infinite timeout * * @return an HttpConnection for the given configuraiton * * @throws HttpException if no connection becomes available before the * timeout expires * * @see HttpConnection#setHttpConnectionManager(HttpConnectionManager) * * @deprecated Use #getConnectionWithTimeout(HostConfiguration, long) */ HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout) throws HttpException; /** * Gets an HttpConnection for a given host configuration. If a connection is * not available, this method will block for at most the specified number of * milliseconds or until a connection becomes available. * * The connection manager should be registered with any HttpConnection that * is created. * * @param hostConfiguration the host configuration to use to configure the * connection * @param timeout - the time (in milliseconds) to wait for a connection to * become available, 0 to specify an infinite timeout * * @return an HttpConnection for the given configuraiton * * @throws ConnectionPoolTimeoutException if no connection becomes available before the * timeout expires * * @see HttpConnection#setHttpConnectionManager(HttpConnectionManager) * * @since 3.0 */ HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout) throws ConnectionPoolTimeoutException; /** * Releases the given HttpConnection for use by other requests. * * @param conn - The HttpConnection to make available. */ void releaseConnection(HttpConnection conn); /** * Closes connections that have been idle for at least the given amount of time. Only * connections that are currently owned, not checked out, are subject to idle timeouts. * * @param idleTimeout the minimum idle time, in milliseconds, for connections to be closed * * @since 3.0 */ void closeIdleConnections(long idleTimeout); /** * Returns {@link HttpConnectionManagerParams parameters} associated * with this connection manager. * * @since 3.0 * * @see HttpConnectionManagerParams */ HttpConnectionManagerParams getParams(); /** * Assigns {@link HttpConnectionManagerParams parameters} for this * connection manager. * * @since 3.0 * * @see HttpConnectionManagerParams */ void setParams(final HttpConnectionManagerParams params); } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpConstants.java100644 0 0 26364 10661532626 25425 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpConstants.java,v 1.15 2004/04/18 23:51:35 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.UnsupportedEncodingException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * HTTP content conversion routines. * * @author Oleg Kalnichevski * @author Mike Bowler * * @deprecated use EncodingUtil class */ public class HttpConstants { /** Character set used to encode HTTP protocol elements */ public static final String HTTP_ELEMENT_CHARSET = "US-ASCII"; /** Default content encoding chatset */ public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1"; /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HttpConstants.class); /** * Converts the specified string to a byte array of HTTP element characters. * This method is to be used when encoding content of HTTP elements (such as * request headers) * * @param data the string to be encoded * @return The resulting byte array. */ public static byte[] getBytes(final String data) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } try { return data.getBytes(HTTP_ELEMENT_CHARSET); } catch (UnsupportedEncodingException e) { if (LOG.isWarnEnabled()) { LOG.warn("Unsupported encoding: " + HTTP_ELEMENT_CHARSET + ". System default encoding used"); } return data.getBytes(); } } /** * Converts the byte array of HTTP element 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 resulting string. */ public static String getString(final byte[] data, int offset, int length) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } try { return new String(data, offset, length, HTTP_ELEMENT_CHARSET); } catch (UnsupportedEncodingException e) { if (LOG.isWarnEnabled()) { LOG.warn("Unsupported encoding: " + HTTP_ELEMENT_CHARSET + ". System default encoding used"); } return new String(data, offset, length); } } /** * Converts the byte array of HTTP element 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 resulting string. */ public static String getString(final byte[] data) { return getString(data, 0, data.length); } /** * Converts the specified string to a byte array of HTTP content charachetrs * This method is to be used when encoding content of HTTP request/response * If the specified charset is not supported, default HTTP content encoding * (ISO-8859-1) is applied * * @param data the string to be encoded * @param charset the desired character encoding * @return The resulting byte array. */ public static byte[] getContentBytes(final String data, String charset) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } if ((charset == null) || (charset.equals(""))) { charset = DEFAULT_CONTENT_CHARSET; } try { return data.getBytes(charset); } catch (UnsupportedEncodingException e) { if (LOG.isWarnEnabled()) { LOG.warn("Unsupported encoding: " + charset + ". HTTP default encoding used"); } try { return data.getBytes(DEFAULT_CONTENT_CHARSET); } catch (UnsupportedEncodingException e2) { if (LOG.isWarnEnabled()) { LOG.warn("Unsupported encoding: " + DEFAULT_CONTENT_CHARSET + ". System encoding used"); } return data.getBytes(); } } } /** * Converts the byte array of HTTP content characters to a string This * method is to be used when decoding content of HTTP request/response If * the specified charset is not supported, default HTTP content encoding * (ISO-8859-1) is applied * * @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 getContentString( final byte[] data, int offset, int length, String charset ) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } if ((charset == null) || (charset.equals(""))) { charset = DEFAULT_CONTENT_CHARSET; } try { return new String(data, offset, length, charset); } catch (UnsupportedEncodingException e) { if (LOG.isWarnEnabled()) { LOG.warn("Unsupported encoding: " + charset + ". Default HTTP encoding used"); } try { return new String(data, offset, length, DEFAULT_CONTENT_CHARSET); } catch (UnsupportedEncodingException e2) { if (LOG.isWarnEnabled()) { LOG.warn("Unsupported encoding: " + DEFAULT_CONTENT_CHARSET + ". System encoding used"); } return new String(data, offset, length); } } } /** * Converts the byte array of HTTP content characters to a string This * method is to be used when decoding content of HTTP request/response If * the specified charset is not supported, default HTTP content encoding * (ISO-8859-1) is applied * * @param data the byte array to be encoded * @param charset the desired character encoding * @return The result of the conversion. */ public static String getContentString(final byte[] data, String charset) { return getContentString(data, 0, data.length, charset); } /** * Converts the specified string to a byte array of HTTP content characters * using default HTTP content encoding (ISO-8859-1) This method is to be * used when encoding content of HTTP request/response * * @param data the string to be encoded * @return The byte array as above. */ public static byte[] getContentBytes(final String data) { return getContentBytes(data, null); } /** * Converts the byte array of HTTP content characters to a string using * default HTTP content encoding (ISO-8859-1) This method is to be used when * decoding content of HTTP request/response * * @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 getContentString(final byte[] data, int offset, int length) { return getContentString(data, offset, length, null); } /** * Converts the byte array of HTTP content characters to a string using * default HTTP content encoding (ISO-8859-1) This method is to be used when * decoding content of HTTP request/response * * @param data the byte array to be encoded * @return The string representation of the byte array. */ public static String getContentString(final byte[] data) { return getContentString(data, null); } /** * 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) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } try { return data.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("HttpClient requires ASCII support"); } } /** * 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, int offset, int length) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } try { return new String(data, offset, length, "US-ASCII"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("HttpClient requires ASCII support"); } } /** * 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) { return getAsciiString(data, 0, data.length); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpContentTooLargeException.java100644 0 0 1000 10661532627 30334 0ustar 0 0 package org.apache.commons.httpclient; /** * Signals that the response content was larger than anticipated. * * @author Ortwin Glck */ public class HttpContentTooLargeException extends HttpException { private int maxlen; public HttpContentTooLargeException(String message, int maxlen) { super(message); this.maxlen = maxlen; } /** * @return the maximum anticipated content length in bytes. */ public int getMaxLength() { return maxlen; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpException.java100644 0 0 20325 10661532626 25376 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpException.java,v 1.19 2004/09/30 18:53:20 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.lang.reflect.Method; /** * Signals that an HTTP or HttpClient exception has occurred. * * @author Laura Werner * * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ */ public class HttpException extends IOException { /** * Creates a new HttpException with a null detail message. */ public HttpException() { super(); this.cause = null; } /** * Creates a new HttpException with the specified detail message. * * @param message the exception detail message */ public HttpException(String message) { super(message); this.cause = null; } /** * Creates a new HttpException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable * * @since 3.0 */ public HttpException(String message, Throwable cause) { super(message); this.cause = cause; // If we're running on JDK 1.4 or later, tell Throwable what the cause was try { Class[] paramsClasses = new Class[] { Throwable.class }; Method initCause = Throwable.class.getMethod("initCause", paramsClasses); initCause.invoke(this, new Object[] { cause }); } catch (Exception e) { // The setCause method must not be available } } /** * Return the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable. * * @return the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable * * @since 3.0 */ public Throwable getCause() { return cause; } /** * Print this HttpException and its stack trace to the standard error stream. * * @since 3.0 */ public void printStackTrace() { printStackTrace(System.err); } /** * Print this HttpException and its stack trace to the specified print stream. * * @param s the PrintStream to which the exception and its stack trace * should be written * * @since 3.0 */ public void printStackTrace(PrintStream s) { try { // JDK 1.4 has a nice printStackTrace method that prints the cause's stack // trace too and prunes out duplicate stack frames. Call it if possible, // which is determined by checking whether JDK 1.4's getStackTrace method is present Class[] paramsClasses = new Class[] { }; this.getClass().getMethod("getStackTrace", paramsClasses); super.printStackTrace(s); } catch (Exception ex) { // If that didn't work, print it out ourselves // First print this exception's stack trace. super.printStackTrace(s); if (cause != null) { // Print out the exception that caused this one. // This will recurse if the cause is another HttpException. s.print("Caused by: "); cause.printStackTrace(s); } } } /** * Print this HttpException and its stack trace to the specified print writer. * * @param s the PrintWriter to which the exception and its stack trace * should be written * * @since 3.0 */ public void printStackTrace(PrintWriter s) { try { // JDK 1.4 has a nice printStackTrace method that prints the cause's stack // trace too and prunes out duplicate stack frames. Call it if possible, // which is determined by checking whether JDK 1.4's getStackTrace method is present Class[] paramsClasses = new Class[] { }; this.getClass().getMethod("getStackTrace", paramsClasses); super.printStackTrace(s); } catch (Exception ex) { // If that didn't work, print it out ourselves // First print this exception's stack trace. super.printStackTrace(s); if (cause != null) { // Print out the exception that caused this one. // This will recurse if the cause is another HttpException. s.print("Caused by: "); cause.printStackTrace(s); } } } /** * Sets the text description of the reason for an exception. * * @param reason The reason for the exception. * * @deprecated HttpClient no longer uses this for itself. It is only * provided for compatibility with existing clients, and will be removed * in a future release. */ public void setReason(String reason) { this.reason = reason; } /** * Get the text description of the reason for an exception. * * @deprecated HttpClient no longer uses this for itself. It is only * provided for compatibility with existing clients, and will be removed * in a future release. */ public String getReason() { return reason; } /** * Sets the status code description of the reason for an exception. * * @param code The reason for the exception. This is intended to be an * HTTP status code. * * @deprecated HttpClient no longer uses this for itself. It is only * provided for compatibility with existing clients, and will be removed * in a future release. */ public void setReasonCode(int code) { reasonCode = code; } /** * Get the status code description of the reason for an exception. * * @deprecated HttpClient no longer uses this for itself. It is only * provided for compatibility with existing clients, and will be removed * in a future release. */ public int getReasonCode() { return this.reasonCode; } /** * A "reason" string provided for compatibility with older clients. * * @deprecated HttpClient no longer uses this field for itself. It * is only provided for compatibility with existing clients. */ private String reason; /** * Reason code for compatibility with older clients. * * @deprecated HttpClient no longer uses this field for itself. * It is only provided for compatibility with existing clients. */ private int reasonCode = HttpStatus.SC_OK; /** The original Throwable representing the cause of this error */ private final Throwable cause; } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpHost.java100644 0 0 15406 10661532627 24362 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpHost.java,v 1.3 2005/01/14 21:16:40 olegk Exp $ * $Revision: 510587 $ * $Date: 2007-02-22 17:56:08 +0100 (Thu, 22 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.util.LangUtils; /** * Holds all of the variables needed to describe an HTTP connection to a host. This includes * remote host, port and protocol. * * @author Michael Becke * @author Mike Bowler * @author Oleg Kalnichevski * @author Laura Werner * * @since 3.0 */ public class HttpHost implements Cloneable { /** The host to use. */ private String hostname = null; /** The port to use. */ private int port = -1; /** The protocol */ private Protocol protocol = null; /** * Constructor for HttpHost. * * @param hostname the hostname (IP or DNS name). Can be null. * @param port the port. Value -1 can be used to set default protocol port * @param protocol the protocol. Value null can be used to set default protocol */ public HttpHost(final String hostname, int port, final Protocol protocol) { super(); if (hostname == null) { throw new IllegalArgumentException("Host name may not be null"); } if (protocol == null) { throw new IllegalArgumentException("Protocol may not be null"); } this.hostname = hostname; this.protocol = protocol; if (port >= 0) { this.port = port; } else { this.port = this.protocol.getDefaultPort(); } } /** * Constructor for HttpHost. * * @param hostname the hostname (IP or DNS name). Can be null. * @param port the port. Value -1 can be used to set default protocol port */ public HttpHost(final String hostname, int port) { this(hostname, port, Protocol.getProtocol("http")); } /** * Constructor for HttpHost. * * @param hostname the hostname (IP or DNS name). Can be null. */ public HttpHost(final String hostname) { this(hostname, -1, Protocol.getProtocol("http")); } /** * URI constructor for HttpHost. * * @param uri the URI. */ public HttpHost(final URI uri) throws URIException { this(uri.getHost(), uri.getPort(), Protocol.getProtocol(uri.getScheme())); } /** * Copy constructor for HttpHost * * @param httphost the HTTP host to copy details from */ public HttpHost (final HttpHost httphost) { super(); init(httphost); } private void init(final HttpHost httphost) { this.hostname = httphost.hostname; this.port = httphost.port; this.protocol = httphost.protocol; } /** * @throws CloneNotSupportedException * @see java.lang.Object#clone() */ public Object clone() throws CloneNotSupportedException { HttpHost copy = (HttpHost) super.clone(); copy.init(this); return copy; } /** * Returns the host name (IP or DNS name). * * @return the host name (IP or DNS name), or null if not set */ public String getHostName() { return this.hostname; } /** * Returns the port. * * @return the host port, or -1 if not set */ public int getPort() { return this.port; } /** * Returns the protocol. * @return The protocol. */ public Protocol getProtocol() { return this.protocol; } /** * Return the host uri. * * @return The host uri. */ public String toURI() { StringBuffer buffer = new StringBuffer(50); buffer.append(this.protocol.getScheme()); buffer.append("://"); buffer.append(this.hostname); if (this.port != this.protocol.getDefaultPort()) { buffer.append(':'); buffer.append(this.port); } return buffer.toString(); } /** * @see java.lang.Object#toString() */ public String toString() { StringBuffer buffer = new StringBuffer(50); buffer.append(toURI()); return buffer.toString(); } /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(final Object o) { if (o instanceof HttpHost) { // shortcut if we're comparing with ourselves if (o == this) { return true; } HttpHost that = (HttpHost) o; if (!this.hostname.equalsIgnoreCase(that.hostname)) { return false; } if (this.port != that.port) { return false; } if (!this.protocol.equals(that.protocol)) { return false; } // everything matches return true; } else { return false; } } /** * @see java.lang.Object#hashCode() */ public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.hostname); hash = LangUtils.hashCode(hash, this.port); hash = LangUtils.hashCode(hash, this.protocol); return hash; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpMethod.java100644 0 0 50303 10661532626 24657 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethod.java,v 1.43 2004/10/07 16:14:15 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.auth.AuthState; import org.apache.commons.httpclient.params.HttpMethodParams; /** *

* HttpMethod interface represents a request to be sent via a * {@link HttpConnection HTTP connection} and a corresponding response. *

* @author Remy Maucherat * @author Rod Waldhoff * @author Jeff Dever * @author Mike Bowler * @author Oleg Kalnichevski * * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * @since 1.0 */ public interface HttpMethod { // ------------------------------------------- Property Setters and Getters /** * Obtains the name of the HTTP method as used in the HTTP request line, * for example "GET" or "POST". * * @return the name of this method */ String getName(); /** * Gets the host configuration for this method. The configuration specifies * the server, port, protocol, and proxy server via which this method will * send its HTTP request. * * @deprecated no longer applicable * * @return the HostConfiguration or null if none is set */ HostConfiguration getHostConfiguration(); /** * Sets the path of the HTTP method. * It is responsibility of the caller to ensure that the path is * properly encoded (URL safe). * * @param path The path of the HTTP method. The path is expected * to be URL encoded. */ void setPath(String path); /** * Returns the path of the HTTP method. * * Calling this method after the request has been executed will * return the actual path, following any redirects automatically * handled by this HTTP method. * * @return the path of the HTTP method, in URL encoded form */ String getPath(); /** * Returns the URI for this method. The URI will be absolute if the host * configuration has been set and relative otherwise. * * @return the URI for this method * * @throws URIException if a URI cannot be constructed */ URI getURI() throws URIException; /** * Sets the URI for this method. * * @param uri URI to be set * * @throws URIException if a URI cannot be set * * @since 3.0 */ void setURI(URI uri) throws URIException; /** * Defines how strictly the method follows the HTTP protocol specification. * (See RFC 2616 and other relevant RFCs.) In the strict mode the method precisely * implements the requirements of the specification, whereas in non-strict mode * it attempts to mimic the exact behaviour of commonly used HTTP agents, * which many HTTP servers expect. * * @param strictMode true for strict mode, false otherwise * * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)} * to exercise a more granular control over HTTP protocol strictness. * * @see #isStrictMode() */ void setStrictMode(boolean strictMode); /** * Returns the value of the strict mode flag. * * @return true if strict mode is enabled, false otherwise * * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)} * to exercise a more granular control over HTTP protocol strictness. * * @see #setStrictMode(boolean) */ boolean isStrictMode(); /** * Sets the specified request header, overwriting any * previous value. * Note that header-name matching is case insensitive. * @param headerName the header's name * @param headerValue the header's value * * @see #setRequestHeader(Header) * @see #getRequestHeader(String) * @see #removeRequestHeader(String) */ void setRequestHeader(String headerName, String headerValue); /** * Sets the specified request header, overwriting any * previous value. * Note that header-name matching is case insensitive. * @param header the header to be set * * @see #setRequestHeader(String,String) * @see #getRequestHeader(String) * @see #removeRequestHeader(String) */ void setRequestHeader(Header header); /** * Adds the specified request header, not overwriting any previous value. * If the same header is added multiple times, perhaps with different values, * multiple instances of that header will be sent in the HTTP request. * Note that header-name matching is case insensitive. * @param headerName the header's name * @param headerValue the header's value * * @see #addRequestHeader(Header) * @see #getRequestHeader(String) * @see #removeRequestHeader(String) */ void addRequestHeader(String headerName, String headerValue); /** * Adds the specified request header, not overwriting any previous value. * If the same header is added multiple times, perhaps with different values, * multiple instances of that header will be sent in the HTTP request. * Note that header-name matching is case insensitive. * @param header the header * * @see #addRequestHeader(String,String) * @see #getRequestHeader(String) * @see #removeRequestHeader(String) */ void addRequestHeader(Header header); /** * Gets the request header with the given name. * If there are multiple headers with the same name, * there values will be combined with the ',' separator as specified by RFC2616. * Note that header-name matching is case insensitive. * @param headerName the header name * @return the header */ Header getRequestHeader(String headerName); /** * Removes all request headers with the given name. * Note that header-name matching is case insensitive. * @param headerName the header name */ void removeRequestHeader(String headerName); /** * Removes the given request header. * * @param header the header * * @since 3.0 */ void removeRequestHeader(Header header); /** * Returns true if the HTTP method should automatically follow HTTP redirects * (status code 302, etc.), false otherwise. * * @return true if the method will automatically follow HTTP redirects, * false otherwise */ boolean getFollowRedirects(); /** * Sets whether or not the HTTP method should automatically follow HTTP redirects * (status code 302, etc.) * * @param followRedirects true if the method will automatically follow redirects, * false otherwise. */ void setFollowRedirects(boolean followRedirects); /** * Sets the query string of the HTTP method. * It is responsibility of the caller to ensure that the path is * properly encoded (URL safe). The string must not include an initial '?' character. * * @param queryString the query to be used in the request, with no leading '?' character * * @see #getQueryString() * @see #setQueryString(NameValuePair[]) */ void setQueryString(String queryString); /** * Sets the query string of this HTTP method. The pairs are encoded as UTF-8 characters. * To use a different charset the parameters can be encoded manually using EncodingUtil * and set as a single String. * * @param params An array of NameValuePairs to use as the query string. * The name/value pairs will be automatically URL encoded and should not * have been encoded previously. * * @see #getQueryString() * @see #setQueryString(String) * @see org.apache.commons.httpclient.util.EncodingUtil#formUrlEncode(NameValuePair[], String) */ void setQueryString(NameValuePair[] params); /** * Returns the query string of this HTTP method. * * @return the query string in URL encoded form, without a leading '?'. * * @see #setQueryString(NameValuePair[]) * @see #setQueryString(String) */ String getQueryString(); /** * Returns the current request headers for this HTTP method. The returned headers * will be in the same order that they were added with addRequestHeader. * If there are multiple request headers with the same name (e.g. Cookie), * they will be returned as multiple entries in the array. * * @return an array containing all of the request headers * * @see #addRequestHeader(Header) * @see #addRequestHeader(String,String) */ Header[] getRequestHeaders(); /** * Returns the request headers with the given name. Note that header-name matching is * case insensitive. * @param headerName the name of the headers to be returned. * @return an array of zero or more headers * * @since 3.0 */ Header[] getRequestHeaders(String headerName); // ---------------------------------------------------------------- Queries /** * Returns true the method is ready to execute, false otherwise. * * @return true if the method is ready to execute, false otherwise. */ boolean validate(); /** * Returns the status code associated with the latest response. * * @return The status code from the most recent execution of this method. * If the method has not yet been executed, the result is undefined. */ int getStatusCode(); /** * Returns the status text (or "reason phrase") associated with the latest * response. * * @return The status text from the most recent execution of this method. * If the method has not yet been executed, the result is undefined. */ String getStatusText(); /** * Returns the response headers from the most recent execution of this request. * * @return A newly-created array containing all of the response headers, * in the order in which they appeared in the response. */ Header[] getResponseHeaders(); /** * Returns the specified response header. Note that header-name matching is * case insensitive. * * @param headerName The name of the header to be returned. * * @return The specified response header. If the repsonse contained multiple * instances of the header, its values will be combined using the ',' * separator as specified by RFC2616. */ Header getResponseHeader(String headerName); /** * Returns the response headers with the given name. Note that header-name matching is * case insensitive. * @param headerName the name of the headers to be returned. * @return an array of zero or more headers * * @since 3.0 */ Header[] getResponseHeaders(String headerName); /** * Returns the response footers from the most recent execution of this request. * * @return an array containing the response footers in the order that they * appeared in the response. If the response had no footers, * an empty array will be returned. */ Header[] getResponseFooters(); /** * Return the specified response footer. Note that footer-name matching is * case insensitive. * * @param footerName The name of the footer. * @return The response footer. */ Header getResponseFooter(String footerName); /** * Returns the response body of the HTTP method, if any, as an array of bytes. * If the method has not yet been executed or the response has no body, null * is returned. Note that this method does not propagate I/O exceptions. * If an error occurs while reading the body, null will be returned. * * @return The response body, or null if the * body is not available. * * @throws IOException if an I/O (transport) problem occurs */ byte[] getResponseBody() throws IOException; /** * Returns the response body of the HTTP method, if any, as a {@link String}. * If response body is not available or cannot be read, null is returned. * The raw bytes in the body are converted to a String using the * character encoding specified in the response's Content-Type header, or * ISO-8859-1 if the response did not specify a character set. *

* Note that this method does not propagate I/O exceptions. * If an error occurs while reading the body, null will be returned. * * @return The response body converted to a String, or null * if the body is not available. * * @throws IOException if an I/O (transport) problem occurs */ String getResponseBodyAsString() throws IOException; /** * Returns the response body of the HTTP method, if any, as an InputStream. * If the response had no body or the method has not yet been executed, * null is returned. Additionally, null may be returned * if {@link #releaseConnection} has been called or * if this method was called previously and the resulting stream was closed. * * @return The response body, or null if it is not available * * @throws IOException if an I/O (transport) problem occurs */ InputStream getResponseBodyAsStream() throws IOException; /** * Returns true if the HTTP method has been already {@link #execute executed}, * but not {@link #recycle recycled}. * * @return true if the method has been executed, false otherwise */ boolean hasBeenUsed(); // --------------------------------------------------------- Action Methods /** * Executes this method using the specified HttpConnection and * HttpState. * * @param state the {@link HttpState state} information to associate with this method * @param connection the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException If an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException If a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @return the integer status code if one was obtained, or -1 */ int execute(HttpState state, HttpConnection connection) throws HttpException, IOException; /** * Aborts the execution of the HTTP method. * * @see #execute(HttpState, HttpConnection) * * @since 3.0 */ void abort(); /** * Recycles the HTTP method so that it can be used again. * Note that all of the instance variables will be reset * once this method has been called. This method will also * release the connection being used by this HTTP method. * * @see #releaseConnection() * * @deprecated no longer supported and will be removed in the future * version of HttpClient */ void recycle(); /** * Releases the connection being used by this HTTP method. In particular the * connection is used to read the response (if there is one) and will be held * until the response has been read. If the connection can be reused by other * HTTP methods it is NOT closed at this point. *

* After this method is called, {@link #getResponseBodyAsStream} will return * null, and {@link #getResponseBody} and {@link #getResponseBodyAsString} * may return null. */ void releaseConnection(); /** * Add a footer to this method's response. *

* Note: This method is for * internal use only and should not be called by external clients. * * @param footer the footer to add * * @since 2.0 */ void addResponseFooter(Header footer); /** * Returns the Status-Line from the most recent response for this method, * or null if the method has not been executed. * * @return the status line, or null if the method has not been executed * * @since 2.0 */ StatusLine getStatusLine(); /** * Returns true if the HTTP method should automatically handle HTTP * authentication challenges (status code 401, etc.), false otherwise * * @return true if authentication challenges will be processed * automatically, false otherwise. * * @since 2.0 * * @see #setDoAuthentication(boolean) */ boolean getDoAuthentication(); /** * Sets whether or not the HTTP method should automatically handle HTTP * authentication challenges (status code 401, etc.) * * @param doAuthentication true to process authentication challenges * automatically, false otherwise. * * @since 2.0 * * @see #getDoAuthentication() */ void setDoAuthentication(boolean doAuthentication); /** * Returns {@link HttpMethodParams HTTP protocol parameters} associated with this method. * * @since 3.0 * * @see HttpMethodParams */ public HttpMethodParams getParams(); /** * Assigns {@link HttpMethodParams HTTP protocol parameters} for this method. * * @since 3.0 * * @see HttpMethodParams */ public void setParams(final HttpMethodParams params); /** * Returns the target host {@link AuthState authentication state} * * @return host authentication state * * @since 3.0 */ public AuthState getHostAuthState(); /** * Returns the proxy {@link AuthState authentication state} * * @return host authentication state * * @since 3.0 */ public AuthState getProxyAuthState(); /** * Returns true if the HTTP has been transmitted to the target * server in its entirety, false otherwise. This flag can be useful * for recovery logic. If the request has not been transmitted in its entirety, * it is safe to retry the failed method. * * @return true if the request has been sent, false otherwise */ boolean isRequestSent(); } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpMethodBase.java100644 0 0 267041 10661532627 25504 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethodBase.java,v 1.222 2005/01/14 21:16:40 olegk Exp $ * $Revision: 539441 $ * $Date: 2007-05-18 14:56:55 +0200 (Fri, 18 May 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.util.Collection; import org.apache.commons.httpclient.auth.AuthState; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.cookie.CookieVersionSupport; import org.apache.commons.httpclient.cookie.MalformedCookieException; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.util.EncodingUtil; import org.apache.commons.httpclient.util.ExceptionUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * An abstract base implementation of HttpMethod. *

* At minimum, subclasses will need to override: *

    *
  • {@link #getName} to return the approriate name for this method *
  • *
*

* *

* When a method requires additional request headers, subclasses will typically * want to override: *

    *
  • {@link #addRequestHeaders addRequestHeaders(HttpState,HttpConnection)} * to write those headers *
  • *
*

* *

* When a method expects specific response headers, subclasses may want to * override: *

    *
  • {@link #processResponseHeaders processResponseHeaders(HttpState,HttpConnection)} * to handle those headers *
  • *
*

* * * @author Remy Maucherat * @author Rodney Waldhoff * @author Sean C. Sullivan * @author dIon Gillard * @author Jeff Dever * @author Davanum Srinivas * @author Ortwin Glueck * @author Eric Johnson * @author Michael Becke * @author Oleg Kalnichevski * @author Mike Bowler * @author Gary Gregory * @author Christian Kohlschuetter * * @version $Revision: 539441 $ $Date: 2007-05-18 14:56:55 +0200 (Fri, 18 May 2007) $ */ public abstract class HttpMethodBase implements HttpMethod { // -------------------------------------------------------------- Constants /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HttpMethodBase.class); // ----------------------------------------------------- Instance variables /** Request headers, if any. */ private HeaderGroup requestHeaders = new HeaderGroup(); /** The Status-Line from the response. */ protected StatusLine statusLine = null; /** Response headers, if any. */ private HeaderGroup responseHeaders = new HeaderGroup(); /** Response trailer headers, if any. */ private HeaderGroup responseTrailerHeaders = new HeaderGroup(); /** Path of the HTTP method. */ private String path = null; /** Query string of the HTTP method, if any. */ private String queryString = null; /** The response body of the HTTP method, assuming it has not be * intercepted by a sub-class. */ private InputStream responseStream = null; /** The connection that the response stream was read from. */ private HttpConnection responseConnection = null; /** Buffer for the response */ private byte[] responseBody = null; /** True if the HTTP method should automatically follow HTTP redirects.*/ private boolean followRedirects = false; /** True if the HTTP method should automatically handle * HTTP authentication challenges. */ private boolean doAuthentication = true; /** HTTP protocol parameters. */ private HttpMethodParams params = new HttpMethodParams(); /** Host authentication state */ private AuthState hostAuthState = new AuthState(); /** Proxy authentication state */ private AuthState proxyAuthState = new AuthState(); /** True if this method has already been executed. */ private boolean used = false; /** Count of how many times did this HTTP method transparently handle * a recoverable exception. */ private int recoverableExceptionCount = 0; /** the host for this HTTP method, can be null */ private HttpHost httphost = null; /** * Handles method retries * * @deprecated no loner used */ private MethodRetryHandler methodRetryHandler; /** True if the connection must be closed when no longer needed */ private boolean connectionCloseForced = false; /** Number of milliseconds to wait for 100-contunue response. */ private static final int RESPONSE_WAIT_TIME_MS = 3000; /** HTTP protocol version used for execution of this method. */ protected HttpVersion effectiveVersion = null; /** Whether the execution of this method has been aborted */ private volatile boolean aborted = false; /** Whether the HTTP request has been transmitted to the target * server it its entirety */ private boolean requestSent = false; /** Actual cookie policy */ private CookieSpec cookiespec = null; /** Default initial size of the response buffer if content length is unknown. */ private static final int DEFAULT_INITIAL_BUFFER_SIZE = 4*1024; // 4 kB // ----------------------------------------------------------- Constructors /** * No-arg constructor. */ public HttpMethodBase() { } /** * Constructor specifying a URI. * It is responsibility of the caller to ensure that URI elements * (path & query parameters) are properly encoded (URL safe). * * @param uri either an absolute or relative URI. The URI is expected * to be URL-encoded * * @throws IllegalArgumentException when URI is invalid * @throws IllegalStateException when protocol of the absolute URI is not recognised */ public HttpMethodBase(String uri) throws IllegalArgumentException, IllegalStateException { try { // create a URI and allow for null/empty uri values if (uri == null || uri.equals("")) { uri = "/"; } String charset = getParams().getUriCharset(); setURI(new URI(uri, true, charset)); } catch (URIException e) { throw new IllegalArgumentException("Invalid uri '" + uri + "': " + e.getMessage() ); } } // ------------------------------------------- Property Setters and Getters /** * Obtains the name of the HTTP method as used in the HTTP request line, * for example "GET" or "POST". * * @return the name of this method */ public abstract String getName(); /** * Returns the URI of the HTTP method * * @return The URI * * @throws URIException If the URI cannot be created. * * @see org.apache.commons.httpclient.HttpMethod#getURI() */ public URI getURI() throws URIException { StringBuffer buffer = new StringBuffer(); if (this.httphost != null) { buffer.append(this.httphost.getProtocol().getScheme()); buffer.append("://"); buffer.append(this.httphost.getHostName()); int port = this.httphost.getPort(); if (port != -1 && port != this.httphost.getProtocol().getDefaultPort()) { buffer.append(":"); buffer.append(port); } } buffer.append(this.path); if (this.queryString != null) { buffer.append('?'); buffer.append(this.queryString); } String charset = getParams().getUriCharset(); return new URI(buffer.toString(), true, charset); } /** * Sets the URI for this method. * * @param uri URI to be set * * @throws URIException if a URI cannot be set * * @since 3.0 */ public void setURI(URI uri) throws URIException { // only set the host if specified by the URI if (uri.isAbsoluteURI()) { this.httphost = new HttpHost(uri); } // set the path, defaulting to root setPath( uri.getPath() == null ? "/" : uri.getEscapedPath() ); setQueryString(uri.getEscapedQuery()); } /** * Sets whether or not the HTTP method should automatically follow HTTP redirects * (status code 302, etc.) * * @param followRedirects true if the method will automatically follow redirects, * false otherwise. */ public void setFollowRedirects(boolean followRedirects) { this.followRedirects = followRedirects; } /** * Returns true if the HTTP method should automatically follow HTTP redirects * (status code 302, etc.), false otherwise. * * @return true if the method will automatically follow HTTP redirects, * false otherwise. */ public boolean getFollowRedirects() { return this.followRedirects; } /** Sets whether version 1.1 of the HTTP protocol should be used per default. * * @param http11 true to use HTTP/1.1, false to use 1.0 * * @deprecated Use {@link HttpMethodParams#setVersion(HttpVersion)} */ public void setHttp11(boolean http11) { if (http11) { this.params.setVersion(HttpVersion.HTTP_1_1); } else { this.params.setVersion(HttpVersion.HTTP_1_0); } } /** * Returns true if the HTTP method should automatically handle HTTP * authentication challenges (status code 401, etc.), false otherwise * * @return true if authentication challenges will be processed * automatically, false otherwise. * * @since 2.0 */ public boolean getDoAuthentication() { return doAuthentication; } /** * Sets whether or not the HTTP method should automatically handle HTTP * authentication challenges (status code 401, etc.) * * @param doAuthentication true to process authentication challenges * authomatically, false otherwise. * * @since 2.0 */ public void setDoAuthentication(boolean doAuthentication) { this.doAuthentication = doAuthentication; } // ---------------------------------------------- Protected Utility Methods /** * Returns true if version 1.1 of the HTTP protocol should be * used per default, false if version 1.0 should be used. * * @return true to use HTTP/1.1, false to use 1.0 * * @deprecated Use {@link HttpMethodParams#getVersion()} */ public boolean isHttp11() { return this.params.getVersion().equals(HttpVersion.HTTP_1_1); } /** * Sets the path of the HTTP method. * It is responsibility of the caller to ensure that the path is * properly encoded (URL safe). * * @param path the path of the HTTP method. The path is expected * to be URL-encoded */ public void setPath(String path) { this.path = path; } /** * Adds the specified request header, NOT overwriting any previous value. * Note that header-name matching is case insensitive. * * @param header the header to add to the request */ public void addRequestHeader(Header header) { LOG.trace("HttpMethodBase.addRequestHeader(Header)"); if (header == null) { LOG.debug("null header value ignored"); } else { getRequestHeaderGroup().addHeader(header); } } /** * Use this method internally to add footers. * * @param footer The footer to add. */ public void addResponseFooter(Header footer) { getResponseTrailerHeaderGroup().addHeader(footer); } /** * Gets the path of this HTTP method. * Calling this method after the request has been executed will * return the actual path, following any redirects automatically * handled by this HTTP method. * * @return the path to request or "/" if the path is blank. */ public String getPath() { return (path == null || path.equals("")) ? "/" : path; } /** * Sets the query string of this HTTP method. The caller must ensure that the string * is properly URL encoded. The query string should not start with the question * mark character. * * @param queryString the query string * * @see EncodingUtil#formUrlEncode(NameValuePair[], String) */ public void setQueryString(String queryString) { this.queryString = queryString; } /** * Sets the query string of this HTTP method. The pairs are encoded as UTF-8 characters. * To use a different charset the parameters can be encoded manually using EncodingUtil * and set as a single String. * * @param params an array of {@link NameValuePair}s to add as query string * parameters. The name/value pairs will be automcatically * URL encoded * * @see EncodingUtil#formUrlEncode(NameValuePair[], String) * @see #setQueryString(String) */ public void setQueryString(NameValuePair[] params) { LOG.trace("enter HttpMethodBase.setQueryString(NameValuePair[])"); queryString = EncodingUtil.formUrlEncode(params, "UTF-8"); } /** * Gets the query string of this HTTP method. * * @return The query string */ public String getQueryString() { return queryString; } /** * Set the specified request header, overwriting any previous value. Note * that header-name matching is case-insensitive. * * @param headerName the header's name * @param headerValue the header's value */ public void setRequestHeader(String headerName, String headerValue) { Header header = new Header(headerName, headerValue); setRequestHeader(header); } /** * Sets the specified request header, overwriting any previous value. * Note that header-name matching is case insensitive. * * @param header the header */ public void setRequestHeader(Header header) { Header[] headers = getRequestHeaderGroup().getHeaders(header.getName()); for (int i = 0; i < headers.length; i++) { getRequestHeaderGroup().removeHeader(headers[i]); } getRequestHeaderGroup().addHeader(header); } /** * Returns the specified request header. Note that header-name matching is * case insensitive. null will be returned if either * headerName is null or there is no matching header for * headerName. * * @param headerName The name of the header to be returned. * * @return The specified request header. * * @since 3.0 */ public Header getRequestHeader(String headerName) { if (headerName == null) { return null; } else { return getRequestHeaderGroup().getCondensedHeader(headerName); } } /** * Returns an array of the requests headers that the HTTP method currently has * * @return an array of my request headers. */ public Header[] getRequestHeaders() { return getRequestHeaderGroup().getAllHeaders(); } /** * @see org.apache.commons.httpclient.HttpMethod#getRequestHeaders(java.lang.String) */ public Header[] getRequestHeaders(String headerName) { return getRequestHeaderGroup().getHeaders(headerName); } /** * Gets the {@link HeaderGroup header group} storing the request headers. * * @return a HeaderGroup * * @since 2.0beta1 */ protected HeaderGroup getRequestHeaderGroup() { return requestHeaders; } /** * Gets the {@link HeaderGroup header group} storing the response trailer headers * as per RFC 2616 section 3.6.1. * * @return a HeaderGroup * * @since 2.0beta1 */ protected HeaderGroup getResponseTrailerHeaderGroup() { return responseTrailerHeaders; } /** * Gets the {@link HeaderGroup header group} storing the response headers. * * @return a HeaderGroup * * @since 2.0beta1 */ protected HeaderGroup getResponseHeaderGroup() { return responseHeaders; } /** * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders(java.lang.String) * * @since 3.0 */ public Header[] getResponseHeaders(String headerName) { return getResponseHeaderGroup().getHeaders(headerName); } /** * Returns the response status code. * * @return the status code associated with the latest response. */ public int getStatusCode() { return statusLine.getStatusCode(); } /** * Provides access to the response status line. * * @return the status line object from the latest response. * @since 2.0 */ public StatusLine getStatusLine() { return statusLine; } /** * Checks if response data is available. * @return true if response data is available, false otherwise. */ private boolean responseAvailable() { return (responseBody != null) || (responseStream != null); } /** * Returns an array of the response headers that the HTTP method currently has * in the order in which they were read. * * @return an array of response headers. */ public Header[] getResponseHeaders() { return getResponseHeaderGroup().getAllHeaders(); } /** * Gets the response header associated with the given name. Header name * matching is case insensitive. null will be returned if either * headerName is null or there is no matching header for * headerName. * * @param headerName the header name to match * * @return the matching header */ public Header getResponseHeader(String headerName) { if (headerName == null) { return null; } else { return getResponseHeaderGroup().getCondensedHeader(headerName); } } /** * Return the length (in bytes) of the response body, as specified in a * Content-Length header. * *

* Return -1 when the content-length is unknown. *

* * @return content length, if Content-Length header is available. * 0 indicates that the request has no body. * If Content-Length header is not present, the method * returns -1. */ public long getResponseContentLength() { Header[] headers = getResponseHeaderGroup().getHeaders("Content-Length"); if (headers.length == 0) { return -1; } if (headers.length > 1) { LOG.warn("Multiple content-length headers detected"); } for (int i = headers.length - 1; i >= 0; i--) { Header header = headers[i]; try { return Long.parseLong(header.getValue()); } catch (NumberFormatException e) { if (LOG.isWarnEnabled()) { LOG.warn("Invalid content-length value: " + e.getMessage()); } } // See if we can have better luck with another header, if present } return -1; } /** * Returns the response body of the HTTP method, if any, as an array of bytes. * If response body is not available or cannot be read, returns null. * Buffers the response and this method can be called several times yielding * the same result each time. * * Note: This will cause the entire response body to be buffered in memory. A * malicious server may easily exhaust all the VM memory. It is strongly * recommended, to use getResponseAsStream if the content length of the response * is unknown or resonably large. * * @return The response body. * * @throws IOException If an I/O (transport) problem occurs while obtaining the * response body. */ public byte[] getResponseBody() throws IOException { if (this.responseBody == null) { InputStream instream = getResponseBodyAsStream(); if (instream != null) { long contentLength = getResponseContentLength(); if (contentLength > Integer.MAX_VALUE) { //guard below cast from overflow throw new IOException("Content too large to be buffered: "+ contentLength +" bytes"); } int limit = getParams().getIntParameter(HttpMethodParams.BUFFER_WARN_TRIGGER_LIMIT, 1024*1024); if ((contentLength == -1) || (contentLength > limit)) { LOG.warn("Going to buffer response body of large or unknown size. " +"Using getResponseBodyAsStream instead is recommended."); } LOG.debug("Buffering response body"); ByteArrayOutputStream outstream = new ByteArrayOutputStream( contentLength > 0 ? (int) contentLength : DEFAULT_INITIAL_BUFFER_SIZE); byte[] buffer = new byte[4096]; int len; while ((len = instream.read(buffer)) > 0) { outstream.write(buffer, 0, len); } outstream.close(); setResponseStream(null); this.responseBody = outstream.toByteArray(); } } return this.responseBody; } /** * Returns the response body of the HTTP method, if any, as an array of bytes. * If response body is not available or cannot be read, returns null. * Buffers the response and this method can be called several times yielding * the same result each time. * * Note: This will cause the entire response body to be buffered in memory. This method is * safe if the content length of the response is unknown, because the amount of memory used * is limited.

* * If the response is large this method involves lots of array copying and many object * allocations, which makes it unsuitable for high-performance / low-footprint applications. * Those applications should use {@link #getResponseBodyAsStream()}. * * @param maxlen the maximum content length to accept (number of bytes). * @return The response body. * * @throws IOException If an I/O (transport) problem occurs while obtaining the * response body. */ public byte[] getResponseBody(int maxlen) throws IOException { if (maxlen < 0) throw new IllegalArgumentException("maxlen must be positive"); if (this.responseBody == null) { InputStream instream = getResponseBodyAsStream(); if (instream != null) { // we might already know that the content is larger long contentLength = getResponseContentLength(); if ((contentLength != -1) && (contentLength > maxlen)) { throw new HttpContentTooLargeException( "Content-Length is " + contentLength, maxlen); } LOG.debug("Buffering response body"); ByteArrayOutputStream rawdata = new ByteArrayOutputStream( contentLength > 0 ? (int) contentLength : DEFAULT_INITIAL_BUFFER_SIZE); byte[] buffer = new byte[2048]; int pos = 0; int len; do { len = instream.read(buffer, 0, Math.min(buffer.length, maxlen-pos)); if (len == -1) break; rawdata.write(buffer, 0, len); pos += len; } while (pos < maxlen); setResponseStream(null); // check if there is even more data if (pos == maxlen) { if (instream.read() != -1) throw new HttpContentTooLargeException( "Content-Length not known but larger than " + maxlen, maxlen); } this.responseBody = rawdata.toByteArray(); } } return this.responseBody; } /** * Returns the response body of the HTTP method, if any, as an {@link InputStream}. * If response body is not available, returns null. If the response has been * buffered this method returns a new stream object on every call. If the response * has not been buffered the returned stream can only be read once. * * @return The response body or null. * * @throws IOException If an I/O (transport) problem occurs while obtaining the * response body. */ public InputStream getResponseBodyAsStream() throws IOException { if (responseStream != null) { return responseStream; } if (responseBody != null) { InputStream byteResponseStream = new ByteArrayInputStream(responseBody); LOG.debug("re-creating response stream from byte array"); return byteResponseStream; } return null; } /** * Returns the response body of the HTTP method, if any, as a {@link String}. * If response body is not available or cannot be read, returns null * The string conversion on the data is done using the character encoding specified * in Content-Type header. Buffers the response and this method can be * called several times yielding the same result each time. * * Note: This will cause the entire response body to be buffered in memory. A * malicious server may easily exhaust all the VM memory. It is strongly * recommended, to use getResponseAsStream if the content length of the response * is unknown or resonably large. * * @return The response body or null. * * @throws IOException If an I/O (transport) problem occurs while obtaining the * response body. */ public String getResponseBodyAsString() throws IOException { byte[] rawdata = null; if (responseAvailable()) { rawdata = getResponseBody(); } if (rawdata != null) { return EncodingUtil.getString(rawdata, getResponseCharSet()); } else { return null; } } /** * Returns the response body of the HTTP method, if any, as a {@link String}. * If response body is not available or cannot be read, returns null * The string conversion on the data is done using the character encoding specified * in Content-Type header. Buffers the response and this method can be * called several times yielding the same result each time.

* * Note: This will cause the entire response body to be buffered in memory. This method is * safe if the content length of the response is unknown, because the amount of memory used * is limited.

* * If the response is large this method involves lots of array copying and many object * allocations, which makes it unsuitable for high-performance / low-footprint applications. * Those applications should use {@link #getResponseBodyAsStream()}. * * @param maxlen the maximum content length to accept (number of bytes). Note that, * depending on the encoding, this is not equal to the number of characters. * @return The response body or null. * * @throws IOException If an I/O (transport) problem occurs while obtaining the * response body. */ public String getResponseBodyAsString(int maxlen) throws IOException { if (maxlen < 0) throw new IllegalArgumentException("maxlen must be positive"); byte[] rawdata = null; if (responseAvailable()) { rawdata = getResponseBody(maxlen); } if (rawdata != null) { return EncodingUtil.getString(rawdata, getResponseCharSet()); } else { return null; } } /** * Returns an array of the response footers that the HTTP method currently has * in the order in which they were read. * * @return an array of footers */ public Header[] getResponseFooters() { return getResponseTrailerHeaderGroup().getAllHeaders(); } /** * Gets the response footer associated with the given name. * Footer name matching is case insensitive. * null will be returned if either footerName is * null or there is no matching footer for footerName * or there are no footers available. If there are multiple footers * with the same name, there values will be combined with the ',' separator * as specified by RFC2616. * * @param footerName the footer name to match * @return the matching footer */ public Header getResponseFooter(String footerName) { if (footerName == null) { return null; } else { return getResponseTrailerHeaderGroup().getCondensedHeader(footerName); } } /** * Sets the response stream. * @param responseStream The new response stream. */ protected void setResponseStream(InputStream responseStream) { this.responseStream = responseStream; } /** * Returns a stream from which the body of the current response may be read. * If the method has not yet been executed, if responseBodyConsumed * has been called, or if the stream returned by a previous call has been closed, * null will be returned. * * @return the current response stream */ protected InputStream getResponseStream() { return responseStream; } /** * Returns the status text (or "reason phrase") associated with the latest * response. * * @return The status text. */ public String getStatusText() { return statusLine.getReasonPhrase(); } /** * Defines how strictly HttpClient follows the HTTP protocol specification * (RFC 2616 and other relevant RFCs). In the strict mode HttpClient precisely * implements the requirements of the specification, whereas in non-strict mode * it attempts to mimic the exact behaviour of commonly used HTTP agents, * which many HTTP servers expect. * * @param strictMode true for strict mode, false otherwise * * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)} * to exercise a more granular control over HTTP protocol strictness. */ public void setStrictMode(boolean strictMode) { if (strictMode) { this.params.makeStrict(); } else { this.params.makeLenient(); } } /** * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)} * to exercise a more granular control over HTTP protocol strictness. * * @return false */ public boolean isStrictMode() { return false; } /** * Adds the specified request header, NOT overwriting any previous value. * Note that header-name matching is case insensitive. * * @param headerName the header's name * @param headerValue the header's value */ public void addRequestHeader(String headerName, String headerValue) { addRequestHeader(new Header(headerName, headerValue)); } /** * Tests if the connection should be force-closed when no longer needed. * * @return true if the connection must be closed */ protected boolean isConnectionCloseForced() { return this.connectionCloseForced; } /** * Sets whether or not the connection should be force-closed when no longer * needed. This value should only be set to true in abnormal * circumstances, such as HTTP protocol violations. * * @param b true if the connection must be closed, false * otherwise. */ protected void setConnectionCloseForced(boolean b) { if (LOG.isDebugEnabled()) { LOG.debug("Force-close connection: " + b); } this.connectionCloseForced = b; } /** * Tests if the connection should be closed after the method has been executed. * The connection will be left open when using HTTP/1.1 or if Connection: * keep-alive header was sent. * * @param conn the connection in question * * @return boolean true if we should close the connection. */ protected boolean shouldCloseConnection(HttpConnection conn) { // Connection must be closed due to an abnormal circumstance if (isConnectionCloseForced()) { LOG.debug("Should force-close connection."); return true; } Header connectionHeader = null; // In case being connected via a proxy server if (!conn.isTransparent()) { // Check for 'proxy-connection' directive connectionHeader = responseHeaders.getFirstHeader("proxy-connection"); } // In all cases Check for 'connection' directive // some non-complaint proxy servers send it instread of // expected 'proxy-connection' directive if (connectionHeader == null) { connectionHeader = responseHeaders.getFirstHeader("connection"); } // In case the response does not contain any explict connection // directives, check whether the request does if (connectionHeader == null) { connectionHeader = requestHeaders.getFirstHeader("connection"); } if (connectionHeader != null) { if (connectionHeader.getValue().equalsIgnoreCase("close")) { if (LOG.isDebugEnabled()) { LOG.debug("Should close connection in response to directive: " + connectionHeader.getValue()); } return true; } else if (connectionHeader.getValue().equalsIgnoreCase("keep-alive")) { if (LOG.isDebugEnabled()) { LOG.debug("Should NOT close connection in response to directive: " + connectionHeader.getValue()); } return false; } else { if (LOG.isDebugEnabled()) { LOG.debug("Unknown directive: " + connectionHeader.toExternalForm()); } } } LOG.debug("Resorting to protocol version default close connection policy"); // missing or invalid connection header, do the default if (this.effectiveVersion.greaterEquals(HttpVersion.HTTP_1_1)) { if (LOG.isDebugEnabled()) { LOG.debug("Should NOT close connection, using " + this.effectiveVersion.toString()); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Should close connection, using " + this.effectiveVersion.toString()); } } return this.effectiveVersion.lessEquals(HttpVersion.HTTP_1_0); } /** * Tests if the this method is ready to be executed. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} to be used * @throws HttpException If the method is in invalid state. */ private void checkExecuteConditions(HttpState state, HttpConnection conn) throws HttpException { if (state == null) { throw new IllegalArgumentException("HttpState parameter may not be null"); } if (conn == null) { throw new IllegalArgumentException("HttpConnection parameter may not be null"); } if (this.aborted) { throw new IllegalStateException("Method has been aborted"); } if (!validate()) { throw new ProtocolException("HttpMethodBase object not valid"); } } /** * Executes this method using the specified HttpConnection and * HttpState. * * @param state {@link HttpState state} information to associate with this * request. Must be non-null. * @param conn the {@link HttpConnection connection} to used to execute * this HTTP method. Must be non-null. * * @return the integer status code if one was obtained, or -1 * * @throws IOException if an I/O (transport) error occurs * @throws HttpException if a protocol exception occurs. */ public int execute(HttpState state, HttpConnection conn) throws HttpException, IOException { LOG.trace("enter HttpMethodBase.execute(HttpState, HttpConnection)"); // this is our connection now, assign it to a local variable so // that it can be released later this.responseConnection = conn; checkExecuteConditions(state, conn); this.statusLine = null; this.connectionCloseForced = false; conn.setLastResponseInputStream(null); // determine the effective protocol version if (this.effectiveVersion == null) { this.effectiveVersion = this.params.getVersion(); } writeRequest(state, conn); this.requestSent = true; readResponse(state, conn); // the method has successfully executed used = true; return statusLine.getStatusCode(); } /** * Aborts the execution of this method. * * @since 3.0 */ public void abort() { if (this.aborted) { return; } this.aborted = true; HttpConnection conn = this.responseConnection; if (conn != null) { conn.close(); } } /** * Returns true if the HTTP method has been already {@link #execute executed}, * but not {@link #recycle recycled}. * * @return true if the method has been executed, false otherwise */ public boolean hasBeenUsed() { return used; } /** * Recycles the HTTP method so that it can be used again. * Note that all of the instance variables will be reset * once this method has been called. This method will also * release the connection being used by this HTTP method. * * @see #releaseConnection() * * @deprecated no longer supported and will be removed in the future * version of HttpClient */ public void recycle() { LOG.trace("enter HttpMethodBase.recycle()"); releaseConnection(); path = null; followRedirects = false; doAuthentication = true; queryString = null; getRequestHeaderGroup().clear(); getResponseHeaderGroup().clear(); getResponseTrailerHeaderGroup().clear(); statusLine = null; effectiveVersion = null; aborted = false; used = false; params = new HttpMethodParams(); responseBody = null; recoverableExceptionCount = 0; connectionCloseForced = false; hostAuthState.invalidate(); proxyAuthState.invalidate(); cookiespec = null; requestSent = false; } /** * Releases the connection being used by this HTTP method. In particular the * connection is used to read the response(if there is one) and will be held * until the response has been read. If the connection can be reused by other * HTTP methods it is NOT closed at this point. * * @since 2.0 */ public void releaseConnection() { try { if (this.responseStream != null) { try { // FYI - this may indirectly invoke responseBodyConsumed. this.responseStream.close(); } catch (IOException ignore) { } } } finally { ensureConnectionRelease(); } } /** * Remove the request header associated with the given name. Note that * header-name matching is case insensitive. * * @param headerName the header name */ public void removeRequestHeader(String headerName) { Header[] headers = getRequestHeaderGroup().getHeaders(headerName); for (int i = 0; i < headers.length; i++) { getRequestHeaderGroup().removeHeader(headers[i]); } } /** * Removes the given request header. * * @param header the header */ public void removeRequestHeader(final Header header) { if (header == null) { return; } getRequestHeaderGroup().removeHeader(header); } // ---------------------------------------------------------------- Queries /** * Returns true the method is ready to execute, false otherwise. * * @return This implementation always returns true. */ public boolean validate() { return true; } /** * Returns the actual cookie policy * * @param state HTTP state. TODO: to be removed in the future * * @return cookie spec */ private CookieSpec getCookieSpec(final HttpState state) { if (this.cookiespec == null) { int i = state.getCookiePolicy(); if (i == -1) { this.cookiespec = CookiePolicy.getCookieSpec(this.params.getCookiePolicy()); } else { this.cookiespec = CookiePolicy.getSpecByPolicy(i); } this.cookiespec.setValidDateFormats( (Collection)this.params.getParameter(HttpMethodParams.DATE_PATTERNS)); } return this.cookiespec; } /** * Generates Cookie request headers for those {@link Cookie cookie}s * that match the given host, port and path. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected void addCookieRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.addCookieRequestHeader(HttpState, " + "HttpConnection)"); Header[] cookieheaders = getRequestHeaderGroup().getHeaders("Cookie"); for (int i = 0; i < cookieheaders.length; i++) { Header cookieheader = cookieheaders[i]; if (cookieheader.isAutogenerated()) { getRequestHeaderGroup().removeHeader(cookieheader); } } CookieSpec matcher = getCookieSpec(state); String host = this.params.getVirtualHost(); if (host == null) { host = conn.getHost(); } Cookie[] cookies = matcher.match(host, conn.getPort(), getPath(), conn.isSecure(), state.getCookies()); if ((cookies != null) && (cookies.length > 0)) { if (getParams().isParameterTrue(HttpMethodParams.SINGLE_COOKIE_HEADER)) { // In strict mode put all cookies on the same header String s = matcher.formatCookies(cookies); getRequestHeaderGroup().addHeader(new Header("Cookie", s, true)); } else { // In non-strict mode put each cookie on a separate header for (int i = 0; i < cookies.length; i++) { String s = matcher.formatCookie(cookies[i]); getRequestHeaderGroup().addHeader(new Header("Cookie", s, true)); } } if (matcher instanceof CookieVersionSupport) { CookieVersionSupport versupport = (CookieVersionSupport) matcher; int ver = versupport.getVersion(); boolean needVersionHeader = false; for (int i = 0; i < cookies.length; i++) { if (ver != cookies[i].getVersion()) { needVersionHeader = true; } } if (needVersionHeader) { // Advertise cookie version support getRequestHeaderGroup().addHeader(versupport.getVersionHeader()); } } } } /** * Generates Host request header, as long as no Host request * header already exists. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected void addHostRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.addHostRequestHeader(HttpState, " + "HttpConnection)"); // Per 19.6.1.1 of RFC 2616, it is legal for HTTP/1.0 based // applications to send the Host request-header. // TODO: Add the ability to disable the sending of this header for // HTTP/1.0 requests. String host = this.params.getVirtualHost(); if (host != null) { LOG.debug("Using virtual host name: " + host); } else { host = conn.getHost(); } int port = conn.getPort(); // Note: RFC 2616 uses the term "internet host name" for what goes on the // host line. It would seem to imply that host should be blank if the // host is a number instead of an name. Based on the behavior of web // browsers, and the fact that RFC 2616 never defines the phrase "internet // host name", and the bad behavior of HttpClient that follows if we // send blank, I interpret this as a small misstatement in the RFC, where // they meant to say "internet host". So IP numbers get sent as host // entries too. -- Eric Johnson 12/13/2002 if (LOG.isDebugEnabled()) { LOG.debug("Adding Host request header"); } //appends the port only if not using the default port for the protocol if (conn.getProtocol().getDefaultPort() != port) { host += (":" + port); } setRequestHeader("Host", host); } /** * Generates Proxy-Connection: Keep-Alive request header when * communicating via a proxy server. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected void addProxyConnectionHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.addProxyConnectionHeader(" + "HttpState, HttpConnection)"); if (!conn.isTransparent()) { if (getRequestHeader("Proxy-Connection") == null) { addRequestHeader("Proxy-Connection", "Keep-Alive"); } } } /** * Generates all the required request {@link Header header}s * to be submitted via the given {@link HttpConnection connection}. * *

* This implementation adds User-Agent, Host, * Cookie, Authorization, Proxy-Authorization * and Proxy-Connection headers, when appropriate. *

* *

* Subclasses may want to override this method to to add additional * headers, and may choose to invoke this implementation (via * super) to add the "standard" headers. *

* * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @see #writeRequestHeaders */ protected void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.addRequestHeaders(HttpState, " + "HttpConnection)"); addUserAgentRequestHeader(state, conn); addHostRequestHeader(state, conn); addCookieRequestHeader(state, conn); addProxyConnectionHeader(state, conn); } /** * Generates default User-Agent request header, as long as no * User-Agent request header already exists. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected void addUserAgentRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.addUserAgentRequestHeaders(HttpState, " + "HttpConnection)"); if (getRequestHeader("User-Agent") == null) { String agent = (String)getParams().getParameter(HttpMethodParams.USER_AGENT); if (agent == null) { agent = "Jakarta Commons-HttpClient"; } setRequestHeader("User-Agent", agent); } } /** * Throws an {@link IllegalStateException} if the HTTP method has been already * {@link #execute executed}, but not {@link #recycle recycled}. * * @throws IllegalStateException if the method has been used and not * recycled */ protected void checkNotUsed() throws IllegalStateException { if (used) { throw new IllegalStateException("Already used."); } } /** * Throws an {@link IllegalStateException} if the HTTP method has not been * {@link #execute executed} since last {@link #recycle recycle}. * * * @throws IllegalStateException if not used */ protected void checkUsed() throws IllegalStateException { if (!used) { throw new IllegalStateException("Not Used."); } } // ------------------------------------------------- Static Utility Methods /** * Generates HTTP request line according to the specified attributes. * * @param connection the {@link HttpConnection connection} used to execute * this HTTP method * @param name the method name generate a request for * @param requestPath the path string for the request * @param query the query string for the request * @param version the protocol version to use (e.g. HTTP/1.0) * * @return HTTP request line */ protected static String generateRequestLine(HttpConnection connection, String name, String requestPath, String query, String version) { LOG.trace("enter HttpMethodBase.generateRequestLine(HttpConnection, " + "String, String, String, String)"); StringBuffer buf = new StringBuffer(); // Append method name buf.append(name); buf.append(" "); // Absolute or relative URL? if (!connection.isTransparent()) { Protocol protocol = connection.getProtocol(); buf.append(protocol.getScheme().toLowerCase()); buf.append("://"); buf.append(connection.getHost()); if ((connection.getPort() != -1) && (connection.getPort() != protocol.getDefaultPort()) ) { buf.append(":"); buf.append(connection.getPort()); } } // Append path, if any if (requestPath == null) { buf.append("/"); } else { if (!connection.isTransparent() && !requestPath.startsWith("/")) { buf.append("/"); } buf.append(requestPath); } // Append query, if any if (query != null) { if (query.indexOf("?") != 0) { buf.append("?"); } buf.append(query); } // Append protocol buf.append(" "); buf.append(version); buf.append("\r\n"); return buf.toString(); } /** * This method is invoked immediately after * {@link #readResponseBody(HttpState,HttpConnection)} and can be overridden by * sub-classes in order to provide custom body processing. * *

* This implementation does nothing. *

* * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @see #readResponse * @see #readResponseBody */ protected void processResponseBody(HttpState state, HttpConnection conn) { } /** * This method is invoked immediately after * {@link #readResponseHeaders(HttpState,HttpConnection)} and can be overridden by * sub-classes in order to provide custom response headers processing. *

* This implementation will handle the Set-Cookie and * Set-Cookie2 headers, if any, adding the relevant cookies to * the given {@link HttpState}. *

* * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @see #readResponse * @see #readResponseHeaders */ protected void processResponseHeaders(HttpState state, HttpConnection conn) { LOG.trace("enter HttpMethodBase.processResponseHeaders(HttpState, " + "HttpConnection)"); CookieSpec parser = getCookieSpec(state); // process set-cookie headers Header[] headers = getResponseHeaderGroup().getHeaders("set-cookie"); processCookieHeaders(parser, headers, state, conn); // see if the cookie spec supports cookie versioning. if (parser instanceof CookieVersionSupport) { CookieVersionSupport versupport = (CookieVersionSupport) parser; if (versupport.getVersion() > 0) { // process set-cookie2 headers. // Cookie2 will replace equivalent Cookie instances headers = getResponseHeaderGroup().getHeaders("set-cookie2"); processCookieHeaders(parser, headers, state, conn); } } } /** * This method processes the specified cookie headers. It is invoked from * within {@link #processResponseHeaders(HttpState,HttpConnection)} * * @param headers cookie {@link Header}s to be processed * @param state the {@link HttpState state} information associated with * this HTTP method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method */ protected void processCookieHeaders( final CookieSpec parser, final Header[] headers, final HttpState state, final HttpConnection conn) { LOG.trace("enter HttpMethodBase.processCookieHeaders(Header[], HttpState, " + "HttpConnection)"); String host = this.params.getVirtualHost(); if (host == null) { host = conn.getHost(); } for (int i = 0; i < headers.length; i++) { Header header = headers[i]; Cookie[] cookies = null; try { cookies = parser.parse( host, conn.getPort(), getPath(), conn.isSecure(), header); } catch (MalformedCookieException e) { if (LOG.isWarnEnabled()) { LOG.warn("Invalid cookie header: \"" + header.getValue() + "\". " + e.getMessage()); } } if (cookies != null) { for (int j = 0; j < cookies.length; j++) { Cookie cookie = cookies[j]; try { parser.validate( host, conn.getPort(), getPath(), conn.isSecure(), cookie); state.addCookie(cookie); if (LOG.isDebugEnabled()) { LOG.debug("Cookie accepted: \"" + parser.formatCookie(cookie) + "\""); } } catch (MalformedCookieException e) { if (LOG.isWarnEnabled()) { LOG.warn("Cookie rejected: \"" + parser.formatCookie(cookie) + "\". " + e.getMessage()); } } } } } } /** * This method is invoked immediately after * {@link #readStatusLine(HttpState,HttpConnection)} and can be overridden by * sub-classes in order to provide custom response status line processing. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @see #readResponse * @see #readStatusLine */ protected void processStatusLine(HttpState state, HttpConnection conn) { } /** * Reads the response from the given {@link HttpConnection connection}. * *

* The response is processed as the following sequence of actions: * *

    *
  1. * {@link #readStatusLine(HttpState,HttpConnection)} is * invoked to read the request line. *
  2. *
  3. * {@link #processStatusLine(HttpState,HttpConnection)} * is invoked, allowing the method to process the status line if * desired. *
  4. *
  5. * {@link #readResponseHeaders(HttpState,HttpConnection)} is invoked to read * the associated headers. *
  6. *
  7. * {@link #processResponseHeaders(HttpState,HttpConnection)} is invoked, allowing * the method to process the headers if desired. *
  8. *
  9. * {@link #readResponseBody(HttpState,HttpConnection)} is * invoked to read the associated body (if any). *
  10. *
  11. * {@link #processResponseBody(HttpState,HttpConnection)} is invoked, allowing the * method to process the response body if desired. *
  12. *
* * Subclasses may want to override one or more of the above methods to to * customize the processing. (Or they may choose to override this method * if dramatically different processing is required.) *

* * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected void readResponse(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace( "enter HttpMethodBase.readResponse(HttpState, HttpConnection)"); // Status line & line may have already been received // if 'expect - continue' handshake has been used while (this.statusLine == null) { readStatusLine(state, conn); processStatusLine(state, conn); readResponseHeaders(state, conn); processResponseHeaders(state, conn); int status = this.statusLine.getStatusCode(); if ((status >= 100) && (status < 200)) { if (LOG.isInfoEnabled()) { LOG.info("Discarding unexpected response: " + this.statusLine.toString()); } this.statusLine = null; } } readResponseBody(state, conn); processResponseBody(state, conn); } /** * Read the response body from the given {@link HttpConnection}. * *

* The current implementation wraps the socket level stream with * an appropriate stream for the type of response (chunked, content-length, * or auto-close). If there is no response body, the connection associated * with the request will be returned to the connection manager. *

* *

* Subclasses may want to override this method to to customize the * processing. *

* * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @see #readResponse * @see #processResponseBody */ protected void readResponseBody(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace( "enter HttpMethodBase.readResponseBody(HttpState, HttpConnection)"); // assume we are not done with the connection if we get a stream InputStream stream = readResponseBody(conn); if (stream == null) { // done using the connection! responseBodyConsumed(); } else { conn.setLastResponseInputStream(stream); setResponseStream(stream); } } /** * Returns the response body as an {@link InputStream input stream} * corresponding to the values of the Content-Length and * Transfer-Encoding headers. If no response body is available * returns null. *

* * @see #readResponse * @see #processResponseBody * * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ private InputStream readResponseBody(HttpConnection conn) throws HttpException, IOException { LOG.trace("enter HttpMethodBase.readResponseBody(HttpConnection)"); responseBody = null; InputStream is = conn.getResponseInputStream(); if (Wire.CONTENT_WIRE.enabled()) { is = new WireLogInputStream(is, Wire.CONTENT_WIRE); } boolean canHaveBody = canResponseHaveBody(statusLine.getStatusCode()); InputStream result = null; Header transferEncodingHeader = responseHeaders.getFirstHeader("Transfer-Encoding"); // We use Transfer-Encoding if present and ignore Content-Length. // RFC2616, 4.4 item number 3 if (transferEncodingHeader != null) { String transferEncoding = transferEncodingHeader.getValue(); if (!"chunked".equalsIgnoreCase(transferEncoding) && !"identity".equalsIgnoreCase(transferEncoding)) { if (LOG.isWarnEnabled()) { LOG.warn("Unsupported transfer encoding: " + transferEncoding); } } HeaderElement[] encodings = transferEncodingHeader.getElements(); // The chunked encoding must be the last one applied // RFC2616, 14.41 int len = encodings.length; if ((len > 0) && ("chunked".equalsIgnoreCase(encodings[len - 1].getName()))) { // if response body is empty if (conn.isResponseAvailable(conn.getParams().getSoTimeout())) { result = new ChunkedInputStream(is, this); } else { if (getParams().isParameterTrue(HttpMethodParams.STRICT_TRANSFER_ENCODING)) { throw new ProtocolException("Chunk-encoded body declared but not sent"); } else { LOG.warn("Chunk-encoded body missing"); } } } else { LOG.info("Response content is not chunk-encoded"); // The connection must be terminated by closing // the socket as per RFC 2616, 3.6 setConnectionCloseForced(true); result = is; } } else { long expectedLength = getResponseContentLength(); if (expectedLength == -1) { if (canHaveBody && this.effectiveVersion.greaterEquals(HttpVersion.HTTP_1_1)) { Header connectionHeader = responseHeaders.getFirstHeader("Connection"); String connectionDirective = null; if (connectionHeader != null) { connectionDirective = connectionHeader.getValue(); } if (!"close".equalsIgnoreCase(connectionDirective)) { LOG.info("Response content length is not known"); setConnectionCloseForced(true); } } result = is; } else { result = new ContentLengthInputStream(is, expectedLength); } } // See if the response is supposed to have a response body if (!canHaveBody) { result = null; } // if there is a result - ALWAYS wrap it in an observer which will // close the underlying stream as soon as it is consumed, and notify // the watcher that the stream has been consumed. if (result != null) { result = new AutoCloseInputStream( result, new ResponseConsumedWatcher() { public void responseConsumed() { responseBodyConsumed(); } } ); } return result; } /** * Reads the response headers from the given {@link HttpConnection connection}. * *

* Subclasses may want to override this method to to customize the * processing. *

* *

* "It must be possible to combine the multiple header fields into one * "field-name: field-value" pair, without changing the semantics of the * message, by appending each subsequent field-value to the first, each * separated by a comma." - HTTP/1.0 (4.3) *

* * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @see #readResponse * @see #processResponseHeaders */ protected void readResponseHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.readResponseHeaders(HttpState," + "HttpConnection)"); getResponseHeaderGroup().clear(); Header[] headers = HttpParser.parseHeaders( conn.getResponseInputStream(), getParams().getHttpElementCharset()); // Wire logging moved to HttpParser getResponseHeaderGroup().setHeaders(headers); } /** * Read the status line from the given {@link HttpConnection}, setting my * {@link #getStatusCode status code} and {@link #getStatusText status * text}. * *

* Subclasses may want to override this method to to customize the * processing. *

* * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @see StatusLine */ protected void readStatusLine(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.readStatusLine(HttpState, HttpConnection)"); final int maxGarbageLines = getParams(). getIntParameter(HttpMethodParams.STATUS_LINE_GARBAGE_LIMIT, Integer.MAX_VALUE); //read out the HTTP status string int count = 0; String s; do { s = conn.readLine(getParams().getHttpElementCharset()); if (s == null && count == 0) { // The server just dropped connection on us throw new NoHttpResponseException("The server " + conn.getHost() + " failed to respond"); } if (Wire.HEADER_WIRE.enabled()) { Wire.HEADER_WIRE.input(s + "\r\n"); } if (s != null && StatusLine.startsWithHTTP(s)) { // Got one break; } else if (s == null || count >= maxGarbageLines) { // Giving up throw new ProtocolException("The server " + conn.getHost() + " failed to respond with a valid HTTP response"); } count++; } while(true); //create the status line from the status string statusLine = new StatusLine(s); //check for a valid HTTP-Version String versionStr = statusLine.getHttpVersion(); if (getParams().isParameterFalse(HttpMethodParams.UNAMBIGUOUS_STATUS_LINE) && versionStr.equals("HTTP")) { getParams().setVersion(HttpVersion.HTTP_1_0); if (LOG.isWarnEnabled()) { LOG.warn("Ambiguous status line (HTTP protocol version missing):" + statusLine.toString()); } } else { this.effectiveVersion = HttpVersion.parse(versionStr); } } // ------------------------------------------------------ Protected Methods /** *

* Sends the request via the given {@link HttpConnection connection}. *

* *

* The request is written as the following sequence of actions: *

* *
    *
  1. * {@link #writeRequestLine(HttpState, HttpConnection)} is invoked to * write the request line. *
  2. *
  3. * {@link #writeRequestHeaders(HttpState, HttpConnection)} is invoked * to write the associated headers. *
  4. *
  5. * \r\n is sent to close the head part of the request. *
  6. *
  7. * {@link #writeRequestBody(HttpState, HttpConnection)} is invoked to * write the body part of the request. *
  8. *
* *

* Subclasses may want to override one or more of the above methods to to * customize the processing. (Or they may choose to override this method * if dramatically different processing is required.) *

* * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected void writeRequest(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace( "enter HttpMethodBase.writeRequest(HttpState, HttpConnection)"); writeRequestLine(state, conn); writeRequestHeaders(state, conn); conn.writeLine(); // close head if (Wire.HEADER_WIRE.enabled()) { Wire.HEADER_WIRE.output("\r\n"); } HttpVersion ver = getParams().getVersion(); Header expectheader = getRequestHeader("Expect"); String expectvalue = null; if (expectheader != null) { expectvalue = expectheader.getValue(); } if ((expectvalue != null) && (expectvalue.compareToIgnoreCase("100-continue") == 0)) { if (ver.greaterEquals(HttpVersion.HTTP_1_1)) { // make sure the status line and headers have been sent conn.flushRequestOutputStream(); int readTimeout = conn.getParams().getSoTimeout(); try { conn.setSocketTimeout(RESPONSE_WAIT_TIME_MS); readStatusLine(state, conn); processStatusLine(state, conn); readResponseHeaders(state, conn); processResponseHeaders(state, conn); if (this.statusLine.getStatusCode() == HttpStatus.SC_CONTINUE) { // Discard status line this.statusLine = null; LOG.debug("OK to continue received"); } else { return; } } catch (InterruptedIOException e) { if (!ExceptionUtil.isSocketTimeoutException(e)) { throw e; } // Most probably Expect header is not recongnized // Remove the header to signal the method // that it's okay to go ahead with sending data removeRequestHeader("Expect"); LOG.info("100 (continue) read timeout. Resume sending the request"); } finally { conn.setSocketTimeout(readTimeout); } } else { removeRequestHeader("Expect"); LOG.info("'Expect: 100-continue' handshake is only supported by " + "HTTP/1.1 or higher"); } } writeRequestBody(state, conn); // make sure the entire request body has been sent conn.flushRequestOutputStream(); } /** * Writes the request body to the given {@link HttpConnection connection}. * *

* This method should return true if the request body was actually * sent (or is empty), or false if it could not be sent for some * reason. *

* *

* This implementation writes nothing and returns true. *

* * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @return true * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected boolean writeRequestBody(HttpState state, HttpConnection conn) throws IOException, HttpException { return true; } /** * Writes the request headers to the given {@link HttpConnection connection}. * *

* This implementation invokes {@link #addRequestHeaders(HttpState,HttpConnection)}, * and then writes each header to the request stream. *

* *

* Subclasses may want to override this method to to customize the * processing. *

* * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @see #addRequestHeaders * @see #getRequestHeaders */ protected void writeRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.writeRequestHeaders(HttpState," + "HttpConnection)"); addRequestHeaders(state, conn); String charset = getParams().getHttpElementCharset(); Header[] headers = getRequestHeaders(); for (int i = 0; i < headers.length; i++) { String s = headers[i].toExternalForm(); if (Wire.HEADER_WIRE.enabled()) { Wire.HEADER_WIRE.output(s); } conn.print(s, charset); } } /** * Writes the request line to the given {@link HttpConnection connection}. * *

* Subclasses may want to override this method to to customize the * processing. *

* * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @see #generateRequestLine */ protected void writeRequestLine(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace( "enter HttpMethodBase.writeRequestLine(HttpState, HttpConnection)"); String requestLine = getRequestLine(conn); if (Wire.HEADER_WIRE.enabled()) { Wire.HEADER_WIRE.output(requestLine); } conn.print(requestLine, getParams().getHttpElementCharset()); } /** * Returns the request line. * * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @return The request line. */ private String getRequestLine(HttpConnection conn) { return HttpMethodBase.generateRequestLine(conn, getName(), getPath(), getQueryString(), this.effectiveVersion.toString()); } /** * Returns {@link HttpMethodParams HTTP protocol parameters} associated with this method. * * @return HTTP parameters. * * @since 3.0 */ public HttpMethodParams getParams() { return this.params; } /** * Assigns {@link HttpMethodParams HTTP protocol parameters} for this method. * * @since 3.0 * * @see HttpMethodParams */ public void setParams(final HttpMethodParams params) { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } this.params = params; } /** * Returns the HTTP version used with this method (may be null * if undefined, that is, the method has not been executed) * * @return HTTP version. * * @since 3.0 */ public HttpVersion getEffectiveVersion() { return this.effectiveVersion; } /** * Per RFC 2616 section 4.3, some response can never contain a message * body. * * @param status - the HTTP status code * * @return true if the message may contain a body, false if it can not * contain a message body */ private static boolean canResponseHaveBody(int status) { LOG.trace("enter HttpMethodBase.canResponseHaveBody(int)"); boolean result = true; if ((status >= 100 && status <= 199) || (status == 204) || (status == 304)) { // NOT MODIFIED result = false; } return result; } /** * Returns proxy authentication realm, if it has been used during authentication process. * Otherwise returns null. * * @return proxy authentication realm * * @deprecated use #getProxyAuthState() */ public String getProxyAuthenticationRealm() { return this.proxyAuthState.getRealm(); } /** * Returns authentication realm, if it has been used during authentication process. * Otherwise returns null. * * @return authentication realm * * @deprecated use #getHostAuthState() */ public String getAuthenticationRealm() { return this.hostAuthState.getRealm(); } /** * Returns the character set from the Content-Type header. * * @param contentheader The content header. * @return String The character set. */ protected String getContentCharSet(Header contentheader) { LOG.trace("enter getContentCharSet( Header contentheader )"); String charset = null; if (contentheader != null) { HeaderElement values[] = contentheader.getElements(); // I expect only one header element to be there // No more. no less if (values.length == 1) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { // If I get anything "funny" // UnsupportedEncondingException will result charset = param.getValue(); } } } if (charset == null) { charset = getParams().getContentCharset(); if (LOG.isDebugEnabled()) { LOG.debug("Default charset used: " + charset); } } return charset; } /** * Returns the character encoding of the request from the Content-Type header. * * @return String The character set. */ public String getRequestCharSet() { return getContentCharSet(getRequestHeader("Content-Type")); } /** * Returns the character encoding of the response from the Content-Type header. * * @return String The character set. */ public String getResponseCharSet() { return getContentCharSet(getResponseHeader("Content-Type")); } /** * @deprecated no longer used * * Returns the number of "recoverable" exceptions thrown and handled, to * allow for monitoring the quality of the connection. * * @return The number of recoverable exceptions handled by the method. */ public int getRecoverableExceptionCount() { return recoverableExceptionCount; } /** * A response has been consumed. * *

The default behavior for this class is to check to see if the connection * should be closed, and close if need be, and to ensure that the connection * is returned to the connection manager - if and only if we are not still * inside the execute call.

* */ protected void responseBodyConsumed() { // make sure this is the initial invocation of the notification, // ignore subsequent ones. responseStream = null; if (responseConnection != null) { responseConnection.setLastResponseInputStream(null); // At this point, no response data should be available. // If there is data available, regard the connection as being // unreliable and close it. if (shouldCloseConnection(responseConnection)) { responseConnection.close(); } else { try { if(responseConnection.isResponseAvailable()) { boolean logExtraInput = getParams().isParameterTrue(HttpMethodParams.WARN_EXTRA_INPUT); if(logExtraInput) { LOG.warn("Extra response data detected - closing connection"); } responseConnection.close(); } } catch (IOException e) { LOG.warn(e.getMessage()); responseConnection.close(); } } } this.connectionCloseForced = false; ensureConnectionRelease(); } /** * Insure that the connection is released back to the pool. */ private void ensureConnectionRelease() { if (responseConnection != null) { responseConnection.releaseConnection(); responseConnection = null; } } /** * Returns the {@link HostConfiguration host configuration}. * * @return the host configuration * * @deprecated no longer applicable */ public HostConfiguration getHostConfiguration() { HostConfiguration hostconfig = new HostConfiguration(); hostconfig.setHost(this.httphost); return hostconfig; } /** * Sets the {@link HostConfiguration host configuration}. * * @param hostconfig The hostConfiguration to set * * @deprecated no longer applicable */ public void setHostConfiguration(final HostConfiguration hostconfig) { if (hostconfig != null) { this.httphost = new HttpHost( hostconfig.getHost(), hostconfig.getPort(), hostconfig.getProtocol()); } else { this.httphost = null; } } /** * Returns the {@link MethodRetryHandler retry handler} for this HTTP method * * @return the methodRetryHandler * * @deprecated use {@link HttpMethodParams} */ public MethodRetryHandler getMethodRetryHandler() { return methodRetryHandler; } /** * Sets the {@link MethodRetryHandler retry handler} for this HTTP method * * @param handler the methodRetryHandler to use when this method executed * * @deprecated use {@link HttpMethodParams} */ public void setMethodRetryHandler(MethodRetryHandler handler) { methodRetryHandler = handler; } /** * This method is a dirty hack intended to work around * current (2.0) design flaw that prevents the user from * obtaining correct status code, headers and response body from the * preceding HTTP CONNECT method. * * TODO: Remove this crap as soon as possible */ void fakeResponse( StatusLine statusline, HeaderGroup responseheaders, InputStream responseStream ) { // set used so that the response can be read this.used = true; this.statusLine = statusline; this.responseHeaders = responseheaders; this.responseBody = null; this.responseStream = responseStream; } /** * Returns the target host {@link AuthState authentication state} * * @return host authentication state * * @since 3.0 */ public AuthState getHostAuthState() { return this.hostAuthState; } /** * Returns the proxy {@link AuthState authentication state} * * @return host authentication state * * @since 3.0 */ public AuthState getProxyAuthState() { return this.proxyAuthState; } /** * Tests whether the execution of this method has been aborted * * @return true if the execution of this method has been aborted, * false otherwise * * @since 3.0 */ public boolean isAborted() { return this.aborted; } /** * Returns true if the HTTP has been transmitted to the target * server in its entirety, false otherwise. This flag can be useful * for recovery logic. If the request has not been transmitted in its entirety, * it is safe to retry the failed method. * * @return true if the request has been sent, false otherwise */ public boolean isRequestSent() { return this.requestSent; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpMethodDirector.java100644 0 0 110375 10661532627 26402 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethodDirector.java,v 1.34 2005/01/14 19:40:39 olegk Exp $ * $Revision: 486658 $ * $Date: 2006-12-13 15:05:50 +0100 (Wed, 13 Dec 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.httpclient.auth.AuthChallengeException; import org.apache.commons.httpclient.auth.AuthChallengeParser; import org.apache.commons.httpclient.auth.AuthChallengeProcessor; import org.apache.commons.httpclient.auth.AuthScheme; import org.apache.commons.httpclient.auth.AuthState; import org.apache.commons.httpclient.auth.AuthenticationException; import org.apache.commons.httpclient.auth.CredentialsProvider; import org.apache.commons.httpclient.auth.CredentialsNotAvailableException; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.auth.MalformedChallengeException; import org.apache.commons.httpclient.params.HostParams; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.params.HttpParams; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Handles the process of executing a method including authentication, redirection and retries. * * @since 3.0 */ class HttpMethodDirector { /** The www authenticate challange header. */ public static final String WWW_AUTH_CHALLENGE = "WWW-Authenticate"; /** The www authenticate response header. */ public static final String WWW_AUTH_RESP = "Authorization"; /** The proxy authenticate challange header. */ public static final String PROXY_AUTH_CHALLENGE = "Proxy-Authenticate"; /** The proxy authenticate response header. */ public static final String PROXY_AUTH_RESP = "Proxy-Authorization"; private static final Log LOG = LogFactory.getLog(HttpMethodDirector.class); private ConnectMethod connectMethod; private HttpState state; private HostConfiguration hostConfiguration; private HttpConnectionManager connectionManager; private HttpClientParams params; private HttpConnection conn; /** A flag to indicate if the connection should be released after the method is executed. */ private boolean releaseConnection = false; /** Authentication processor */ private AuthChallengeProcessor authProcessor = null; private Set redirectLocations = null; public HttpMethodDirector( final HttpConnectionManager connectionManager, final HostConfiguration hostConfiguration, final HttpClientParams params, final HttpState state ) { super(); this.connectionManager = connectionManager; this.hostConfiguration = hostConfiguration; this.params = params; this.state = state; this.authProcessor = new AuthChallengeProcessor(this.params); } /** * Executes the method associated with this method director. * * @throws IOException * @throws HttpException */ public void executeMethod(final HttpMethod method) throws IOException, HttpException { if (method == null) { throw new IllegalArgumentException("Method may not be null"); } // Link all parameter collections to form the hierarchy: // Global -> HttpClient -> HostConfiguration -> HttpMethod this.hostConfiguration.getParams().setDefaults(this.params); method.getParams().setDefaults(this.hostConfiguration.getParams()); // Generate default request headers Collection defaults = (Collection)this.hostConfiguration.getParams(). getParameter(HostParams.DEFAULT_HEADERS); if (defaults != null) { Iterator i = defaults.iterator(); while (i.hasNext()) { method.addRequestHeader((Header)i.next()); } } try { int maxRedirects = this.params.getIntParameter(HttpClientParams.MAX_REDIRECTS, 100); for (int redirectCount = 0;;) { // make sure the connection we have is appropriate if (this.conn != null && !hostConfiguration.hostEquals(this.conn)) { this.conn.setLocked(false); this.conn.releaseConnection(); this.conn = null; } // get a connection, if we need one if (this.conn == null) { this.conn = connectionManager.getConnectionWithTimeout( hostConfiguration, this.params.getConnectionManagerTimeout() ); this.conn.setLocked(true); if (this.params.isAuthenticationPreemptive() || this.state.isAuthenticationPreemptive()) { LOG.debug("Preemptively sending default basic credentials"); method.getHostAuthState().setPreemptive(); method.getHostAuthState().setAuthAttempted(true); if (this.conn.isProxied() && !this.conn.isSecure()) { method.getProxyAuthState().setPreemptive(); method.getProxyAuthState().setAuthAttempted(true); } } } authenticate(method); executeWithRetry(method); if (this.connectMethod != null) { fakeResponse(method); break; } boolean retry = false; if (isRedirectNeeded(method)) { if (processRedirectResponse(method)) { retry = true; ++redirectCount; if (redirectCount >= maxRedirects) { LOG.error("Narrowly avoided an infinite loop in execute"); throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded"); } if (LOG.isDebugEnabled()) { LOG.debug("Execute redirect " + redirectCount + " of " + maxRedirects); } } } if (isAuthenticationNeeded(method)) { if (processAuthenticationResponse(method)) { LOG.debug("Retry authentication"); retry = true; } } if (!retry) { break; } // retry - close previous stream. Caution - this causes // responseBodyConsumed to be called, which may also close the // connection. if (method.getResponseBodyAsStream() != null) { method.getResponseBodyAsStream().close(); } } //end of retry loop } finally { if (this.conn != null) { this.conn.setLocked(false); } // If the response has been fully processed, return the connection // to the pool. Use this flag, rather than other tests (like // responseStream == null), as subclasses, might reset the stream, // for example, reading the entire response into a file and then // setting the file as the stream. if ( (releaseConnection || method.getResponseBodyAsStream() == null) && this.conn != null ) { this.conn.releaseConnection(); } } } private void authenticate(final HttpMethod method) { try { if (this.conn.isProxied() && !this.conn.isSecure()) { authenticateProxy(method); } authenticateHost(method); } catch (AuthenticationException e) { LOG.error(e.getMessage(), e); } } private boolean cleanAuthHeaders(final HttpMethod method, final String name) { Header[] authheaders = method.getRequestHeaders(name); boolean clean = true; for (int i = 0; i < authheaders.length; i++) { Header authheader = authheaders[i]; if (authheader.isAutogenerated()) { method.removeRequestHeader(authheader); } else { clean = false; } } return clean; } private void authenticateHost(final HttpMethod method) throws AuthenticationException { // Clean up existing authentication headers if (!cleanAuthHeaders(method, WWW_AUTH_RESP)) { // User defined authentication header(s) present return; } AuthState authstate = method.getHostAuthState(); AuthScheme authscheme = authstate.getAuthScheme(); if (authscheme == null) { return; } if (authstate.isAuthRequested() || !authscheme.isConnectionBased()) { String host = method.getParams().getVirtualHost(); if (host == null) { host = conn.getHost(); } int port = conn.getPort(); AuthScope authscope = new AuthScope( host, port, authscheme.getRealm(), authscheme.getSchemeName()); if (LOG.isDebugEnabled()) { LOG.debug("Authenticating with " + authscope); } Credentials credentials = this.state.getCredentials(authscope); if (credentials != null) { String authstring = authscheme.authenticate(credentials, method); if (authstring != null) { method.addRequestHeader(new Header(WWW_AUTH_RESP, authstring, true)); } } else { if (LOG.isWarnEnabled()) { LOG.warn("Required credentials not available for " + authscope); if (method.getHostAuthState().isPreemptive()) { LOG.warn("Preemptive authentication requested but no default " + "credentials available"); } } } } } private void authenticateProxy(final HttpMethod method) throws AuthenticationException { // Clean up existing authentication headers if (!cleanAuthHeaders(method, PROXY_AUTH_RESP)) { // User defined authentication header(s) present return; } AuthState authstate = method.getProxyAuthState(); AuthScheme authscheme = authstate.getAuthScheme(); if (authscheme == null) { return; } if (authstate.isAuthRequested() || !authscheme.isConnectionBased()) { AuthScope authscope = new AuthScope( conn.getProxyHost(), conn.getProxyPort(), authscheme.getRealm(), authscheme.getSchemeName()); if (LOG.isDebugEnabled()) { LOG.debug("Authenticating with " + authscope); } Credentials credentials = this.state.getProxyCredentials(authscope); if (credentials != null) { String authstring = authscheme.authenticate(credentials, method); if (authstring != null) { method.addRequestHeader(new Header(PROXY_AUTH_RESP, authstring, true)); } } else { if (LOG.isWarnEnabled()) { LOG.warn("Required proxy credentials not available for " + authscope); if (method.getProxyAuthState().isPreemptive()) { LOG.warn("Preemptive authentication requested but no default " + "proxy credentials available"); } } } } } /** * Applies connection parameters specified for a given method * * @param method HTTP method * * @throws IOException if an I/O occurs setting connection parameters */ private void applyConnectionParams(final HttpMethod method) throws IOException { int timeout = 0; // see if a timeout is given for this method Object param = method.getParams().getParameter(HttpMethodParams.SO_TIMEOUT); if (param == null) { // if not, use the default value param = this.conn.getParams().getParameter(HttpConnectionParams.SO_TIMEOUT); } if (param != null) { timeout = ((Integer)param).intValue(); } this.conn.setSocketTimeout(timeout); } /** * Executes a method with the current hostConfiguration. * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ private void executeWithRetry(final HttpMethod method) throws IOException, HttpException { /** How many times did this transparently handle a recoverable exception? */ int execCount = 0; // loop until the method is successfully processed, the retryHandler // returns false or a non-recoverable exception is thrown try { while (true) { execCount++; try { if (LOG.isTraceEnabled()) { LOG.trace("Attempt number " + execCount + " to process request"); } if (this.conn.getParams().isStaleCheckingEnabled()) { this.conn.closeIfStale(); } if (!this.conn.isOpen()) { // this connection must be opened before it can be used // This has nothing to do with opening a secure tunnel this.conn.open(); if (this.conn.isProxied() && this.conn.isSecure() && !(method instanceof ConnectMethod)) { // we need to create a secure tunnel before we can execute the real method if (!executeConnect()) { // abort, the connect method failed return; } } } applyConnectionParams(method); method.execute(state, this.conn); break; } catch (HttpException e) { // filter out protocol exceptions which cannot be recovered from throw e; } catch (IOException e) { LOG.debug("Closing the connection."); this.conn.close(); // test if this method should be retried // ======================================== // this code is provided for backward compatibility with 2.0 // will be removed in the next major release if (method instanceof HttpMethodBase) { MethodRetryHandler handler = ((HttpMethodBase)method).getMethodRetryHandler(); if (handler != null) { if (!handler.retryMethod( method, this.conn, new HttpRecoverableException(e.getMessage()), execCount, method.isRequestSent())) { LOG.debug("Method retry handler returned false. " + "Automatic recovery will not be attempted"); throw e; } } } // ======================================== HttpMethodRetryHandler handler = (HttpMethodRetryHandler)method.getParams().getParameter( HttpMethodParams.RETRY_HANDLER); if (handler == null) { handler = new DefaultHttpMethodRetryHandler(); } if (!handler.retryMethod(method, e, execCount)) { LOG.debug("Method retry handler returned false. " + "Automatic recovery will not be attempted"); throw e; } if (LOG.isInfoEnabled()) { LOG.info("I/O exception ("+ e.getClass().getName() +") caught when processing request: " + e.getMessage()); } if (LOG.isDebugEnabled()) { LOG.debug(e.getMessage(), e); } LOG.info("Retrying request"); } } } catch (IOException e) { if (this.conn.isOpen()) { LOG.debug("Closing the connection."); this.conn.close(); } releaseConnection = true; throw e; } catch (RuntimeException e) { if (this.conn.isOpen()) { LOG.debug("Closing the connection."); this.conn.close(); } releaseConnection = true; throw e; } } /** * Executes a ConnectMethod to establish a tunneled connection. * * @return true if the connect was successful * * @throws IOException * @throws HttpException */ private boolean executeConnect() throws IOException, HttpException { this.connectMethod = new ConnectMethod(this.hostConfiguration); this.connectMethod.getParams().setDefaults(this.hostConfiguration.getParams()); int code; for (;;) { if (!this.conn.isOpen()) { this.conn.open(); } if (this.params.isAuthenticationPreemptive() || this.state.isAuthenticationPreemptive()) { LOG.debug("Preemptively sending default basic credentials"); this.connectMethod.getProxyAuthState().setPreemptive(); this.connectMethod.getProxyAuthState().setAuthAttempted(true); } try { authenticateProxy(this.connectMethod); } catch (AuthenticationException e) { LOG.error(e.getMessage(), e); } applyConnectionParams(this.connectMethod); this.connectMethod.execute(state, this.conn); code = this.connectMethod.getStatusCode(); boolean retry = false; AuthState authstate = this.connectMethod.getProxyAuthState(); authstate.setAuthRequested(code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED); if (authstate.isAuthRequested()) { if (processAuthenticationResponse(this.connectMethod)) { retry = true; } } if (!retry) { break; } if (this.connectMethod.getResponseBodyAsStream() != null) { this.connectMethod.getResponseBodyAsStream().close(); } } if ((code >= 200) && (code < 300)) { this.conn.tunnelCreated(); // Drop the connect method, as it is no longer needed this.connectMethod = null; return true; } else { this.conn.close(); return false; } } /** * Fake response * @param method * @return */ private void fakeResponse(final HttpMethod method) throws IOException, HttpException { // What is to follow is an ugly hack. // I REALLY hate having to resort to such // an appalling trick // The only feasible solution is to split monolithic // HttpMethod into HttpRequest/HttpResponse pair. // That would allow to execute CONNECT method // behind the scene and return CONNECT HttpResponse // object in response to the original request that // contains the correct status line, headers & // response body. LOG.debug("CONNECT failed, fake the response for the original method"); // Pass the status, headers and response stream to the wrapped // method. // To ensure that the connection is not released more than once // this method is still responsible for releasing the connection. // This will happen when the response body is consumed, or when // the wrapped method closes the response connection in // releaseConnection(). if (method instanceof HttpMethodBase) { ((HttpMethodBase) method).fakeResponse( this.connectMethod.getStatusLine(), this.connectMethod.getResponseHeaderGroup(), this.connectMethod.getResponseBodyAsStream() ); method.getProxyAuthState().setAuthScheme( this.connectMethod.getProxyAuthState().getAuthScheme()); this.connectMethod = null; } else { releaseConnection = true; LOG.warn( "Unable to fake response on method as it is not derived from HttpMethodBase."); } } /** * Process the redirect response. * * @return true if the redirect was successful */ private boolean processRedirectResponse(final HttpMethod method) throws RedirectException { //get the location header to find out where to redirect to Header locationHeader = method.getResponseHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header LOG.error("Received redirect response " + method.getStatusCode() + " but no location header"); return false; } String location = locationHeader.getValue(); if (LOG.isDebugEnabled()) { LOG.debug("Redirect requested to location '" + location + "'"); } //rfc2616 demands the location value be a complete URI //Location = "Location" ":" absoluteURI URI redirectUri = null; URI currentUri = null; try { currentUri = new URI( this.conn.getProtocol().getScheme(), null, this.conn.getHost(), this.conn.getPort(), method.getPath() ); String charset = method.getParams().getUriCharset(); redirectUri = new URI(location, true, charset); if (redirectUri.isRelativeURI()) { if (this.params.isParameterTrue(HttpClientParams.REJECT_RELATIVE_REDIRECT)) { LOG.warn("Relative redirect location '" + location + "' not allowed"); return false; } else { //location is incomplete, use current values for defaults LOG.debug("Redirect URI is not absolute - parsing as relative"); redirectUri = new URI(currentUri, redirectUri); } } else { // Reset the default params method.getParams().setDefaults(this.params); } method.setURI(redirectUri); hostConfiguration.setHost(redirectUri); } catch (URIException ex) { throw new InvalidRedirectLocationException( "Invalid redirect location: " + location, location, ex); } if (this.params.isParameterFalse(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS)) { if (this.redirectLocations == null) { this.redirectLocations = new HashSet(); } this.redirectLocations.add(currentUri); try { if(redirectUri.hasQuery()) { redirectUri.setQuery(null); } } catch (URIException e) { // Should never happen return false; } if (this.redirectLocations.contains(redirectUri)) { throw new CircularRedirectException("Circular redirect to '" + redirectUri + "'"); } } if (LOG.isDebugEnabled()) { LOG.debug("Redirecting from '" + currentUri.getEscapedURI() + "' to '" + redirectUri.getEscapedURI()); } //And finally invalidate the actual authentication scheme method.getHostAuthState().invalidate(); return true; } /** * Processes a response that requires authentication * * @param method the current {@link HttpMethod HTTP method} * * @return true if the authentication challenge can be responsed to, * (that is, at least one of the requested authentication scheme is supported, * and matching credentials have been found), false otherwise. */ private boolean processAuthenticationResponse(final HttpMethod method) { LOG.trace("enter HttpMethodBase.processAuthenticationResponse(" + "HttpState, HttpConnection)"); try { switch (method.getStatusCode()) { case HttpStatus.SC_UNAUTHORIZED: return processWWWAuthChallenge(method); case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: return processProxyAuthChallenge(method); default: return false; } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(e.getMessage(), e); } return false; } } private boolean processWWWAuthChallenge(final HttpMethod method) throws MalformedChallengeException, AuthenticationException { AuthState authstate = method.getHostAuthState(); Map challenges = AuthChallengeParser.parseChallenges( method.getResponseHeaders(WWW_AUTH_CHALLENGE)); if (challenges.isEmpty()) { LOG.debug("Authentication challenge(s) not found"); return false; } AuthScheme authscheme = null; try { authscheme = this.authProcessor.processChallenge(authstate, challenges); } catch (AuthChallengeException e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } if (authscheme == null) { return false; } String host = method.getParams().getVirtualHost(); if (host == null) { host = conn.getHost(); } int port = conn.getPort(); AuthScope authscope = new AuthScope( host, port, authscheme.getRealm(), authscheme.getSchemeName()); if (LOG.isDebugEnabled()) { LOG.debug("Authentication scope: " + authscope); } if (authstate.isAuthAttempted() && authscheme.isComplete()) { // Already tried and failed Credentials credentials = promptForCredentials( authscheme, method.getParams(), authscope); if (credentials == null) { if (LOG.isInfoEnabled()) { LOG.info("Failure authenticating with " + authscope); } return false; } else { return true; } } else { authstate.setAuthAttempted(true); Credentials credentials = this.state.getCredentials(authscope); if (credentials == null) { credentials = promptForCredentials( authscheme, method.getParams(), authscope); } if (credentials == null) { if (LOG.isInfoEnabled()) { LOG.info("No credentials available for " + authscope); } return false; } else { return true; } } } private boolean processProxyAuthChallenge(final HttpMethod method) throws MalformedChallengeException, AuthenticationException { AuthState authstate = method.getProxyAuthState(); Map proxyChallenges = AuthChallengeParser.parseChallenges( method.getResponseHeaders(PROXY_AUTH_CHALLENGE)); if (proxyChallenges.isEmpty()) { LOG.debug("Proxy authentication challenge(s) not found"); return false; } AuthScheme authscheme = null; try { authscheme = this.authProcessor.processChallenge(authstate, proxyChallenges); } catch (AuthChallengeException e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } if (authscheme == null) { return false; } AuthScope authscope = new AuthScope( conn.getProxyHost(), conn.getProxyPort(), authscheme.getRealm(), authscheme.getSchemeName()); if (LOG.isDebugEnabled()) { LOG.debug("Proxy authentication scope: " + authscope); } if (authstate.isAuthAttempted() && authscheme.isComplete()) { // Already tried and failed Credentials credentials = promptForProxyCredentials( authscheme, method.getParams(), authscope); if (credentials == null) { if (LOG.isInfoEnabled()) { LOG.info("Failure authenticating with " + authscope); } return false; } else { return true; } } else { authstate.setAuthAttempted(true); Credentials credentials = this.state.getProxyCredentials(authscope); if (credentials == null) { credentials = promptForProxyCredentials( authscheme, method.getParams(), authscope); } if (credentials == null) { if (LOG.isInfoEnabled()) { LOG.info("No credentials available for " + authscope); } return false; } else { return true; } } } /** * Tests if the {@link HttpMethod method} requires a redirect to another location. * * @param method HTTP method * * @return boolean true if a retry is needed, false otherwise. */ private boolean isRedirectNeeded(final HttpMethod method) { switch (method.getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: LOG.debug("Redirect required"); if (method.getFollowRedirects()) { return true; } else { return false; } default: return false; } //end of switch } /** * Tests if the {@link HttpMethod method} requires authentication. * * @param method HTTP method * * @return boolean true if a retry is needed, false otherwise. */ private boolean isAuthenticationNeeded(final HttpMethod method) { method.getHostAuthState().setAuthRequested( method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED); method.getProxyAuthState().setAuthRequested( method.getStatusCode() == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED); if (method.getHostAuthState().isAuthRequested() || method.getProxyAuthState().isAuthRequested()) { LOG.debug("Authorization required"); if (method.getDoAuthentication()) { //process authentication response return true; } else { //let the client handle the authenticaiton LOG.info("Authentication requested but doAuthentication is " + "disabled"); return false; } } else { return false; } } private Credentials promptForCredentials( final AuthScheme authScheme, final HttpParams params, final AuthScope authscope) { LOG.debug("Credentials required"); Credentials creds = null; CredentialsProvider credProvider = (CredentialsProvider)params.getParameter(CredentialsProvider.PROVIDER); if (credProvider != null) { try { creds = credProvider.getCredentials( authScheme, authscope.getHost(), authscope.getPort(), false); } catch (CredentialsNotAvailableException e) { LOG.warn(e.getMessage()); } if (creds != null) { this.state.setCredentials(authscope, creds); if (LOG.isDebugEnabled()) { LOG.debug(authscope + " new credentials given"); } } } else { LOG.debug("Credentials provider not available"); } return creds; } private Credentials promptForProxyCredentials( final AuthScheme authScheme, final HttpParams params, final AuthScope authscope) { LOG.debug("Proxy credentials required"); Credentials creds = null; CredentialsProvider credProvider = (CredentialsProvider)params.getParameter(CredentialsProvider.PROVIDER); if (credProvider != null) { try { creds = credProvider.getCredentials( authScheme, authscope.getHost(), authscope.getPort(), true); } catch (CredentialsNotAvailableException e) { LOG.warn(e.getMessage()); } if (creds != null) { this.state.setProxyCredentials(authscope, creds); if (LOG.isDebugEnabled()) { LOG.debug(authscope + " new credentials given"); } } } else { LOG.debug("Proxy credentials provider not available"); } return creds; } /** * @return */ public HostConfiguration getHostConfiguration() { return hostConfiguration; } /** * @return */ public HttpState getState() { return state; } /** * @return */ public HttpConnectionManager getConnectionManager() { return connectionManager; } /** * @return */ public HttpParams getParams() { return this.params; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpMethodRetryHandler.java100644 0 0 5024 10661532626 27163 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethodRetryHandler.java,v 1.2 2004/09/14 20:11:31 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; /** * A handler for determining if an HttpMethod should be retried after a * recoverable exception during execution. * *

* Classes implementing this interface must synchronize access to shared * data as methods of this interfrace may be executed from multiple threads *

* * @see HttpMethod#execute(HttpState, HttpConnection) * * @author Michael Becke * @author Oleg Kalnichevski */ public interface HttpMethodRetryHandler { /** * Determines if a method should be retried after an HttpRecoverableException * occurs during execution. * * @param method the method being executed * @param exception the exception that occurred * @param executionCount the number of times this method has been * unsuccessfully executed * * @return true if the method should be retried, false * otherwise */ boolean retryMethod(HttpMethod method, IOException exception, int executionCount); } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpParser.java100644 0 0 20636 10661532626 24701 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpParser.java,v 1.13 2005/01/11 13:57:06 oglueck Exp $ * $Revision: 533405 $ * $Date: 2007-04-28 20:19:29 +0200 (Sat, 28 Apr 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import org.apache.commons.httpclient.util.EncodingUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A utility class for parsing http header values according to * RFC-2616 Section 4 and 19.3. * * @author Michael Becke * @author Oleg Kalnichevski * * @since 2.0beta1 */ public class HttpParser { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HttpParser.class); /** * Constructor for HttpParser. */ private HttpParser() { } /** * Return byte array from an (unchunked) input stream. * Stop reading when "\n" terminator encountered * If the stream ends before the line terminator is found, * the last part of the string will still be returned. * If no input data available, null is returned. * * @param inputStream the stream to read from * * @throws IOException if an I/O problem occurs * @return a byte array from the stream */ public static byte[] readRawLine(InputStream inputStream) throws IOException { LOG.trace("enter HttpParser.readRawLine()"); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int ch; while ((ch = inputStream.read()) >= 0) { buf.write(ch); if (ch == '\n') { // be tolerant (RFC-2616 Section 19.3) break; } } if (buf.size() == 0) { return null; } return buf.toByteArray(); } /** * Read up to "\n" from an (unchunked) input stream. * If the stream ends before the line terminator is found, * the last part of the string will still be returned. * If no input data available, null is returned. * * @param inputStream the stream to read from * @param charset charset of HTTP protocol elements * * @throws IOException if an I/O problem occurs * @return a line from the stream * * @since 3.0 */ public static String readLine(InputStream inputStream, String charset) throws IOException { LOG.trace("enter HttpParser.readLine(InputStream, String)"); byte[] rawdata = readRawLine(inputStream); if (rawdata == null) { return null; } // strip CR and LF from the end int len = rawdata.length; int offset = 0; if (len > 0) { if (rawdata[len - 1] == '\n') { offset++; if (len > 1) { if (rawdata[len - 2] == '\r') { offset++; } } } } final String result = EncodingUtil.getString(rawdata, 0, len - offset, charset); if (Wire.HEADER_WIRE.enabled()) { String logoutput = result; if (offset == 2) logoutput = result + "\r\n"; else if (offset == 1) logoutput = result + "\n"; Wire.HEADER_WIRE.input(logoutput); } return result; } /** * Read up to "\n" from an (unchunked) input stream. * If the stream ends before the line terminator is found, * the last part of the string will still be returned. * If no input data available, null is returned * * @param inputStream the stream to read from * * @throws IOException if an I/O problem occurs * @return a line from the stream * * @deprecated use #readLine(InputStream, String) */ public static String readLine(InputStream inputStream) throws IOException { LOG.trace("enter HttpParser.readLine(InputStream)"); return readLine(inputStream, "US-ASCII"); } /** * Parses headers from the given stream. Headers with the same name are not * combined. * * @param is the stream to read headers from * @param charset the charset to use for reading the data * * @return an array of headers in the order in which they were parsed * * @throws IOException if an IO error occurs while reading from the stream * @throws HttpException if there is an error parsing a header value * * @since 3.0 */ public static Header[] parseHeaders(InputStream is, String charset) throws IOException, HttpException { LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)"); ArrayList headers = new ArrayList(); String name = null; StringBuffer value = null; for (; ;) { String line = HttpParser.readLine(is, charset); if ((line == null) || (line.trim().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 ((line.charAt(0) == ' ') || (line.charAt(0) == '\t')) { // we have continuation folded header // so append value if (value != null) { value.append(' '); value.append(line.trim()); } } else { // make sure we save the previous name,value pair if present if (name != null) { headers.add(new Header(name, value.toString())); } // Otherwise we should have normal HTTP header line // Parse the header name and value int colon = line.indexOf(":"); if (colon < 0) { throw new ProtocolException("Unable to parse header: " + line); } name = line.substring(0, colon).trim(); value = new StringBuffer(line.substring(colon + 1).trim()); } } // make sure we save the last name,value pair if present if (name != null) { headers.add(new Header(name, value.toString())); } return (Header[]) headers.toArray(new Header[headers.size()]); } /** * Parses headers from the given stream. Headers with the same name are not * combined. * * @param is the stream to read headers from * * @return an array of headers in the order in which they were parsed * * @throws IOException if an IO error occurs while reading from the stream * @throws HttpException if there is an error parsing a header value * * @deprecated use #parseHeaders(InputStream, String) */ public static Header[] parseHeaders(InputStream is) throws IOException, HttpException { LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)"); return parseHeaders(is, "US-ASCII"); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpRecoverableException.java100644 0 0 4601 10661532626 27527 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpRecoverableException.java,v 1.15 2004/07/05 22:46:58 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** *

* Signals that an HTTP or HttpClient exception has occurred. This * exception may have been caused by a transient error and the request * may be retried. It may be possible to retrieve the underlying transient * error via the inherited {@link HttpException#getCause()} method. *

* * @deprecated no longer used * * @author Unascribed * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ */ public class HttpRecoverableException extends HttpException { /** * Creates a new HttpRecoverableException with a null detail message. */ public HttpRecoverableException() { super(); } /** * Creates a new HttpRecoverableException with the specified detail message. * * @param message exception message */ public HttpRecoverableException(String message) { super(message); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpState.java100644 0 0 53344 10661532626 24527 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpState.java,v 1.38 2004/12/20 11:50:54 olegk Exp $ * $Revision: 561099 $ * $Date: 2007-07-30 21:41:17 +0200 (Mon, 30 Jul 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.Iterator; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

* A container for HTTP attributes that may persist from request * to request, such as {@link Cookie cookies} and authentication * {@link Credentials credentials}. *

* * @author Remy Maucherat * @author Rodney Waldhoff * @author Jeff Dever * @author Sean C. Sullivan * @author Michael Becke * @author Oleg Kalnichevski * @author Mike Bowler * @author Adrian Sutton * * @version $Revision: 561099 $ $Date: 2007-07-30 21:41:17 +0200 (Mon, 30 Jul 2007) $ * */ public class HttpState { // ----------------------------------------------------- Instance Variables /** * Map of {@link Credentials credentials} by realm that this * HTTP state contains. */ protected HashMap credMap = new HashMap(); /** * Map of {@link Credentials proxy credentials} by realm that this * HTTP state contains */ protected HashMap proxyCred = new HashMap(); /** * Array of {@link Cookie cookies} that this HTTP state contains. */ protected ArrayList cookies = new ArrayList(); private boolean preemptive = false; private int cookiePolicy = -1; // -------------------------------------------------------- Class Variables /** * The boolean system property name to turn on preemptive authentication. * @deprecated This field and feature will be removed following HttpClient 3.0. */ public static final String PREEMPTIVE_PROPERTY = "httpclient.authentication.preemptive"; /** * The default value for {@link #PREEMPTIVE_PROPERTY}. * @deprecated This field and feature will be removed following HttpClient 3.0. */ public static final String PREEMPTIVE_DEFAULT = "false"; /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HttpState.class); /** * Default constructor. */ public HttpState() { super(); } // ------------------------------------------------------------- Properties /** * Adds an {@link Cookie HTTP cookie}, replacing any existing equivalent cookies. * If the given cookie has already expired it will not be added, but existing * values will still be removed. * * @param cookie the {@link Cookie cookie} to be added * * @see #addCookies(Cookie[]) * */ public synchronized void addCookie(Cookie cookie) { LOG.trace("enter HttpState.addCookie(Cookie)"); if (cookie != null) { // first remove any old cookie that is equivalent for (Iterator it = cookies.iterator(); it.hasNext();) { Cookie tmp = (Cookie) it.next(); if (cookie.equals(tmp)) { it.remove(); break; } } if (!cookie.isExpired()) { cookies.add(cookie); } } } /** * Adds an array of {@link Cookie HTTP cookies}. Cookies are added individually and * in the given array order. If any of the given cookies has already expired it will * not be added, but existing values will still be removed. * * @param cookies the {@link Cookie cookies} to be added * * @see #addCookie(Cookie) * * */ public synchronized void addCookies(Cookie[] cookies) { LOG.trace("enter HttpState.addCookies(Cookie[])"); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { this.addCookie(cookies[i]); } } } /** * Returns an array of {@link Cookie cookies} that this HTTP * state currently contains. * * @return an array of {@link Cookie cookies}. * * @see #getCookies(String, int, String, boolean) * */ public synchronized Cookie[] getCookies() { LOG.trace("enter HttpState.getCookies()"); return (Cookie[]) (cookies.toArray(new Cookie[cookies.size()])); } /** * Returns an array of {@link Cookie cookies} in this HTTP * state that match the given request parameters. * * @param domain the request domain * @param port the request port * @param path the request path * @param secure true when using HTTPS * * @return an array of {@link Cookie cookies}. * * @see #getCookies() * * @deprecated use CookieSpec#match(String, int, String, boolean, Cookie) */ public synchronized Cookie[] getCookies( String domain, int port, String path, boolean secure ) { LOG.trace("enter HttpState.getCookies(String, int, String, boolean)"); CookieSpec matcher = CookiePolicy.getDefaultSpec(); ArrayList list = new ArrayList(cookies.size()); for (int i = 0, m = cookies.size(); i < m; i++) { Cookie cookie = (Cookie) (cookies.get(i)); if (matcher.match(domain, port, path, secure, cookie)) { list.add(cookie); } } return (Cookie[]) (list.toArray(new Cookie[list.size()])); } /** * Removes all of {@link Cookie cookies} in this HTTP state * that have expired according to the current system time. * * @see #purgeExpiredCookies(java.util.Date) * */ public synchronized boolean purgeExpiredCookies() { LOG.trace("enter HttpState.purgeExpiredCookies()"); return purgeExpiredCookies(new Date()); } /** * Removes all of {@link Cookie cookies} in this HTTP state * that have expired by the specified {@link java.util.Date date}. * * @param date The {@link java.util.Date date} to compare against. * * @return true if any cookies were purged. * * @see Cookie#isExpired(java.util.Date) * * @see #purgeExpiredCookies() */ public synchronized boolean purgeExpiredCookies(Date date) { LOG.trace("enter HttpState.purgeExpiredCookies(Date)"); boolean removed = false; Iterator it = cookies.iterator(); while (it.hasNext()) { if (((Cookie) (it.next())).isExpired(date)) { it.remove(); removed = true; } } return removed; } /** * Returns the current {@link CookiePolicy cookie policy} for this * HTTP state. * * @return The {@link CookiePolicy cookie policy}. * * @deprecated Use * {@link org.apache.commons.httpclient.params.HttpMethodParams#getCookiePolicy()}, * {@link HttpMethod#getParams()}. */ public int getCookiePolicy() { return this.cookiePolicy; } /** * Defines whether preemptive authentication should be * attempted. * * @param value true if preemptive authentication should be * attempted, false otherwise. * * @deprecated Use * {@link org.apache.commons.httpclient.params.HttpClientParams#setAuthenticationPreemptive(boolean)}, * {@link HttpClient#getParams()}. */ public void setAuthenticationPreemptive(boolean value) { this.preemptive = value; } /** * Returns true if preemptive authentication should be * attempted, false otherwise. * * @return boolean flag. * * @deprecated Use * {@link org.apache.commons.httpclient.params.HttpClientParams#isAuthenticationPreemptive()}, * {@link HttpClient#getParams()}. */ public boolean isAuthenticationPreemptive() { return this.preemptive; } /** * Sets the current {@link CookiePolicy cookie policy} for this HTTP * state to one of the following supported policies: * {@link CookiePolicy#COMPATIBILITY}, * {@link CookiePolicy#NETSCAPE_DRAFT} or * {@link CookiePolicy#RFC2109}. * * @param policy new {@link CookiePolicy cookie policy} * * @deprecated * Use {@link org.apache.commons.httpclient.params.HttpMethodParams#setCookiePolicy(String)}, * {@link HttpMethod#getParams()}. */ public void setCookiePolicy(int policy) { this.cookiePolicy = policy; } /** * Sets the {@link Credentials credentials} for the given authentication * realm on the given host. The null realm signifies default * credentials for the given host, which should be used when no * {@link Credentials credentials} have been explictly supplied for the * challenging realm. The null host signifies default * credentials, which should be used when no {@link Credentials credentials} * have been explictly supplied for the challenging host. Any previous * credentials for the given realm on the given host will be overwritten. * * @param realm the authentication realm * @param host the host the realm belongs to * @param credentials the authentication {@link Credentials credentials} * for the given realm. * * @see #getCredentials(String, String) * @see #setProxyCredentials(String, String, Credentials) * * @deprecated use #setCredentials(AuthScope, Credentials) */ public synchronized void setCredentials(String realm, String host, Credentials credentials) { LOG.trace("enter HttpState.setCredentials(String, String, Credentials)"); credMap.put(new AuthScope(host, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME), credentials); } /** * Sets the {@link Credentials credentials} for the given authentication * scope. Any previous credentials for the given scope will be overwritten. * * @param authscope the {@link AuthScope authentication scope} * @param credentials the authentication {@link Credentials credentials} * for the given scope. * * @see #getCredentials(AuthScope) * @see #setProxyCredentials(AuthScope, Credentials) * * @since 3.0 */ public synchronized void setCredentials(final AuthScope authscope, final Credentials credentials) { if (authscope == null) { throw new IllegalArgumentException("Authentication scope may not be null"); } LOG.trace("enter HttpState.setCredentials(AuthScope, Credentials)"); credMap.put(authscope, credentials); } /** * Find matching {@link Credentials credentials} for the given authentication scope. * * @param map the credentials hash map * @param token the {@link AuthScope authentication scope} * @return the credentials * */ private static Credentials matchCredentials(final HashMap map, final AuthScope authscope) { // see if we get a direct hit Credentials creds = (Credentials)map.get(authscope); if (creds == null) { // Nope. // Do a full scan int bestMatchFactor = -1; AuthScope bestMatch = null; Iterator items = map.keySet().iterator(); while (items.hasNext()) { AuthScope current = (AuthScope)items.next(); int factor = authscope.match(current); if (factor > bestMatchFactor) { bestMatchFactor = factor; bestMatch = current; } } if (bestMatch != null) { creds = (Credentials)map.get(bestMatch); } } return creds; } /** * Get the {@link Credentials credentials} for the given authentication scope on the * given host. * * If the realm exists on host, return the coresponding credentials. * If the host exists with a null realm, return the corresponding * credentials. * If the realm exists with a null host, return the * corresponding credentials. If the realm does not exist, return * the default Credentials. If there are no default credentials, return * null. * * @param realm the authentication realm * @param host the host the realm is on * @return the credentials * * @see #setCredentials(String, String, Credentials) * * @deprecated use #getCredentials(AuthScope) */ public synchronized Credentials getCredentials(String realm, String host) { LOG.trace("enter HttpState.getCredentials(String, String"); return matchCredentials(this.credMap, new AuthScope(host, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME)); } /** * Get the {@link Credentials credentials} for the given authentication scope. * * @param authscope the {@link AuthScope authentication scope} * @return the credentials * * @see #setCredentials(AuthScope, Credentials) * * @since 3.0 */ public synchronized Credentials getCredentials(final AuthScope authscope) { if (authscope == null) { throw new IllegalArgumentException("Authentication scope may not be null"); } LOG.trace("enter HttpState.getCredentials(AuthScope)"); return matchCredentials(this.credMap, authscope); } /** * Sets the {@link Credentials credentials} for the given proxy authentication * realm on the given proxy host. The null proxy realm signifies * default credentials for the given proxy host, which should be used when no * {@link Credentials credentials} have been explictly supplied for the * challenging proxy realm. The null proxy host signifies default * credentials, which should be used when no {@link Credentials credentials} * have been explictly supplied for the challenging proxy host. Any previous * credentials for the given proxy realm on the given proxy host will be * overwritten. * * @param realm the authentication realm * @param proxyHost the proxy host * @param credentials the authentication credentials for the given realm * * @see #getProxyCredentials(AuthScope) * @see #setCredentials(AuthScope, Credentials) * * @deprecated use #setProxyCredentials(AuthScope, Credentials) */ public synchronized void setProxyCredentials( String realm, String proxyHost, Credentials credentials ) { LOG.trace("enter HttpState.setProxyCredentials(String, String, Credentials"); proxyCred.put(new AuthScope(proxyHost, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME), credentials); } /** * Sets the {@link Credentials proxy credentials} for the given authentication * realm. Any previous credentials for the given realm will be overwritten. * * @param authscope the {@link AuthScope authentication scope} * @param credentials the authentication {@link Credentials credentials} * for the given realm. * * @see #getProxyCredentials(AuthScope) * @see #setCredentials(AuthScope, Credentials) * * @since 3.0 */ public synchronized void setProxyCredentials(final AuthScope authscope, final Credentials credentials) { if (authscope == null) { throw new IllegalArgumentException("Authentication scope may not be null"); } LOG.trace("enter HttpState.setProxyCredentials(AuthScope, Credentials)"); proxyCred.put(authscope, credentials); } /** * Get the {@link Credentials credentials} for the proxy host with the given * authentication scope. * * If the realm exists on host, return the coresponding credentials. * If the host exists with a null realm, return the corresponding * credentials. * If the realm exists with a null host, return the * corresponding credentials. If the realm does not exist, return * the default Credentials. If there are no default credentials, return * null. * * @param realm the authentication realm * @param proxyHost the proxy host the realm is on * @return the credentials * @see #setProxyCredentials(String, String, Credentials) * * @deprecated use #getProxyCredentials(AuthScope) */ public synchronized Credentials getProxyCredentials(String realm, String proxyHost) { LOG.trace("enter HttpState.getCredentials(String, String"); return matchCredentials(this.proxyCred, new AuthScope(proxyHost, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME)); } /** * Get the {@link Credentials proxy credentials} for the given authentication scope. * * @param authscope the {@link AuthScope authentication scope} * @return the credentials * * @see #setProxyCredentials(AuthScope, Credentials) * * @since 3.0 */ public synchronized Credentials getProxyCredentials(final AuthScope authscope) { if (authscope == null) { throw new IllegalArgumentException("Authentication scope may not be null"); } LOG.trace("enter HttpState.getProxyCredentials(AuthScope)"); return matchCredentials(this.proxyCred, authscope); } /** * Returns a string representation of this HTTP state. * * @return The string representation of the HTTP state. * * @see java.lang.Object#toString() */ public synchronized String toString() { StringBuffer sbResult = new StringBuffer(); sbResult.append("["); sbResult.append(getCredentialsStringRepresentation(proxyCred)); sbResult.append(" | "); sbResult.append(getCredentialsStringRepresentation(credMap)); sbResult.append(" | "); sbResult.append(getCookiesStringRepresentation(cookies)); sbResult.append("]"); String strResult = sbResult.toString(); return strResult; } /** * Returns a string representation of the credentials. * @param credMap The credentials. * @return The string representation. */ private static String getCredentialsStringRepresentation(final Map credMap) { StringBuffer sbResult = new StringBuffer(); Iterator iter = credMap.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); Credentials cred = (Credentials) credMap.get(key); if (sbResult.length() > 0) { sbResult.append(", "); } sbResult.append(key); sbResult.append("#"); sbResult.append(cred.toString()); } return sbResult.toString(); } /** * Returns a string representation of the cookies. * @param cookies The cookies * @return The string representation. */ private static String getCookiesStringRepresentation(final List cookies) { StringBuffer sbResult = new StringBuffer(); Iterator iter = cookies.iterator(); while (iter.hasNext()) { Cookie ck = (Cookie) iter.next(); if (sbResult.length() > 0) { sbResult.append("#"); } sbResult.append(ck.toExternalForm()); } return sbResult.toString(); } /** * Clears all credentials. */ public void clearCredentials() { this.credMap.clear(); } /** * Clears all proxy credentials. */ public void clearProxyCredentials() { this.proxyCred.clear(); } /** * Clears all cookies. */ public synchronized void clearCookies() { this.cookies.clear(); } /** * Clears the state information (all cookies, credentials and proxy credentials). */ public void clear() { clearCookies(); clearCredentials(); clearProxyCredentials(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpStatus.java100644 0 0 33312 10661532626 24723 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpStatus.java,v 1.18 2004/05/02 11:21:13 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * Constants enumerating the HTTP status codes. * All status codes defined in RFC1945 (HTTP/1.0, RFC2616 (HTTP/1.1), and * RFC2518 (WebDAV) are supported. * * @see StatusLine * @author Unascribed * @author Mike Bowler * @author Jeff Dever * * TODO: Internationalization of reason phrases * * @version $Id: HttpStatus.java 480424 2006-11-29 05:56:49Z bayard $ */ public class HttpStatus { // -------------------------------------------------------- Class Variables /** Reason phrases lookup table. */ private static final String[][] REASON_PHRASES = new String[][]{ new String[0], new String[3], new String[8], new String[8], new String[25], new String[8] }; // --------------------------------------------------------- Public Methods /** * Get the reason phrase for a particular status code. * * This method always returns the English text as specified in the * relevent RFCs and is not internationalized. * * @param statusCode the numeric status code * @return the reason phrase associated with the given status code * or null if the status code is not recognized. * * TODO: getStatusText should be called getReasonPhrase to match RFC */ public static String getStatusText(int statusCode) { if (statusCode < 0) { throw new IllegalArgumentException("status code may not be negative"); } int classIndex = statusCode / 100; int codeIndex = statusCode - classIndex * 100; if (classIndex < 1 || classIndex > (REASON_PHRASES.length - 1) || codeIndex < 0 || codeIndex > (REASON_PHRASES[classIndex].length - 1)) { return null; } return REASON_PHRASES[classIndex][codeIndex]; } // -------------------------------------------------------- Private Methods /** * Store the given reason phrase, by status code. * @param statusCode The status code to lookup * @param reasonPhrase The reason phrase for this status code */ private static void addStatusCodeMap(int statusCode, String reasonPhrase) { int classIndex = statusCode / 100; REASON_PHRASES[classIndex][statusCode - classIndex * 100] = reasonPhrase; } // -------------------------------------------------------------- Constants // --- 1xx Informational --- /** 100 Continue (HTTP/1.1 - RFC 2616) */ public static final int SC_CONTINUE = 100; /** 101 Switching Protocols (HTTP/1.1 - RFC 2616)*/ public static final int SC_SWITCHING_PROTOCOLS = 101; /** 102 Processing (WebDAV - RFC 2518) */ public static final int SC_PROCESSING = 102; // --- 2xx Success --- /** 200 OK (HTTP/1.0 - RFC 1945) */ public static final int SC_OK = 200; /** 201 Created (HTTP/1.0 - RFC 1945) */ public static final int SC_CREATED = 201; /** 202 Accepted (HTTP/1.0 - RFC 1945) */ public static final int SC_ACCEPTED = 202; /** 203 Non Authoritative Information (HTTP/1.1 - RFC 2616) */ public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203; /** 204 No Content (HTTP/1.0 - RFC 1945) */ public static final int SC_NO_CONTENT = 204; /** 205 Reset Content (HTTP/1.1 - RFC 2616) */ public static final int SC_RESET_CONTENT = 205; /** 206 Partial Content (HTTP/1.1 - RFC 2616) */ public static final int SC_PARTIAL_CONTENT = 206; /** * 207 Multi-Status (WebDAV - RFC 2518) or 207 Partial Update * OK (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?) */ public static final int SC_MULTI_STATUS = 207; // --- 3xx Redirection --- /** 300 Mutliple Choices (HTTP/1.1 - RFC 2616) */ public static final int SC_MULTIPLE_CHOICES = 300; /** 301 Moved Permanently (HTTP/1.0 - RFC 1945) */ public static final int SC_MOVED_PERMANENTLY = 301; /** 302 Moved Temporarily (Sometimes Found) (HTTP/1.0 - RFC 1945) */ public static final int SC_MOVED_TEMPORARILY = 302; /** 303 See Other (HTTP/1.1 - RFC 2616) */ public static final int SC_SEE_OTHER = 303; /** 304 Not Modified (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_MODIFIED = 304; /** 305 Use Proxy (HTTP/1.1 - RFC 2616) */ public static final int SC_USE_PROXY = 305; /** 307 Temporary Redirect (HTTP/1.1 - RFC 2616) */ public static final int SC_TEMPORARY_REDIRECT = 307; // --- 4xx Client Error --- /** 400 Bad Request (HTTP/1.1 - RFC 2616) */ public static final int SC_BAD_REQUEST = 400; /** 401 Unauthorized (HTTP/1.0 - RFC 1945) */ public static final int SC_UNAUTHORIZED = 401; /** 402 Payment Required (HTTP/1.1 - RFC 2616) */ public static final int SC_PAYMENT_REQUIRED = 402; /** 403 Forbidden (HTTP/1.0 - RFC 1945) */ public static final int SC_FORBIDDEN = 403; /** 404 Not Found (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_FOUND = 404; /** 405 Method Not Allowed (HTTP/1.1 - RFC 2616) */ public static final int SC_METHOD_NOT_ALLOWED = 405; /** 406 Not Acceptable (HTTP/1.1 - RFC 2616) */ public static final int SC_NOT_ACCEPTABLE = 406; /** 407 Proxy Authentication Required (HTTP/1.1 - RFC 2616)*/ public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; /** 408 Request Timeout (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_TIMEOUT = 408; /** 409 Conflict (HTTP/1.1 - RFC 2616) */ public static final int SC_CONFLICT = 409; /** 410 Gone (HTTP/1.1 - RFC 2616) */ public static final int SC_GONE = 410; /** 411 Length Required (HTTP/1.1 - RFC 2616) */ public static final int SC_LENGTH_REQUIRED = 411; /** 412 Precondition Failed (HTTP/1.1 - RFC 2616) */ public static final int SC_PRECONDITION_FAILED = 412; /** 413 Request Entity Too Large (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_TOO_LONG = 413; /** 414 Request-URI Too Long (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_URI_TOO_LONG = 414; /** 415 Unsupported Media Type (HTTP/1.1 - RFC 2616) */ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; /** 416 Requested Range Not Satisfiable (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; /** 417 Expectation Failed (HTTP/1.1 - RFC 2616) */ public static final int SC_EXPECTATION_FAILED = 417; /** * Static constant for a 418 error. * 418 Unprocessable Entity (WebDAV drafts?) * or 418 Reauthentication Required (HTTP/1.1 drafts?) */ // not used // public static final int SC_UNPROCESSABLE_ENTITY = 418; /** * Static constant for a 419 error. * 419 Insufficient Space on Resource * (WebDAV - draft-ietf-webdav-protocol-05?) * or 419 Proxy Reauthentication Required * (HTTP/1.1 drafts?) */ public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419; /** * Static constant for a 420 error. * 420 Method Failure * (WebDAV - draft-ietf-webdav-protocol-05?) */ public static final int SC_METHOD_FAILURE = 420; /** 422 Unprocessable Entity (WebDAV - RFC 2518) */ public static final int SC_UNPROCESSABLE_ENTITY = 422; /** 423 Locked (WebDAV - RFC 2518) */ public static final int SC_LOCKED = 423; /** 424 Failed Dependency (WebDAV - RFC 2518) */ public static final int SC_FAILED_DEPENDENCY = 424; // --- 5xx Server Error --- /** 500 Server Error (HTTP/1.0 - RFC 1945) */ public static final int SC_INTERNAL_SERVER_ERROR = 500; /** 501 Not Implemented (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_IMPLEMENTED = 501; /** 502 Bad Gateway (HTTP/1.0 - RFC 1945) */ public static final int SC_BAD_GATEWAY = 502; /** 503 Service Unavailable (HTTP/1.0 - RFC 1945) */ public static final int SC_SERVICE_UNAVAILABLE = 503; /** 504 Gateway Timeout (HTTP/1.1 - RFC 2616) */ public static final int SC_GATEWAY_TIMEOUT = 504; /** 505 HTTP Version Not Supported (HTTP/1.1 - RFC 2616) */ public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505; /** 507 Insufficient Storage (WebDAV - RFC 2518) */ public static final int SC_INSUFFICIENT_STORAGE = 507; // ----------------------------------------------------- Static Initializer /** Set up status code to "reason phrase" map. */ static { // HTTP 1.0 Server status codes -- see RFC 1945 addStatusCodeMap(SC_OK, "OK"); addStatusCodeMap(SC_CREATED, "Created"); addStatusCodeMap(SC_ACCEPTED, "Accepted"); addStatusCodeMap(SC_NO_CONTENT, "No Content"); addStatusCodeMap(SC_MOVED_PERMANENTLY, "Moved Permanently"); addStatusCodeMap(SC_MOVED_TEMPORARILY, "Moved Temporarily"); addStatusCodeMap(SC_NOT_MODIFIED, "Not Modified"); addStatusCodeMap(SC_BAD_REQUEST, "Bad Request"); addStatusCodeMap(SC_UNAUTHORIZED, "Unauthorized"); addStatusCodeMap(SC_FORBIDDEN, "Forbidden"); addStatusCodeMap(SC_NOT_FOUND, "Not Found"); addStatusCodeMap(SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); addStatusCodeMap(SC_NOT_IMPLEMENTED, "Not Implemented"); addStatusCodeMap(SC_BAD_GATEWAY, "Bad Gateway"); addStatusCodeMap(SC_SERVICE_UNAVAILABLE, "Service Unavailable"); // HTTP 1.1 Server status codes -- see RFC 2048 addStatusCodeMap(SC_CONTINUE, "Continue"); addStatusCodeMap(SC_TEMPORARY_REDIRECT, "Temporary Redirect"); addStatusCodeMap(SC_METHOD_NOT_ALLOWED, "Method Not Allowed"); addStatusCodeMap(SC_CONFLICT, "Conflict"); addStatusCodeMap(SC_PRECONDITION_FAILED, "Precondition Failed"); addStatusCodeMap(SC_REQUEST_TOO_LONG, "Request Too Long"); addStatusCodeMap(SC_REQUEST_URI_TOO_LONG, "Request-URI Too Long"); addStatusCodeMap(SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type"); addStatusCodeMap(SC_MULTIPLE_CHOICES, "Multiple Choices"); addStatusCodeMap(SC_SEE_OTHER, "See Other"); addStatusCodeMap(SC_USE_PROXY, "Use Proxy"); addStatusCodeMap(SC_PAYMENT_REQUIRED, "Payment Required"); addStatusCodeMap(SC_NOT_ACCEPTABLE, "Not Acceptable"); addStatusCodeMap(SC_PROXY_AUTHENTICATION_REQUIRED, "Proxy Authentication Required"); addStatusCodeMap(SC_REQUEST_TIMEOUT, "Request Timeout"); addStatusCodeMap(SC_SWITCHING_PROTOCOLS, "Switching Protocols"); addStatusCodeMap(SC_NON_AUTHORITATIVE_INFORMATION, "Non Authoritative Information"); addStatusCodeMap(SC_RESET_CONTENT, "Reset Content"); addStatusCodeMap(SC_PARTIAL_CONTENT, "Partial Content"); addStatusCodeMap(SC_GATEWAY_TIMEOUT, "Gateway Timeout"); addStatusCodeMap(SC_HTTP_VERSION_NOT_SUPPORTED, "Http Version Not Supported"); addStatusCodeMap(SC_GONE, "Gone"); addStatusCodeMap(SC_LENGTH_REQUIRED, "Length Required"); addStatusCodeMap(SC_REQUESTED_RANGE_NOT_SATISFIABLE, "Requested Range Not Satisfiable"); addStatusCodeMap(SC_EXPECTATION_FAILED, "Expectation Failed"); // WebDAV Server-specific status codes addStatusCodeMap(SC_PROCESSING, "Processing"); addStatusCodeMap(SC_MULTI_STATUS, "Multi-Status"); addStatusCodeMap(SC_UNPROCESSABLE_ENTITY, "Unprocessable Entity"); addStatusCodeMap(SC_INSUFFICIENT_SPACE_ON_RESOURCE, "Insufficient Space On Resource"); addStatusCodeMap(SC_METHOD_FAILURE, "Method Failure"); addStatusCodeMap(SC_LOCKED, "Locked"); addStatusCodeMap(SC_INSUFFICIENT_STORAGE , "Insufficient Storage"); addStatusCodeMap(SC_FAILED_DEPENDENCY, "Failed Dependency"); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpURL.java100644 0 0 70642 10661532627 24112 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpURL.java,v 1.18 2004/09/30 17:26:41 oglueck Exp $ * $Revision: 507324 $ * $Date: 2007-02-14 01:12:11 +0100 (Wed, 14 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.util.URIUtil; /** * The HTTP URL. * * @author Sung-Gu * @author Mike Bowler */ public class HttpURL extends URI { // ----------------------------------------------------------- Constructors /** Create an instance as an internal use. */ protected HttpURL() { } /** * Construct a HTTP URL as an escaped form of a character array with the * given charset to do escape encoding. * * @param escaped the HTTP URL character sequence * @param charset the charset string to do escape encoding * @throws URIException If {@link #checkValid()} fails * @throws NullPointerException if escaped is null * @see #getProtocolCharset */ public HttpURL(char[] escaped, String charset) throws URIException, NullPointerException { protocolCharset = charset; parseUriReference(new String(escaped), true); checkValid(); } /** * Construct a HTTP URL as an escaped form of a character array. * * @param escaped the HTTP URL character sequence * @throws URIException If {@link #checkValid()} fails * @throws NullPointerException if escaped is null * @see #getDefaultProtocolCharset */ public HttpURL(char[] escaped) throws URIException, NullPointerException { parseUriReference(new String(escaped), true); checkValid(); } /** * Construct a HTTP URL from a given string with the given charset to do * escape encoding. * * @param original the HTTP URL string * @param charset the charset string to do escape encoding * @throws URIException If {@link #checkValid()} fails * @see #getProtocolCharset */ public HttpURL(String original, String charset) throws URIException { protocolCharset = charset; parseUriReference(original, false); checkValid(); } /** * Construct a HTTP URL from a given string. * * @param original the HTTP URL string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String original) throws URIException { parseUriReference(original, false); checkValid(); } /** * Construct a HTTP URL from given components. * * @param host the host string * @param port the port number * @param path the path string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String host, int port, String path) throws URIException { this(null, null, host, port, path, null, null); } /** * Construct a HTTP URL from given components. * * @param host the host string * @param port the port number * @param path the path string * @param query the query string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String host, int port, String path, String query) throws URIException { this(null, null, host, port, path, query, null); } /** * Construct a HTTP URL from given components. * * @param user the user name * @param password his or her password * @param host the host string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String user, String password, String host) throws URIException { this(user, password, host, -1, null, null, null); } /** * Construct a HTTP URL from given components. * * @param user the user name * @param password his or her password * @param host the host string * @param port the port number * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String user, String password, String host, int port) throws URIException { this(user, password, host, port, null, null, null); } /** * Construct a HTTP URL from given components. * * @param user the user name * @param password his or her password * @param host the host string * @param port the port number * @param path the path string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String user, String password, String host, int port, String path) throws URIException { this(user, password, host, port, path, null, null); } /** * Construct a HTTP URL from given components. * * @param user the user name * @param password his or her password * @param host the host string * @param port the port number * @param path the path string * @param query The query string. * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String user, String password, String host, int port, String path, String query) throws URIException { this(user, password, host, port, path, query, null); } /** * Construct a HTTP URL from given components. * * @param host the host string * @param path the path string * @param query the query string * @param fragment the fragment string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String host, String path, String query, String fragment) throws URIException { this(null, null, host, -1, path, query, fragment); } /** * Construct a HTTP URL from given components. * * Note: The userinfo format is normally * <username>:<password> where * username and password must both be URL escaped. * * @param userinfo the userinfo string whose parts are URL escaped * @param host the host string * @param path the path string * @param query the query string * @param fragment the fragment string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String userinfo, String host, String path, String query, String fragment) throws URIException { this(userinfo, host, -1, path, query, fragment); } /** * Construct a HTTP URL from given components. * * Note: The userinfo format is normally * <username>:<password> where * username and password must both be URL escaped. * * @param userinfo the userinfo string whose parts are URL escaped * @param host the host string * @param port the port number * @param path the path string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String userinfo, String host, int port, String path) throws URIException { this(userinfo, host, port, path, null, null); } /** * Construct a HTTP URL from given components. * * Note: The userinfo format is normally * <username>:<password> where * username and password must both be URL escaped. * * @param userinfo the userinfo string whose parts are URL escaped * @param host the host string * @param port the port number * @param path the path string * @param query the query string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String userinfo, String host, int port, String path, String query) throws URIException { this(userinfo, host, port, path, query, null); } /** * Construct a HTTP URL from given components. * * Note: The userinfo format is normally * <username>:<password> where * username and password must both be URL escaped. * * @param userinfo the userinfo string whose parts are URL escaped * @param host the host string * @param port the port number * @param path the path string * @param query the query string * @param fragment the fragment string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String userinfo, String host, int port, String path, String query, String fragment) throws URIException { // validate and contruct the URI character sequence StringBuffer buff = new StringBuffer(); if (userinfo != null || host != null || port != -1) { _scheme = DEFAULT_SCHEME; // in order to verify the own protocol buff.append(_default_scheme); buff.append("://"); if (userinfo != null) { buff.append(userinfo); buff.append('@'); } if (host != null) { buff.append(URIUtil.encode(host, URI.allowed_host)); if (port != -1 || port != DEFAULT_PORT) { buff.append(':'); buff.append(port); } } } if (path != null) { // accept empty path if (scheme != null && !path.startsWith("/")) { throw new URIException(URIException.PARSING, "abs_path requested"); } buff.append(URIUtil.encode(path, URI.allowed_abs_path)); } if (query != null) { buff.append('?'); buff.append(URIUtil.encode(query, URI.allowed_query)); } if (fragment != null) { buff.append('#'); buff.append(URIUtil.encode(fragment, URI.allowed_fragment)); } parseUriReference(buff.toString(), true); checkValid(); } /** * Construct a HTTP URL from given components. * * @param user the user name * @param password his or her password * @param host the host string * @param port the port number * @param path the path string * @param query the query string * @param fragment the fragment string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpURL(String user, String password, String host, int port, String path, String query, String fragment) throws URIException { this(toUserinfo(user, password), host, port, path, query, fragment); } protected static String toUserinfo(String user, String password) throws URIException { if (user == null) return null; StringBuffer usrinfo = new StringBuffer(20); //sufficient for real world usrinfo.append(URIUtil.encode(user, URI.allowed_within_userinfo)); if (password == null) return usrinfo.toString(); usrinfo.append(':'); usrinfo.append(URIUtil.encode(password, URI.allowed_within_userinfo)); return usrinfo.toString(); } /** * Construct a HTTP URL with a given relative URL string. * * @param base the base HttpURL * @param relative the relative HTTP URL string * @throws URIException If {@link #checkValid()} fails */ public HttpURL(HttpURL base, String relative) throws URIException { this(base, new HttpURL(relative)); } /** * Construct a HTTP URL with a given relative URL. * * @param base the base HttpURL * @param relative the relative HttpURL * @throws URIException If {@link #checkValid()} fails */ public HttpURL(HttpURL base, HttpURL relative) throws URIException { super(base, relative); checkValid(); } // -------------------------------------------------------------- Constants /** * Default scheme for HTTP URL. */ public static final char[] DEFAULT_SCHEME = { 'h', 't', 't', 'p' }; /** * Default scheme for HTTP URL. * @deprecated Use {@link #DEFAULT_SCHEME} instead. This one doesn't * conform to the project naming conventions. */ public static final char[] _default_scheme = DEFAULT_SCHEME; /** * Default port for HTTP URL. */ public static final int DEFAULT_PORT = 80; /** * Default port for HTTP URL. * @deprecated Use {@link #DEFAULT_PORT} instead. This one doesn't conform * to the project naming conventions. */ public static final int _default_port = DEFAULT_PORT; /** * The serialVersionUID. */ static final long serialVersionUID = -7158031098595039459L; // ------------------------------------------------------------- The scheme /** * Get the scheme. You can get the scheme explicitly. * * @return the scheme */ public char[] getRawScheme() { return (_scheme == null) ? null : HttpURL.DEFAULT_SCHEME; } /** * Get the scheme. You can get the scheme explicitly. * * @return the scheme null if empty or undefined */ public String getScheme() { return (_scheme == null) ? null : new String(HttpURL.DEFAULT_SCHEME); } // --------------------------------------------------------------- The port /** * Get the port number. * @return the port number */ public int getPort() { return (_port == -1) ? HttpURL.DEFAULT_PORT : _port; } // ----------------------------------------------------------- The userinfo /** * Set the raw-escaped user and password. * * @param escapedUser the raw-escaped user * @param escapedPassword the raw-escaped password; could be null * @throws URIException escaped user not valid or user required; escaped * password not valid or username missed */ public void setRawUserinfo(char[] escapedUser, char[] escapedPassword) throws URIException { if (escapedUser == null || escapedUser.length == 0) { throw new URIException(URIException.PARSING, "user required"); } if (!validate(escapedUser, within_userinfo) || ((escapedPassword != null) && !validate(escapedPassword, within_userinfo))) { throw new URIException(URIException.ESCAPING, "escaped userinfo not valid"); } String username = new String(escapedUser); String password = (escapedPassword == null) ? null : new String(escapedPassword); String userinfo = username + ((password == null) ? "" : ":" + password); String hostname = new String(getRawHost()); String hostport = (_port == -1) ? hostname : hostname + ":" + _port; String authority = userinfo + "@" + hostport; _userinfo = userinfo.toCharArray(); _authority = authority.toCharArray(); setURI(); } /** * Set the raw-escaped user and password. * * @param escapedUser the escaped user * @param escapedPassword the escaped password; could be null * @throws URIException escaped user not valid or user required; escaped * password not valid or username missed * @throws NullPointerException null user */ public void setEscapedUserinfo(String escapedUser, String escapedPassword) throws URIException, NullPointerException { setRawUserinfo(escapedUser.toCharArray(), (escapedPassword == null) ? null : escapedPassword.toCharArray()); } /** * Set the user and password. * * @param user the user * @param password the password; could be null * @throws URIException encoding error or username missed * @throws NullPointerException null user */ public void setUserinfo(String user, String password) throws URIException, NullPointerException { // set the charset to do escape encoding String charset = getProtocolCharset(); setRawUserinfo(encode(user, within_userinfo, charset), (password == null) ? null : encode(password, within_userinfo, charset)); } /** * Set the raw-escaped user. * * @param escapedUser the raw-escaped user * @throws URIException escaped user not valid or user required */ public void setRawUser(char[] escapedUser) throws URIException { if (escapedUser == null || escapedUser.length == 0) { throw new URIException(URIException.PARSING, "user required"); } if (!validate(escapedUser, within_userinfo)) { throw new URIException(URIException.ESCAPING, "escaped user not valid"); } String username = new String(escapedUser); char[] rawPassword = getRawPassword(); String password = rawPassword == null ? null : new String(rawPassword); String userinfo = username + ((password == null) ? "" : ":" + password); String hostname = new String(getRawHost()); String hostport = (_port == -1) ? hostname : hostname + ":" + _port; String authority = userinfo + "@" + hostport; _userinfo = userinfo.toCharArray(); _authority = authority.toCharArray(); setURI(); } /** * Set the escaped user string. * * @param escapedUser the escaped user string * @throws URIException escaped user not valid * @throws NullPointerException null user */ public void setEscapedUser(String escapedUser) throws URIException, NullPointerException { setRawUser(escapedUser.toCharArray()); } /** * Set the user string. * * @param user the user string * @throws URIException user encoding error * @throws NullPointerException null user */ public void setUser(String user) throws URIException, NullPointerException { setRawUser(encode(user, allowed_within_userinfo, getProtocolCharset())); } /** * Get the raw-escaped user. * * @return the raw-escaped user */ public char[] getRawUser() { if (_userinfo == null || _userinfo.length == 0) { return null; } int to = indexFirstOf(_userinfo, ':'); // String.indexOf(':', 0, _userinfo.length, _userinfo, 0, 1, 0); if (to == -1) { return _userinfo; // only user. } char[] result = new char[to]; System.arraycopy(_userinfo, 0, result, 0, to); return result; } /** * Get the escaped user * * @return the escaped user */ public String getEscapedUser() { char[] user = getRawUser(); return (user == null) ? null : new String(user); } /** * Get the user. * * @return the user name * @throws URIException If {@link #decode} fails */ public String getUser() throws URIException { char[] user = getRawUser(); return (user == null) ? null : decode(user, getProtocolCharset()); } /** * Set the raw-escaped password. * * @param escapedPassword the raw-escaped password; could be null * @throws URIException escaped password not valid or username missed */ public void setRawPassword(char[] escapedPassword) throws URIException { if (escapedPassword != null && !validate(escapedPassword, within_userinfo)) { throw new URIException(URIException.ESCAPING, "escaped password not valid"); } if (getRawUser() == null || getRawUser().length == 0) { throw new URIException(URIException.PARSING, "username required"); } String username = new String(getRawUser()); String password = escapedPassword == null ? null : new String(escapedPassword); // an emtpy string is allowed as a password String userinfo = username + ((password == null) ? "" : ":" + password); String hostname = new String(getRawHost()); String hostport = (_port == -1) ? hostname : hostname + ":" + _port; String authority = userinfo + "@" + hostport; _userinfo = userinfo.toCharArray(); _authority = authority.toCharArray(); setURI(); } /** * Set the escaped password string. * * @param escapedPassword the escaped password string; could be null * @throws URIException escaped password not valid or username missed */ public void setEscapedPassword(String escapedPassword) throws URIException { setRawPassword((escapedPassword == null) ? null : escapedPassword.toCharArray()); } /** * Set the password string. * * @param password the password string; could be null * @throws URIException encoding error or username missed */ public void setPassword(String password) throws URIException { setRawPassword((password == null) ? null : encode(password, allowed_within_userinfo, getProtocolCharset())); } /** * Get the raw-escaped password. * * @return the raw-escaped password */ public char[] getRawPassword() { int from = indexFirstOf(_userinfo, ':'); if (from == -1) { return null; // null or only user. } int len = _userinfo.length - from - 1; char[] result = new char[len]; System.arraycopy(_userinfo, from + 1, result, 0, len); return result; } /** * Get the escaped password. * * @return the escaped password */ public String getEscapedPassword() { char[] password = getRawPassword(); return (password == null) ? null : new String(password); } /** * Get the password. * * @return the password * @throws URIException If {@link #decode(char[],String)} fails. */ public String getPassword() throws URIException { char[] password = getRawPassword(); return (password == null) ? null : decode(password, getProtocolCharset()); } // --------------------------------------------------------------- The path /** * Get the raw-escaped current hierarchy level. * * @return the raw-escaped current hierarchy level * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. */ public char[] getRawCurrentHierPath() throws URIException { return (_path == null || _path.length == 0) ? rootPath : super.getRawCurrentHierPath(_path); } /** * Get the level above the this hierarchy level. * * @return the raw above hierarchy level * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. */ public char[] getRawAboveHierPath() throws URIException { char[] path = getRawCurrentHierPath(); return (path == null || path.length == 0) ? rootPath : getRawCurrentHierPath(path); } /** * Get the raw escaped path. * * @return the path '/' if empty or undefined */ public char[] getRawPath() { char[] path = super.getRawPath(); return (path == null || path.length == 0) ? rootPath : path; } // -------------------------------------------------------------- The query /** * Set the query as the name and value pair. * * @param queryName the query string. * @param queryValue the query string. * @throws URIException incomplete trailing escape pattern * Or unsupported character encoding * @throws NullPointerException null query * @see #encode */ public void setQuery(String queryName, String queryValue) throws URIException, NullPointerException { StringBuffer buff = new StringBuffer(); // set the charset to do escape encoding String charset = getProtocolCharset(); buff.append(encode(queryName, allowed_within_query, charset)); buff.append('='); buff.append(encode(queryValue, allowed_within_query, charset)); _query = buff.toString().toCharArray(); setURI(); } /** * Set the query as the name and value pairs. * * @param queryName the array of the query string. * @param queryValue the array of the query string. * @throws URIException incomplete trailing escape pattern, * unsupported character encoding or wrong array size * @throws NullPointerException null query * @see #encode */ public void setQuery(String[] queryName, String[] queryValue) throws URIException, NullPointerException { int length = queryName.length; if (length != queryValue.length) { throw new URIException("wrong array size of query"); } StringBuffer buff = new StringBuffer(); // set the charset to do escape encoding String charset = getProtocolCharset(); for (int i = 0; i < length; i++) { buff.append(encode(queryName[i], allowed_within_query, charset)); buff.append('='); buff.append(encode(queryValue[i], allowed_within_query, charset)); if (i + 1 < length) { buff.append('&'); } } _query = buff.toString().toCharArray(); setURI(); } // ---------------------------------------------------------------- Utility /** * Verify the valid class use for construction. * * @throws URIException the wrong scheme use */ protected void checkValid() throws URIException { // could be explicit protocol or undefined. if (!(equals(_scheme, DEFAULT_SCHEME) || _scheme == null)) { throw new URIException(URIException.PARSING, "wrong class use"); } } /** * Once it's parsed successfully, set this URI. * * @see #getRawURI */ protected void setURI() { // set _uri StringBuffer buf = new StringBuffer(); // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? if (_scheme != null) { buf.append(_scheme); buf.append(':'); } if (_is_net_path) { buf.append("//"); if (_authority != null) { // has_authority if (_userinfo != null) { // by default, remove userinfo part if (_host != null) { buf.append(_host); if (_port != -1) { buf.append(':'); buf.append(_port); } } } else { buf.append(_authority); } } } if (_opaque != null && _is_opaque_part) { buf.append(_opaque); } else if (_path != null) { // _is_hier_part or _is_relativeURI if (_path.length != 0) { buf.append(_path); } } if (_query != null) { // has_query buf.append('?'); buf.append(_query); } // ignore the fragment identifier _uri = buf.toString().toCharArray(); hash = 0; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpVersion.java100644 0 0 21025 10661532626 25063 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpVersion.java,v 1.6 2004/12/20 19:52:50 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** *

HTTP version, as specified in RFC 2616.

*

* HTTP uses a "<major>.<minor>" numbering scheme to indicate * versions of the protocol. The protocol versioning policy is intended to * allow the sender to indicate the format of a message and its capacity for * understanding further HTTP communication, rather than the features * obtained via that communication. No change is made to the version * number for the addition of message components which do not affect * communication behavior or which only add to extensible field values. * The <minor> number is incremented when the changes made to the * protocol add features which do not change the general message parsing * algorithm, but which may add to the message semantics and imply * additional capabilities of the sender. The <major> number is * incremented when the format of a message within the protocol is * changed. See RFC 2145 [36] for a fuller explanation. *

*

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

* Note that the major and minor numbers MUST be treated as separate * integers and that each MAY be incremented higher than a single digit. * Thus, HTTP/2.4 is a lower version than HTTP/2.13, which in turn is * lower than HTTP/12.3. Leading zeros MUST be ignored by recipients and * MUST NOT be sent. *

* * @author Oleg Kalnichevski * * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * @since 3.0 */ public class HttpVersion implements Comparable { /** Major version number of the HTTP protocol */ private int major = 0; /** Minor version number of the HTTP protocol */ private int minor = 0; /** 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(int major, int minor) { if (major < 0) { throw new IllegalArgumentException("HTTP major version number may not be negative"); } this.major = major; if (minor < 0) { throw new IllegalArgumentException("HTTP minor version number may not be negative"); } this.minor = minor; } /** * Returns the major version number of the HTTP protocol. * * @return the major version number. */ public int getMajor() { return major; } /** * Returns the minor version number of the HTTP protocol. * * @return the minor version number. */ public int getMinor() { return minor; } /** * @see java.lang.Object#hashCode() */ public int hashCode() { return this.major * 100000 + this.minor; } /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof HttpVersion)) { return false; } return equals((HttpVersion)obj); } /** * Compares this HTTP protocol version with another one. * * @param anotherVer the version to be compared with. * * @return a negative integer, zero, or a positive integer as this version is less than, * equal to, or greater than the specified version. */ public int compareTo(HttpVersion anotherVer) { if (anotherVer == null) { throw new IllegalArgumentException("Version parameter may not be null"); } int delta = getMajor() - anotherVer.getMajor(); if (delta == 0) { delta = getMinor() - anotherVer.getMinor(); } return delta; } /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Object o) { return compareTo((HttpVersion)o); } /** * Test if the HTTP protocol version is equal to the given number. * * @return true if HTTP protocol version is given to the given number, * false otherwise. */ public boolean equals(HttpVersion version) { return compareTo(version) == 0; } /** * Test if the HTTP protocol version is greater or equal to the given number. * * @return true if HTTP protocol version is greater or equal given to the * given number, false otherwise. */ public boolean greaterEquals(HttpVersion version) { return compareTo(version) >= 0; } /** * Test if the HTTP protocol version is less or equal to the given number. * * @return true if HTTP protocol version is less or equal to given to the * given number, false otherwise. */ public boolean lessEquals(HttpVersion version) { return compareTo(version) <= 0; } /** * @see java.lang.Object#toString() */ public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("HTTP/"); buffer.append(this.major); buffer.append('.'); buffer.append(this.minor); return buffer.toString(); } /** * Parses the textual representation of the given HTTP protocol version. * * @return HTTP protocol version. * * @throws ProtocolException if the string is not a valid HTTP protocol version. */ public static HttpVersion parse(final String s) throws ProtocolException { if (s == null) { throw new IllegalArgumentException("String may not be null"); } if (!s.startsWith("HTTP/")) { throw new ProtocolException("Invalid HTTP version string: " + s); } int major, minor; int i1 = "HTTP/".length(); int i2 = s.indexOf(".", i1); if (i2 == -1) { throw new ProtocolException("Invalid HTTP version number: " + s); } try { major = Integer.parseInt(s.substring(i1, i2)); } catch (NumberFormatException e) { throw new ProtocolException("Invalid HTTP major version number: " + s); } i1 = i2 + 1; i2 = s.length(); try { minor = Integer.parseInt(s.substring(i1, i2)); } catch (NumberFormatException e) { throw new ProtocolException("Invalid HTTP minor version number: " + s); } return new HttpVersion(major, minor); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/HttpsURL.java100644 0 0 35761 10661532627 24300 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpsURL.java,v 1.11 2004/09/30 17:26:41 oglueck Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.util.URIUtil; /** * The HTTPS URL. * * @author Sung-Gu * @author Mike Bowler */ public class HttpsURL extends HttpURL { // ----------------------------------------------------------- Constructors /** * Create an instance as an internal use. */ protected HttpsURL() { } /** * Construct a HTTPS URL as an escaped form of a character array with the * given charset to do escape encoding. * * @param escaped the HTTPS URL character sequence * @param charset the charset to do escape encoding * @throws URIException If {@link #checkValid()} fails * @throws NullPointerException if escaped is null * @see #getProtocolCharset */ public HttpsURL(char[] escaped, String charset) throws URIException, NullPointerException { protocolCharset = charset; parseUriReference(new String(escaped), true); checkValid(); } /** * Construct a HTTPS URL as an escaped form of a character array. * * @param escaped the HTTPS URL character sequence * @throws URIException If {@link #checkValid()} fails * @throws NullPointerException if escaped is null * @see #getDefaultProtocolCharset */ public HttpsURL(char[] escaped) throws URIException, NullPointerException { parseUriReference(new String(escaped), true); checkValid(); } /** * Construct a HTTPS URL from a given string with the given charset to do * escape encoding. * * @param original the HTTPS URL string * @param charset the charset to do escape encoding * @throws URIException If {@link #checkValid()} fails * @see #getProtocolCharset */ public HttpsURL(String original, String charset) throws URIException { protocolCharset = charset; parseUriReference(original, false); checkValid(); } /** * Construct a HTTPS URL from a given string. * * @param original the HTTPS URL string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String original) throws URIException { parseUriReference(original, false); checkValid(); } /** * Construct a HTTPS URL from given components. * * @param host the host string * @param port the port number * @param path the path string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String host, int port, String path) throws URIException { this(null, host, port, path, null, null); } /** * Construct a HTTPS URL from given components. * * @param host the host string * @param port the port number * @param path the path string * @param query the query string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String host, int port, String path, String query) throws URIException { this(null, host, port, path, query, null); } /** * Construct a HTTPS URL from given components. * * @param user the user name * @param password his or her password * @param host the host string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String user, String password, String host) throws URIException { this(user, password, host, -1, null, null, null); } /** * Construct a HTTPS URL from given components. * * @param user the user name * @param password his or her password * @param host the host string * @param port the port number * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String user, String password, String host, int port) throws URIException { this(user, password, host, port, null, null, null); } /** * Construct a HTTPS URL from given components. * * @param user the user name * @param password his or her password * @param host the host string * @param port the port number * @param path the path string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String user, String password, String host, int port, String path) throws URIException { this(user, password, host, port, path, null, null); } /** * Construct a HTTPS URL from given components. * * @param user the user name * @param password his or her password * @param host the host string * @param port the port number * @param path the path string * @param query The query string. * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String user, String password, String host, int port, String path, String query) throws URIException { this(user, password, host, port, path, query, null); } /** * Construct a HTTPS URL from given components. * * @param host the host string * @param path the path string * @param query the query string * @param fragment the fragment string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String host, String path, String query, String fragment) throws URIException { this(null, host, -1, path, query, fragment); } /** * Construct a HTTPS URL from given components. * * Note: The userinfo format is normally * <username>:<password> where * username and password must both be URL escaped. * * @param userinfo the userinfo string whose parts are URL escaped * @param host the host string * @param path the path string * @param query the query string * @param fragment the fragment string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String userinfo, String host, String path, String query, String fragment) throws URIException { this(userinfo, host, -1, path, query, fragment); } /** * Construct a HTTPS URL from given components. * * Note: The userinfo format is normally * <username>:<password> where * username and password must both be URL escaped. * * @param userinfo the userinfo string whose parts are URL escaped * @param host the host string * @param port the port number * @param path the path string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String userinfo, String host, int port, String path) throws URIException { this(userinfo, host, port, path, null, null); } /** * Construct a HTTPS URL from given components. * * Note: The userinfo format is normally * <username>:<password> where * username and password must both be URL escaped. * * @param userinfo the userinfo string whose parts are URL escaped * @param host the host string * @param port the port number * @param path the path string * @param query the query string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String userinfo, String host, int port, String path, String query) throws URIException { this(userinfo, host, port, path, query, null); } /** * Construct a HTTPS URL from given components. * * Note: The userinfo format is normally * <username>:<password> where * username and password must both be URL escaped. * * @param userinfo the userinfo string whose parts are URL escaped * @param host the host string * @param port the port number * @param path the path string * @param query the query string * @param fragment the fragment string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String userinfo, String host, int port, String path, String query, String fragment) throws URIException { // validate and contruct the URI character sequence StringBuffer buff = new StringBuffer(); if (userinfo != null || host != null || port != -1) { _scheme = DEFAULT_SCHEME; // in order to verify the own protocol buff.append(_default_scheme); buff.append("://"); if (userinfo != null) { buff.append(userinfo); buff.append('@'); } if (host != null) { buff.append(URIUtil.encode(host, URI.allowed_host)); if (port != -1 || port != DEFAULT_PORT) { buff.append(':'); buff.append(port); } } } if (path != null) { // accept empty path if (scheme != null && !path.startsWith("/")) { throw new URIException(URIException.PARSING, "abs_path requested"); } buff.append(URIUtil.encode(path, URI.allowed_abs_path)); } if (query != null) { buff.append('?'); buff.append(URIUtil.encode(query, URI.allowed_query)); } if (fragment != null) { buff.append('#'); buff.append(URIUtil.encode(fragment, URI.allowed_fragment)); } parseUriReference(buff.toString(), true); checkValid(); } /** * Construct a HTTP URL from given components. * * @param user the user name * @param password his or her password * @param host the host string * @param port the port number * @param path the path string * @param query the query string * @param fragment the fragment string * @throws URIException If {@link #checkValid()} fails * @see #getDefaultProtocolCharset */ public HttpsURL(String user, String password, String host, int port, String path, String query, String fragment) throws URIException { this(HttpURL.toUserinfo(user, password), host, port, path, query, fragment); } /** * Construct a HTTPS URL with a given relative HTTPS URL string. * * @param base the base HttpsURL * @param relative the relative HTTPS URL string * @throws URIException If {@link #checkValid()} fails */ public HttpsURL(HttpsURL base, String relative) throws URIException { this(base, new HttpsURL(relative)); } /** * Construct a HTTPS URL with a given relative URL. * * @param base the base HttpsURL * @param relative the relative HttpsURL * @throws URIException If {@link #checkValid()} fails */ public HttpsURL(HttpsURL base, HttpsURL relative) throws URIException { super(base, relative); checkValid(); } // -------------------------------------------------------------- Constants /** * Default scheme for HTTPS URL. */ public static final char[] DEFAULT_SCHEME = { 'h', 't', 't', 'p', 's' }; /** * Default scheme for HTTPS URL. * @deprecated Use {@link #DEFAULT_SCHEME} instead. This one doesn't * conform to the project naming conventions. */ public static final char[] _default_scheme = DEFAULT_SCHEME; /** * Default port for HTTPS URL. */ public static final int DEFAULT_PORT = 443; /** * Default port for HTTPS URL. * @deprecated Use {@link #DEFAULT_PORT} instead. This one doesn't conform * to the project naming conventions. */ public static final int _default_port = DEFAULT_PORT; /** * The serialVersionUID. */ static final long serialVersionUID = 887844277028676648L; // ------------------------------------------------------------- The scheme /** * Get the scheme. You can get the scheme explicitly. * * @return the scheme */ public char[] getRawScheme() { return (_scheme == null) ? null : HttpsURL.DEFAULT_SCHEME; } /** * Get the scheme. You can get the scheme explicitly. * * @return the scheme null if empty or undefined */ public String getScheme() { return (_scheme == null) ? null : new String(HttpsURL.DEFAULT_SCHEME); } // --------------------------------------------------------------- The port /** * Get the port number. * @return the port number */ public int getPort() { return (_port == -1) ? HttpsURL.DEFAULT_PORT : _port; } // ---------------------------------------------------------------- Utility /** * Verify the valid class use for construction. * * @throws URIException the wrong scheme use */ protected void checkValid() throws URIException { // could be explicit protocol or undefined. if (!(equals(_scheme, DEFAULT_SCHEME) || _scheme == null)) { throw new URIException(URIException.PARSING, "wrong class use"); } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/InvalidRedirectLocationException.java100644 0 0 5103 10661532626 31175 0ustar 0 0 /* * $HeadRL$ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * Signals violation of HTTP specification caused by an invalid redirect * location * * @author Oleg Kalnichevski * * @since 3.1 */ public class InvalidRedirectLocationException extends RedirectException { private final String location; /** * Creates a new InvalidRedirectLocationException with the specified detail message. * * @param message the exception detail message * @param location redirect location */ public InvalidRedirectLocationException(final String message, final String location) { super(message); this.location = location; } /** * Creates a new RedirectException with the specified detail message and cause. * * @param message the exception detail message * @param location redirect location * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public InvalidRedirectLocationException(final String message, final String location, final Throwable cause) { super(message, cause); this.location = location; } public String getLocation() { return this.location; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/MethodRetryHandler.java100644 0 0 5253 10661532626 26327 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/MethodRetryHandler.java,v 1.5 2004/07/05 22:46:58 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * A handler for determining if an HttpMethod should be retried after a * recoverable exception during execution. * * @see HttpMethod#execute(HttpState, HttpConnection) * @see HttpRecoverableException * * @deprecated use {@link HttpMethodRetryHandler} * * @author Michael Becke */ public interface MethodRetryHandler { /** * Determines if a method should be retried after an HttpRecoverableException * occurs during execution. * * @param method the method being executed * @param connection the connection the method is using * @param recoverableException the exception that occurred * @param executionCount the number of times this method has been * unsuccessfully executed * @param requestSent this argument is unused and will be removed in the future. * {@link HttpMethod#isRequestSent()} should be used instead * * @return true if the method should be retried, false * otherwise */ boolean retryMethod( HttpMethod method, HttpConnection connection, HttpRecoverableException recoverableException, int executionCount, boolean requestSent); } ././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.javacommons-httpclient-3.1/src/java/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.jav100644 0 0 167143 10661532627 31400 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.java,v 1.47 2004/12/21 11:27:55 olegk Exp $ * $Revision: 564906 $ * $Date: 2007-08-11 14:27:18 +0200 (Sat, 11 Aug 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.net.InetAddress; import java.net.SocketException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.WeakHashMap; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.util.IdleConnectionHandler; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Manages a set of HttpConnections for various HostConfigurations. * * @author Michael Becke * @author Eric Johnson * @author Mike Bowler * @author Carl A. Dunham * * @since 2.0 */ public class MultiThreadedHttpConnectionManager implements HttpConnectionManager { // -------------------------------------------------------- Class Variables /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(MultiThreadedHttpConnectionManager.class); /** The default maximum number of connections allowed per host */ public static final int DEFAULT_MAX_HOST_CONNECTIONS = 2; // Per RFC 2616 sec 8.1.4 /** The default maximum number of connections allowed overall */ public static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 20; /** * A mapping from Reference to ConnectionSource. Used to reclaim resources when connections * are lost to the garbage collector. */ private static final Map REFERENCE_TO_CONNECTION_SOURCE = new HashMap(); /** * The reference queue used to track when HttpConnections are lost to the * garbage collector */ private static final ReferenceQueue REFERENCE_QUEUE = new ReferenceQueue(); /** * The thread responsible for handling lost connections. */ private static ReferenceQueueThread REFERENCE_QUEUE_THREAD; /** * Holds references to all active instances of this class. */ private static WeakHashMap ALL_CONNECTION_MANAGERS = new WeakHashMap(); // ---------------------------------------------------------- Class Methods /** * Shuts down and cleans up resources used by all instances of * MultiThreadedHttpConnectionManager. All static resources are released, all threads are * stopped, and {@link #shutdown()} is called on all live instances of * MultiThreadedHttpConnectionManager. * * @see #shutdown() */ public static void shutdownAll() { synchronized (REFERENCE_TO_CONNECTION_SOURCE) { // shutdown all connection managers synchronized (ALL_CONNECTION_MANAGERS) { // Don't use an iterator here. Iterators on WeakHashMap can // get ConcurrentModificationException on garbage collection. MultiThreadedHttpConnectionManager[] connManagers = (MultiThreadedHttpConnectionManager[]) ALL_CONNECTION_MANAGERS.keySet().toArray( new MultiThreadedHttpConnectionManager [ALL_CONNECTION_MANAGERS.size()] ); // The map may shrink after size() is called, or some entry // may get GCed while the array is built, so expect null. for (int i=0; iA static reference to the connection manager will also be stored. To ensure that * the connection manager can be GCed {@link #removeReferenceToConnection(HttpConnection)} * should be called for all connections that the connection manager is storing a reference * to.

* * @param connection the connection to create a reference for * @param hostConfiguration the connection's host config * @param connectionPool the connection pool that created the connection * * @see #removeReferenceToConnection(HttpConnection) */ private static void storeReferenceToConnection( HttpConnectionWithReference connection, HostConfiguration hostConfiguration, ConnectionPool connectionPool ) { ConnectionSource source = new ConnectionSource(); source.connectionPool = connectionPool; source.hostConfiguration = hostConfiguration; synchronized (REFERENCE_TO_CONNECTION_SOURCE) { // start the reference queue thread if needed if (REFERENCE_QUEUE_THREAD == null) { REFERENCE_QUEUE_THREAD = new ReferenceQueueThread(); REFERENCE_QUEUE_THREAD.start(); } REFERENCE_TO_CONNECTION_SOURCE.put( connection.reference, source ); } } /** * Closes and releases all connections currently checked out of the given connection pool. * @param connectionPool the connection pool to shutdown the connections for */ private static void shutdownCheckedOutConnections(ConnectionPool connectionPool) { // keep a list of the connections to be closed ArrayList connectionsToClose = new ArrayList(); synchronized (REFERENCE_TO_CONNECTION_SOURCE) { Iterator referenceIter = REFERENCE_TO_CONNECTION_SOURCE.keySet().iterator(); while (referenceIter.hasNext()) { Reference ref = (Reference) referenceIter.next(); ConnectionSource source = (ConnectionSource) REFERENCE_TO_CONNECTION_SOURCE.get(ref); if (source.connectionPool == connectionPool) { referenceIter.remove(); HttpConnection connection = (HttpConnection) ref.get(); if (connection != null) { connectionsToClose.add(connection); } } } } // close and release the connections outside of the synchronized block to // avoid holding the lock for too long for (Iterator i = connectionsToClose.iterator(); i.hasNext();) { HttpConnection connection = (HttpConnection) i.next(); connection.close(); // remove the reference to the connection manager. this ensures // that the we don't accidentally end up here again connection.setHttpConnectionManager(null); connection.releaseConnection(); } } /** * Removes the reference being stored for the given connection. This method should be called * when the connection manager again has a direct reference to the connection. * * @param connection the connection to remove the reference for * * @see #storeReferenceToConnection(HttpConnection, HostConfiguration, ConnectionPool) */ private static void removeReferenceToConnection(HttpConnectionWithReference connection) { synchronized (REFERENCE_TO_CONNECTION_SOURCE) { REFERENCE_TO_CONNECTION_SOURCE.remove(connection.reference); } } // ----------------------------------------------------- Instance Variables /** * Collection of parameters associated with this connection manager. */ private HttpConnectionManagerParams params = new HttpConnectionManagerParams(); /** Connection Pool */ private ConnectionPool connectionPool; private volatile boolean shutdown = false; // ----------------------------------------------------------- Constructors /** * No-args constructor */ public MultiThreadedHttpConnectionManager() { this.connectionPool = new ConnectionPool(); synchronized(ALL_CONNECTION_MANAGERS) { ALL_CONNECTION_MANAGERS.put(this, null); } } // ------------------------------------------------------- Instance Methods /** * Shuts down the connection manager and releases all resources. All connections associated * with this class will be closed and released. * *

The connection manager can no longer be used once shut down. * *

Calling this method more than once will have no effect. */ public synchronized void shutdown() { synchronized (connectionPool) { if (!shutdown) { shutdown = true; connectionPool.shutdown(); } } } /** * Gets the staleCheckingEnabled value to be set on HttpConnections that are created. * * @return true if stale checking will be enabled on HttpConnections * * @see HttpConnection#isStaleCheckingEnabled() * * @deprecated Use {@link HttpConnectionManagerParams#isStaleCheckingEnabled()}, * {@link HttpConnectionManager#getParams()}. */ public boolean isConnectionStaleCheckingEnabled() { return this.params.isStaleCheckingEnabled(); } /** * Sets the staleCheckingEnabled value to be set on HttpConnections that are created. * * @param connectionStaleCheckingEnabled true if stale checking will be enabled * on HttpConnections * * @see HttpConnection#setStaleCheckingEnabled(boolean) * * @deprecated Use {@link HttpConnectionManagerParams#setStaleCheckingEnabled(boolean)}, * {@link HttpConnectionManager#getParams()}. */ public void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled) { this.params.setStaleCheckingEnabled(connectionStaleCheckingEnabled); } /** * Sets the maximum number of connections allowed for a given * HostConfiguration. Per RFC 2616 section 8.1.4, this value defaults to 2. * * @param maxHostConnections the number of connections allowed for each * hostConfiguration * * @deprecated Use {@link HttpConnectionManagerParams#setDefaultMaxConnectionsPerHost(int)}, * {@link HttpConnectionManager#getParams()}. */ public void setMaxConnectionsPerHost(int maxHostConnections) { this.params.setDefaultMaxConnectionsPerHost(maxHostConnections); } /** * Gets the maximum number of connections allowed for a given * hostConfiguration. * * @return The maximum number of connections allowed for a given * hostConfiguration. * * @deprecated Use {@link HttpConnectionManagerParams#getDefaultMaxConnectionsPerHost()}, * {@link HttpConnectionManager#getParams()}. */ public int getMaxConnectionsPerHost() { return this.params.getDefaultMaxConnectionsPerHost(); } /** * Sets the maximum number of connections allowed for this connection manager. * * @param maxTotalConnections the maximum number of connections allowed * * @deprecated Use {@link HttpConnectionManagerParams#setMaxTotalConnections(int)}, * {@link HttpConnectionManager#getParams()}. */ public void setMaxTotalConnections(int maxTotalConnections) { this.params.setMaxTotalConnections(maxTotalConnections); } /** * Gets the maximum number of connections allowed for this connection manager. * * @return The maximum number of connections allowed * * @deprecated Use {@link HttpConnectionManagerParams#getMaxTotalConnections()}, * {@link HttpConnectionManager#getParams()}. */ public int getMaxTotalConnections() { return this.params.getMaxTotalConnections(); } /** * @see HttpConnectionManager#getConnection(HostConfiguration) */ public HttpConnection getConnection(HostConfiguration hostConfiguration) { while (true) { try { return getConnectionWithTimeout(hostConfiguration, 0); } catch (ConnectionPoolTimeoutException e) { // we'll go ahead and log this, but it should never happen. HttpExceptions // are only thrown when the timeout occurs and since we have no timeout // it should never happen. LOG.debug( "Unexpected exception while waiting for connection", e ); } } } /** * Gets a connection or waits if one is not available. A connection is * available if one exists that is not being used or if fewer than * maxHostConnections have been created in the connectionPool, and fewer * than maxTotalConnections have been created in all connectionPools. * * @param hostConfiguration The host configuration specifying the connection * details. * @param timeout the number of milliseconds to wait for a connection, 0 to * wait indefinitely * * @return HttpConnection an available connection * * @throws HttpException if a connection does not become available in * 'timeout' milliseconds * * @since 3.0 */ public HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout) throws ConnectionPoolTimeoutException { LOG.trace("enter HttpConnectionManager.getConnectionWithTimeout(HostConfiguration, long)"); if (hostConfiguration == null) { throw new IllegalArgumentException("hostConfiguration is null"); } if (LOG.isDebugEnabled()) { LOG.debug("HttpConnectionManager.getConnection: config = " + hostConfiguration + ", timeout = " + timeout); } final HttpConnection conn = doGetConnection(hostConfiguration, timeout); // wrap the connection in an adapter so we can ensure it is used // only once return new HttpConnectionAdapter(conn); } /** * @see HttpConnectionManager#getConnection(HostConfiguration, long) * * @deprecated Use #getConnectionWithTimeout(HostConfiguration, long) */ public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout) throws HttpException { LOG.trace("enter HttpConnectionManager.getConnection(HostConfiguration, long)"); try { return getConnectionWithTimeout(hostConfiguration, timeout); } catch(ConnectionPoolTimeoutException e) { throw new HttpException(e.getMessage()); } } private HttpConnection doGetConnection(HostConfiguration hostConfiguration, long timeout) throws ConnectionPoolTimeoutException { HttpConnection connection = null; int maxHostConnections = this.params.getMaxConnectionsPerHost(hostConfiguration); int maxTotalConnections = this.params.getMaxTotalConnections(); synchronized (connectionPool) { // we clone the hostConfiguration // so that it cannot be changed once the connection has been retrieved hostConfiguration = new HostConfiguration(hostConfiguration); HostConnectionPool hostPool = connectionPool.getHostPool(hostConfiguration, true); WaitingThread waitingThread = null; boolean useTimeout = (timeout > 0); long timeToWait = timeout; long startWait = 0; long endWait = 0; while (connection == null) { if (shutdown) { throw new IllegalStateException("Connection factory has been shutdown."); } // happen to have a free connection with the right specs // if (hostPool.freeConnections.size() > 0) { connection = connectionPool.getFreeConnection(hostConfiguration); // have room to make more // } else if ((hostPool.numConnections < maxHostConnections) && (connectionPool.numConnections < maxTotalConnections)) { connection = connectionPool.createConnection(hostConfiguration); // have room to add host connection, and there is at least one free // connection that can be liberated to make overall room // } else if ((hostPool.numConnections < maxHostConnections) && (connectionPool.freeConnections.size() > 0)) { connectionPool.deleteLeastUsedConnection(); connection = connectionPool.createConnection(hostConfiguration); // otherwise, we have to wait for one of the above conditions to // become true // } else { // TODO: keep track of which hostConfigurations have waiting // threads, so they avoid being sacrificed before necessary try { if (useTimeout && timeToWait <= 0) { throw new ConnectionPoolTimeoutException("Timeout waiting for connection"); } if (LOG.isDebugEnabled()) { LOG.debug("Unable to get a connection, waiting..., hostConfig=" + hostConfiguration); } if (waitingThread == null) { waitingThread = new WaitingThread(); waitingThread.hostConnectionPool = hostPool; waitingThread.thread = Thread.currentThread(); } else { waitingThread.interruptedByConnectionPool = false; } if (useTimeout) { startWait = System.currentTimeMillis(); } hostPool.waitingThreads.addLast(waitingThread); connectionPool.waitingThreads.addLast(waitingThread); connectionPool.wait(timeToWait); } catch (InterruptedException e) { if (!waitingThread.interruptedByConnectionPool) { LOG.debug("Interrupted while waiting for connection", e); throw new IllegalThreadStateException( "Interrupted while waiting in MultiThreadedHttpConnectionManager"); } // Else, do nothing, we were interrupted by the connection pool // and should now have a connection waiting for us, continue // in the loop and let's get it. } finally { if (!waitingThread.interruptedByConnectionPool) { // Either we timed out, experienced a "spurious wakeup", or were // interrupted by an external thread. Regardless we need to // cleanup for ourselves in the wait queue. hostPool.waitingThreads.remove(waitingThread); connectionPool.waitingThreads.remove(waitingThread); } if (useTimeout) { endWait = System.currentTimeMillis(); timeToWait -= (endWait - startWait); } } } } } return connection; } /** * Gets the total number of pooled connections for the given host configuration. This * is the total number of connections that have been created and are still in use * by this connection manager for the host configuration. This value will * not exceed the {@link #getMaxConnectionsPerHost() maximum number of connections per * host}. * * @param hostConfiguration The host configuration * @return The total number of pooled connections */ public int getConnectionsInPool(HostConfiguration hostConfiguration) { synchronized (connectionPool) { HostConnectionPool hostPool = connectionPool.getHostPool(hostConfiguration, false); return (hostPool != null) ? hostPool.numConnections : 0; } } /** * Gets the total number of pooled connections. This is the total number of * connections that have been created and are still in use by this connection * manager. This value will not exceed the {@link #getMaxTotalConnections() * maximum number of connections}. * * @return the total number of pooled connections */ public int getConnectionsInPool() { synchronized (connectionPool) { return connectionPool.numConnections; } } /** * Gets the number of connections in use for this configuration. * * @param hostConfiguration the key that connections are tracked on * @return the number of connections in use * * @deprecated Use {@link #getConnectionsInPool(HostConfiguration)} */ public int getConnectionsInUse(HostConfiguration hostConfiguration) { return getConnectionsInPool(hostConfiguration); } /** * Gets the total number of connections in use. * * @return the total number of connections in use * * @deprecated Use {@link #getConnectionsInPool()} */ public int getConnectionsInUse() { return getConnectionsInPool(); } /** * Deletes all closed connections. Only connections currently owned by the connection * manager are processed. * * @see HttpConnection#isOpen() * * @since 3.0 */ public void deleteClosedConnections() { connectionPool.deleteClosedConnections(); } /** * @since 3.0 */ public void closeIdleConnections(long idleTimeout) { connectionPool.closeIdleConnections(idleTimeout); deleteClosedConnections(); } /** * Make the given HttpConnection available for use by other requests. * If another thread is blocked in getConnection() that could use this * connection, it will be woken up. * * @param conn the HttpConnection to make available. */ public void releaseConnection(HttpConnection conn) { LOG.trace("enter HttpConnectionManager.releaseConnection(HttpConnection)"); if (conn instanceof HttpConnectionAdapter) { // connections given out are wrapped in an HttpConnectionAdapter conn = ((HttpConnectionAdapter) conn).getWrappedConnection(); } else { // this is okay, when an HttpConnectionAdapter is released // is releases the real connection } // make sure that the response has been read. SimpleHttpConnectionManager.finishLastResponse(conn); connectionPool.freeConnection(conn); } /** * Gets the host configuration for a connection. * @param conn the connection to get the configuration of * @return a new HostConfiguration */ private HostConfiguration configurationForConnection(HttpConnection conn) { HostConfiguration connectionConfiguration = new HostConfiguration(); connectionConfiguration.setHost( conn.getHost(), conn.getPort(), conn.getProtocol() ); if (conn.getLocalAddress() != null) { connectionConfiguration.setLocalAddress(conn.getLocalAddress()); } if (conn.getProxyHost() != null) { connectionConfiguration.setProxy(conn.getProxyHost(), conn.getProxyPort()); } return connectionConfiguration; } /** * Returns {@link HttpConnectionManagerParams parameters} associated * with this connection manager. * * @since 3.0 * * @see HttpConnectionManagerParams */ public HttpConnectionManagerParams getParams() { return this.params; } /** * Assigns {@link HttpConnectionManagerParams parameters} for this * connection manager. * * @since 3.0 * * @see HttpConnectionManagerParams */ public void setParams(final HttpConnectionManagerParams params) { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } this.params = params; } /** * Global Connection Pool, including per-host pools */ private class ConnectionPool { /** The list of free connections */ private LinkedList freeConnections = new LinkedList(); /** The list of WaitingThreads waiting for a connection */ private LinkedList waitingThreads = new LinkedList(); /** * Map where keys are {@link HostConfiguration}s and values are {@link * HostConnectionPool}s */ private final Map mapHosts = new HashMap(); private IdleConnectionHandler idleConnectionHandler = new IdleConnectionHandler(); /** The number of created connections */ private int numConnections = 0; /** * Cleans up all connection pool resources. */ public synchronized void shutdown() { // close all free connections Iterator iter = freeConnections.iterator(); while (iter.hasNext()) { HttpConnection conn = (HttpConnection) iter.next(); iter.remove(); conn.close(); } // close all connections that have been checked out shutdownCheckedOutConnections(this); // interrupt all waiting threads iter = waitingThreads.iterator(); while (iter.hasNext()) { WaitingThread waiter = (WaitingThread) iter.next(); iter.remove(); waiter.interruptedByConnectionPool = true; waiter.thread.interrupt(); } // clear out map hosts mapHosts.clear(); // remove all references to connections idleConnectionHandler.removeAll(); } /** * Creates a new connection and returns it for use of the calling method. * * @param hostConfiguration the configuration for the connection * @return a new connection or null if none are available */ public synchronized HttpConnection createConnection(HostConfiguration hostConfiguration) { HostConnectionPool hostPool = getHostPool(hostConfiguration, true); if (LOG.isDebugEnabled()) { LOG.debug("Allocating new connection, hostConfig=" + hostConfiguration); } HttpConnectionWithReference connection = new HttpConnectionWithReference( hostConfiguration); connection.getParams().setDefaults(MultiThreadedHttpConnectionManager.this.params); connection.setHttpConnectionManager(MultiThreadedHttpConnectionManager.this); numConnections++; hostPool.numConnections++; // store a reference to this connection so that it can be cleaned up // in the event it is not correctly released storeReferenceToConnection(connection, hostConfiguration, this); return connection; } /** * Handles cleaning up for a lost connection with the given config. Decrements any * connection counts and notifies waiting threads, if appropriate. * * @param config the host configuration of the connection that was lost */ public synchronized void handleLostConnection(HostConfiguration config) { HostConnectionPool hostPool = getHostPool(config, true); hostPool.numConnections--; if ((hostPool.numConnections == 0) && hostPool.waitingThreads.isEmpty()) { mapHosts.remove(config); } numConnections--; notifyWaitingThread(config); } /** * Get the pool (list) of connections available for the given hostConfig. * * @param hostConfiguration the configuraton for the connection pool * @param create true to create a pool if not found, * false to return null * * @return a pool (list) of connections available for the given config, * or null if neither found nor created */ public synchronized HostConnectionPool getHostPool(HostConfiguration hostConfiguration, boolean create) { LOG.trace("enter HttpConnectionManager.ConnectionPool.getHostPool(HostConfiguration)"); // Look for a list of connections for the given config HostConnectionPool listConnections = (HostConnectionPool) mapHosts.get(hostConfiguration); if ((listConnections == null) && create) { // First time for this config listConnections = new HostConnectionPool(); listConnections.hostConfiguration = hostConfiguration; mapHosts.put(hostConfiguration, listConnections); } return listConnections; } /** * If available, get a free connection for this host * * @param hostConfiguration the configuraton for the connection pool * @return an available connection for the given config */ public synchronized HttpConnection getFreeConnection(HostConfiguration hostConfiguration) { HttpConnectionWithReference connection = null; HostConnectionPool hostPool = getHostPool(hostConfiguration, false); if ((hostPool != null) && (hostPool.freeConnections.size() > 0)) { connection = (HttpConnectionWithReference) hostPool.freeConnections.removeLast(); freeConnections.remove(connection); // store a reference to this connection so that it can be cleaned up // in the event it is not correctly released storeReferenceToConnection(connection, hostConfiguration, this); if (LOG.isDebugEnabled()) { LOG.debug("Getting free connection, hostConfig=" + hostConfiguration); } // remove the connection from the timeout handler idleConnectionHandler.remove(connection); } else if (LOG.isDebugEnabled()) { LOG.debug("There were no free connections to get, hostConfig=" + hostConfiguration); } return connection; } /** * Deletes all closed connections. */ public synchronized void deleteClosedConnections() { Iterator iter = freeConnections.iterator(); while (iter.hasNext()) { HttpConnection conn = (HttpConnection) iter.next(); if (!conn.isOpen()) { iter.remove(); deleteConnection(conn); } } } /** * Closes idle connections. * @param idleTimeout */ public synchronized void closeIdleConnections(long idleTimeout) { idleConnectionHandler.closeIdleConnections(idleTimeout); } /** * Deletes the given connection. This will remove all reference to the connection * so that it can be GCed. * *

Note: Does not remove the connection from the freeConnections list. It * is assumed that the caller has already handled this case.

* * @param connection The connection to delete */ private synchronized void deleteConnection(HttpConnection connection) { HostConfiguration connectionConfiguration = configurationForConnection(connection); if (LOG.isDebugEnabled()) { LOG.debug("Reclaiming connection, hostConfig=" + connectionConfiguration); } connection.close(); HostConnectionPool hostPool = getHostPool(connectionConfiguration, true); hostPool.freeConnections.remove(connection); hostPool.numConnections--; numConnections--; if ((hostPool.numConnections == 0) && hostPool.waitingThreads.isEmpty()) { mapHosts.remove(connectionConfiguration); } // remove the connection from the timeout handler idleConnectionHandler.remove(connection); } /** * Close and delete an old, unused connection to make room for a new one. */ public synchronized void deleteLeastUsedConnection() { HttpConnection connection = (HttpConnection) freeConnections.removeFirst(); if (connection != null) { deleteConnection(connection); } else if (LOG.isDebugEnabled()) { LOG.debug("Attempted to reclaim an unused connection but there were none."); } } /** * Notifies a waiting thread that a connection for the given configuration is * available. * @param configuration the host config to use for notifying * @see #notifyWaitingThread(HostConnectionPool) */ public synchronized void notifyWaitingThread(HostConfiguration configuration) { notifyWaitingThread(getHostPool(configuration, true)); } /** * Notifies a waiting thread that a connection for the given configuration is * available. This will wake a thread waiting in this host pool or if there is not * one a thread in the connection pool will be notified. * * @param hostPool the host pool to use for notifying */ public synchronized void notifyWaitingThread(HostConnectionPool hostPool) { // find the thread we are going to notify, we want to ensure that each // waiting thread is only interrupted once so we will remove it from // all wait queues before interrupting it WaitingThread waitingThread = null; if (hostPool.waitingThreads.size() > 0) { if (LOG.isDebugEnabled()) { LOG.debug("Notifying thread waiting on host pool, hostConfig=" + hostPool.hostConfiguration); } waitingThread = (WaitingThread) hostPool.waitingThreads.removeFirst(); waitingThreads.remove(waitingThread); } else if (waitingThreads.size() > 0) { if (LOG.isDebugEnabled()) { LOG.debug("No-one waiting on host pool, notifying next waiting thread."); } waitingThread = (WaitingThread) waitingThreads.removeFirst(); waitingThread.hostConnectionPool.waitingThreads.remove(waitingThread); } else if (LOG.isDebugEnabled()) { LOG.debug("Notifying no-one, there are no waiting threads"); } if (waitingThread != null) { waitingThread.interruptedByConnectionPool = true; waitingThread.thread.interrupt(); } } /** * Marks the given connection as free. * @param conn a connection that is no longer being used */ public void freeConnection(HttpConnection conn) { HostConfiguration connectionConfiguration = configurationForConnection(conn); if (LOG.isDebugEnabled()) { LOG.debug("Freeing connection, hostConfig=" + connectionConfiguration); } synchronized (this) { if (shutdown) { // the connection manager has been shutdown, release the connection's // resources and get out of here conn.close(); return; } HostConnectionPool hostPool = getHostPool(connectionConfiguration, true); // Put the connect back in the available list and notify a waiter hostPool.freeConnections.add(conn); if (hostPool.numConnections == 0) { // for some reason this connection pool didn't already exist LOG.error("Host connection pool not found, hostConfig=" + connectionConfiguration); hostPool.numConnections = 1; } freeConnections.add(conn); // we can remove the reference to this connection as we have control over // it again. this also ensures that the connection manager can be GCed removeReferenceToConnection((HttpConnectionWithReference) conn); if (numConnections == 0) { // for some reason this connection pool didn't already exist LOG.error("Host connection pool not found, hostConfig=" + connectionConfiguration); numConnections = 1; } // register the connection with the timeout handler idleConnectionHandler.add(conn); notifyWaitingThread(hostPool); } } } /** * A simple struct-like class to combine the objects needed to release a connection's * resources when claimed by the garbage collector. */ private static class ConnectionSource { /** The connection pool that created the connection */ public ConnectionPool connectionPool; /** The connection's host configuration */ public HostConfiguration hostConfiguration; } /** * A simple struct-like class to combine the connection list and the count * of created connections. */ private static class HostConnectionPool { /** The hostConfig this pool is for */ public HostConfiguration hostConfiguration; /** The list of free connections */ public LinkedList freeConnections = new LinkedList(); /** The list of WaitingThreads for this host */ public LinkedList waitingThreads = new LinkedList(); /** The number of created connections */ public int numConnections = 0; } /** * A simple struct-like class to combine the waiting thread and the connection * pool it is waiting on. */ private static class WaitingThread { /** The thread that is waiting for a connection */ public Thread thread; /** The connection pool the thread is waiting for */ public HostConnectionPool hostConnectionPool; /** Flag to indicate if the thread was interrupted by the ConnectionPool. Set * to true inside {@link ConnectionPool#notifyWaitingThread(HostConnectionPool)} * before the thread is interrupted. */ public boolean interruptedByConnectionPool = false; } /** * A thread for listening for HttpConnections reclaimed by the garbage * collector. */ private static class ReferenceQueueThread extends Thread { private volatile boolean shutdown = false; /** * Create an instance and make this a daemon thread. */ public ReferenceQueueThread() { setDaemon(true); setName("MultiThreadedHttpConnectionManager cleanup"); } public void shutdown() { this.shutdown = true; this.interrupt(); } /** * Handles cleaning up for the given connection reference. * * @param ref the reference to clean up */ private void handleReference(Reference ref) { ConnectionSource source = null; synchronized (REFERENCE_TO_CONNECTION_SOURCE) { source = (ConnectionSource) REFERENCE_TO_CONNECTION_SOURCE.remove(ref); } // only clean up for this reference if it is still associated with // a ConnectionSource if (source != null) { if (LOG.isDebugEnabled()) { LOG.debug( "Connection reclaimed by garbage collector, hostConfig=" + source.hostConfiguration); } source.connectionPool.handleLostConnection(source.hostConfiguration); } } /** * Start execution. */ public void run() { while (!shutdown) { try { // remove the next reference and process it Reference ref = REFERENCE_QUEUE.remove(); if (ref != null) { handleReference(ref); } } catch (InterruptedException e) { LOG.debug("ReferenceQueueThread interrupted", e); } } } } /** * A connection that keeps a reference to itself. */ private static class HttpConnectionWithReference extends HttpConnection { public WeakReference reference = new WeakReference(this, REFERENCE_QUEUE); /** * @param hostConfiguration */ public HttpConnectionWithReference(HostConfiguration hostConfiguration) { super(hostConfiguration); } } /** * An HttpConnection wrapper that ensures a connection cannot be used * once released. */ private static class HttpConnectionAdapter extends HttpConnection { // the wrapped connection private HttpConnection wrappedConnection; /** * Creates a new HttpConnectionAdapter. * @param connection the connection to be wrapped */ public HttpConnectionAdapter(HttpConnection connection) { super(connection.getHost(), connection.getPort(), connection.getProtocol()); this.wrappedConnection = connection; } /** * Tests if the wrapped connection is still available. * @return boolean */ protected boolean hasConnection() { return wrappedConnection != null; } /** * @return HttpConnection */ HttpConnection getWrappedConnection() { return wrappedConnection; } public void close() { if (hasConnection()) { wrappedConnection.close(); } else { // do nothing } } public InetAddress getLocalAddress() { if (hasConnection()) { return wrappedConnection.getLocalAddress(); } else { return null; } } /** * @deprecated */ public boolean isStaleCheckingEnabled() { if (hasConnection()) { return wrappedConnection.isStaleCheckingEnabled(); } else { return false; } } public void setLocalAddress(InetAddress localAddress) { if (hasConnection()) { wrappedConnection.setLocalAddress(localAddress); } else { throw new IllegalStateException("Connection has been released"); } } /** * @deprecated */ public void setStaleCheckingEnabled(boolean staleCheckEnabled) { if (hasConnection()) { wrappedConnection.setStaleCheckingEnabled(staleCheckEnabled); } else { throw new IllegalStateException("Connection has been released"); } } public String getHost() { if (hasConnection()) { return wrappedConnection.getHost(); } else { return null; } } public HttpConnectionManager getHttpConnectionManager() { if (hasConnection()) { return wrappedConnection.getHttpConnectionManager(); } else { return null; } } public InputStream getLastResponseInputStream() { if (hasConnection()) { return wrappedConnection.getLastResponseInputStream(); } else { return null; } } public int getPort() { if (hasConnection()) { return wrappedConnection.getPort(); } else { return -1; } } public Protocol getProtocol() { if (hasConnection()) { return wrappedConnection.getProtocol(); } else { return null; } } public String getProxyHost() { if (hasConnection()) { return wrappedConnection.getProxyHost(); } else { return null; } } public int getProxyPort() { if (hasConnection()) { return wrappedConnection.getProxyPort(); } else { return -1; } } public OutputStream getRequestOutputStream() throws IOException, IllegalStateException { if (hasConnection()) { return wrappedConnection.getRequestOutputStream(); } else { return null; } } public InputStream getResponseInputStream() throws IOException, IllegalStateException { if (hasConnection()) { return wrappedConnection.getResponseInputStream(); } else { return null; } } public boolean isOpen() { if (hasConnection()) { return wrappedConnection.isOpen(); } else { return false; } } public boolean closeIfStale() throws IOException { if (hasConnection()) { return wrappedConnection.closeIfStale(); } else { return false; } } public boolean isProxied() { if (hasConnection()) { return wrappedConnection.isProxied(); } else { return false; } } public boolean isResponseAvailable() throws IOException { if (hasConnection()) { return wrappedConnection.isResponseAvailable(); } else { return false; } } public boolean isResponseAvailable(int timeout) throws IOException { if (hasConnection()) { return wrappedConnection.isResponseAvailable(timeout); } else { return false; } } public boolean isSecure() { if (hasConnection()) { return wrappedConnection.isSecure(); } else { return false; } } public boolean isTransparent() { if (hasConnection()) { return wrappedConnection.isTransparent(); } else { return false; } } public void open() throws IOException { if (hasConnection()) { wrappedConnection.open(); } else { throw new IllegalStateException("Connection has been released"); } } /** * @deprecated */ public void print(String data) throws IOException, IllegalStateException { if (hasConnection()) { wrappedConnection.print(data); } else { throw new IllegalStateException("Connection has been released"); } } public void printLine() throws IOException, IllegalStateException { if (hasConnection()) { wrappedConnection.printLine(); } else { throw new IllegalStateException("Connection has been released"); } } /** * @deprecated */ public void printLine(String data) throws IOException, IllegalStateException { if (hasConnection()) { wrappedConnection.printLine(data); } else { throw new IllegalStateException("Connection has been released"); } } /** * @deprecated */ public String readLine() throws IOException, IllegalStateException { if (hasConnection()) { return wrappedConnection.readLine(); } else { throw new IllegalStateException("Connection has been released"); } } public String readLine(String charset) throws IOException, IllegalStateException { if (hasConnection()) { return wrappedConnection.readLine(charset); } else { throw new IllegalStateException("Connection has been released"); } } public void releaseConnection() { if (!isLocked() && hasConnection()) { HttpConnection wrappedConnection = this.wrappedConnection; this.wrappedConnection = null; wrappedConnection.releaseConnection(); } else { // do nothing } } /** * @deprecated */ public void setConnectionTimeout(int timeout) { if (hasConnection()) { wrappedConnection.setConnectionTimeout(timeout); } else { // do nothing } } public void setHost(String host) throws IllegalStateException { if (hasConnection()) { wrappedConnection.setHost(host); } else { // do nothing } } public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager) { if (hasConnection()) { wrappedConnection.setHttpConnectionManager(httpConnectionManager); } else { // do nothing } } public void setLastResponseInputStream(InputStream inStream) { if (hasConnection()) { wrappedConnection.setLastResponseInputStream(inStream); } else { // do nothing } } public void setPort(int port) throws IllegalStateException { if (hasConnection()) { wrappedConnection.setPort(port); } else { // do nothing } } public void setProtocol(Protocol protocol) { if (hasConnection()) { wrappedConnection.setProtocol(protocol); } else { // do nothing } } public void setProxyHost(String host) throws IllegalStateException { if (hasConnection()) { wrappedConnection.setProxyHost(host); } else { // do nothing } } public void setProxyPort(int port) throws IllegalStateException { if (hasConnection()) { wrappedConnection.setProxyPort(port); } else { // do nothing } } /** * @deprecated */ public void setSoTimeout(int timeout) throws SocketException, IllegalStateException { if (hasConnection()) { wrappedConnection.setSoTimeout(timeout); } else { // do nothing } } /** * @deprecated */ public void shutdownOutput() { if (hasConnection()) { wrappedConnection.shutdownOutput(); } else { // do nothing } } public void tunnelCreated() throws IllegalStateException, IOException { if (hasConnection()) { wrappedConnection.tunnelCreated(); } else { // do nothing } } public void write(byte[] data, int offset, int length) throws IOException, IllegalStateException { if (hasConnection()) { wrappedConnection.write(data, offset, length); } else { throw new IllegalStateException("Connection has been released"); } } public void write(byte[] data) throws IOException, IllegalStateException { if (hasConnection()) { wrappedConnection.write(data); } else { throw new IllegalStateException("Connection has been released"); } } public void writeLine() throws IOException, IllegalStateException { if (hasConnection()) { wrappedConnection.writeLine(); } else { throw new IllegalStateException("Connection has been released"); } } public void writeLine(byte[] data) throws IOException, IllegalStateException { if (hasConnection()) { wrappedConnection.writeLine(data); } else { throw new IllegalStateException("Connection has been released"); } } public void flushRequestOutputStream() throws IOException { if (hasConnection()) { wrappedConnection.flushRequestOutputStream(); } else { throw new IllegalStateException("Connection has been released"); } } /** * @deprecated */ public int getSoTimeout() throws SocketException { if (hasConnection()) { return wrappedConnection.getSoTimeout(); } else { throw new IllegalStateException("Connection has been released"); } } /** * @deprecated */ public String getVirtualHost() { if (hasConnection()) { return wrappedConnection.getVirtualHost(); } else { throw new IllegalStateException("Connection has been released"); } } /** * @deprecated */ public void setVirtualHost(String host) throws IllegalStateException { if (hasConnection()) { wrappedConnection.setVirtualHost(host); } else { throw new IllegalStateException("Connection has been released"); } } public int getSendBufferSize() throws SocketException { if (hasConnection()) { return wrappedConnection.getSendBufferSize(); } else { throw new IllegalStateException("Connection has been released"); } } /** * @deprecated */ public void setSendBufferSize(int sendBufferSize) throws SocketException { if (hasConnection()) { wrappedConnection.setSendBufferSize(sendBufferSize); } else { throw new IllegalStateException("Connection has been released"); } } public HttpConnectionParams getParams() { if (hasConnection()) { return wrappedConnection.getParams(); } else { throw new IllegalStateException("Connection has been released"); } } public void setParams(final HttpConnectionParams params) { if (hasConnection()) { wrappedConnection.setParams(params); } else { throw new IllegalStateException("Connection has been released"); } } /* (non-Javadoc) * @see org.apache.commons.httpclient.HttpConnection#print(java.lang.String, java.lang.String) */ public void print(String data, String charset) throws IOException, IllegalStateException { if (hasConnection()) { wrappedConnection.print(data, charset); } else { throw new IllegalStateException("Connection has been released"); } } /* (non-Javadoc) * @see org.apache.commons.httpclient.HttpConnection#printLine(java.lang.String, java.lang.String) */ public void printLine(String data, String charset) throws IOException, IllegalStateException { if (hasConnection()) { wrappedConnection.printLine(data, charset); } else { throw new IllegalStateException("Connection has been released"); } } /* (non-Javadoc) * @see org.apache.commons.httpclient.HttpConnection#setSocketTimeout(int) */ public void setSocketTimeout(int timeout) throws SocketException, IllegalStateException { if (hasConnection()) { wrappedConnection.setSocketTimeout(timeout); } else { throw new IllegalStateException("Connection has been released"); } } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/NTCredentials.java100644 0 0 14220 10661532626 25274 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/NTCredentials.java,v 1.10 2004/04/18 23:51:35 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.util.LangUtils; /** {@link Credentials} for use with the NTLM authentication scheme which requires additional * information. * * @author Adrian Sutton * @author Mike Bowler * * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * @since 2.0 */ public class NTCredentials extends UsernamePasswordCredentials { // ----------------------------------------------------- Instance Variables /** The Domain to authenticate with. */ private String domain; /** The host the authentication request is originating from. */ private String host; // ----------------------------------------------------------- Constructors /** * Default constructor. * * @deprecated Do not use. Null user name, domain & host no longer allowed */ public NTCredentials() { super(); } /** * Constructor. * @param userName The user name. This should not include the domain to authenticate with. * For example: "user" is correct whereas "DOMAIN\\user" is not. * @param password The password. * @param host The host the authentication request is originating from. Essentially, the * computer name for this machine. * @param domain The domain to authenticate within. */ public NTCredentials(String userName, String password, String host, String domain) { super(userName, password); if (domain == null) { throw new IllegalArgumentException("Domain may not be null"); } this.domain = domain; if (host == null) { throw new IllegalArgumentException("Host may not be null"); } this.host = host; } // ------------------------------------------------------- Instance Methods /** * Sets the domain to authenticate with. The domain may not be null. * * @param domain the NT domain to authenticate in. * * @see #getDomain() * * @deprecated Do not use. The NTCredentials objects should be immutable */ public void setDomain(String domain) { if (domain == null) { throw new IllegalArgumentException("Domain may not be null"); } this.domain = domain; } /** * Retrieves the name to authenticate with. * * @return String the domain these credentials are intended to authenticate with. * * @see #setDomain(String) * */ public String getDomain() { return domain; } /** * Sets the host name of the computer originating the request. The host name may * not be null. * * @param host the Host the user is logged into. * * @deprecated Do not use. The NTCredentials objects should be immutable */ public void setHost(String host) { if (host == null) { throw new IllegalArgumentException("Host may not be null"); } this.host = host; } /** * Retrieves the host name of the computer originating the request. * * @return String the host the user is logged into. */ public String getHost() { return this.host; } /** * Return a string representation of this object. * @return A string represenation of this object. */ public String toString() { final StringBuffer sbResult = new StringBuffer(super.toString()); sbResult.append("@"); sbResult.append(this.host); sbResult.append("."); sbResult.append(this.domain); return sbResult.toString(); } /** * Computes a hash code based on all the case-sensitive parts of the credentials object. * * @return The hash code for the credentials. */ public int hashCode() { int hash = super.hashCode(); hash = LangUtils.hashCode(hash, this.host); hash = LangUtils.hashCode(hash, this.domain); return hash; } /** * Performs a case-sensitive check to see if the components of the credentials * are the same. * * @param o The object to match. * * @return true if all of the credentials match. */ public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; if (super.equals(o) ) { if (o instanceof NTCredentials) { NTCredentials that = (NTCredentials) o; return LangUtils.equals(this.domain, that.domain) && LangUtils.equals(this.host, that.host); } } return false; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/NameValuePair.java100644 0 0 10224 10661532626 25266 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/NameValuePair.java,v 1.17 2004/04/18 23:51:35 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.Serializable; import org.apache.commons.httpclient.util.LangUtils; /** *

A simple class encapsulating a name/value pair.

* * @author B.C. Holmes * @author Sean C. Sullivan * @author Mike Bowler * * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * */ public class NameValuePair implements Serializable { // ----------------------------------------------------------- Constructors /** * Default constructor. * */ public NameValuePair() { this (null, null); } /** * Constructor. * @param name The name. * @param value The value. */ public NameValuePair(String name, String value) { this.name = name; this.value = value; } // ----------------------------------------------------- Instance Variables /** * Name. */ private String name = null; /** * Value. */ private String value = null; // ------------------------------------------------------------- Properties /** * Set the name. * * @param name The new name * @see #getName() */ public void setName(String name) { this.name = name; } /** * Return the name. * * @return String name The name * @see #setName(String) */ public String getName() { return name; } /** * Set the value. * * @param value The new value. */ public void setValue(String value) { this.value = value; } /** * Return the current value. * * @return String value The current value. */ public String getValue() { return value; } // --------------------------------------------------------- Public Methods /** * Get a String representation of this pair. * @return A string representation. */ public String toString() { return ("name=" + name + ", " + "value=" + value); } public boolean equals(final Object object) { if (object == null) return false; if (this == object) return true; if (object instanceof NameValuePair) { NameValuePair that = (NameValuePair) object; return LangUtils.equals(this.name, that.name) && LangUtils.equals(this.value, that.value); } else { return false; } } public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.name); hash = LangUtils.hashCode(hash, this.value); return hash; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/NoHttpResponseException.java100644 0 0 5442 10661532626 27375 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/NoHttpResponseException.java,v 1.1 2004/07/05 22:46:58 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import org.apache.commons.httpclient.util.ExceptionUtil; /** *

* Signals that the target server failed to respond with a valid HTTP response. *

* * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class NoHttpResponseException extends IOException { /** * Creates a new NoHttpResponseException with a null detail message. */ public NoHttpResponseException() { super(); } /** * Creates a new NoHttpResponseException with the specified detail message. * * @param message exception message */ public NoHttpResponseException(String message) { super(message); } /** * Creates a new NoHttpResponseException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable * * @since 3.0 */ public NoHttpResponseException(String message, Throwable cause) { super(message); // If we're running on JDK 1.4 or later, tell Throwable what the cause was ExceptionUtil.initCause(this, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/ProtocolException.java100644 0 0 5101 10661532626 26233 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ProtocolException.java,v 1.4 2004/05/13 04:03:25 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * Signals that an HTTP protocol violation has occurred. For example, HttpClient * detected a malformed status line or headers, a missing message body, etc. * * @author Laura Werner * * @since 3.0 */ public class ProtocolException extends HttpException { /** * Creates a new ProtocolException with a null detail message. */ public ProtocolException() { super(); } /** * Creates a new ProtocolException with the specified detail message. * * @param message The exception detail message */ public ProtocolException(String message) { super(message); } /** * Creates a new ProtocolException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public ProtocolException(String message, Throwable cause) { super(message, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/ProxyClient.java100644 0 0 24364 10661532626 25067 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ProxyClient.java,v 1.5 2004/12/20 11:39:04 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.net.Socket; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.params.HttpParams; /** * A client that provides {@link java.net.Socket sockets} for communicating through HTTP proxies * via the HTTP CONNECT method. This is primarily needed for non-HTTP protocols that wish to * communicate via an HTTP proxy. * * @author Oleg Kalnichevski * @author Michael Becke * * @since 3.0 * * @version $Revision: 480424 $ */ public class ProxyClient { // ----------------------------------------------------- Instance Variables /** * The {@link HttpState HTTP state} associated with this ProxyClient. */ private HttpState state = new HttpState(); /** * The {@link HttpClientParams collection of parameters} associated with this ProxyClient. */ private HttpClientParams params = null; /** * The {@link HostConfiguration host configuration} associated with * the ProxyClient */ private HostConfiguration hostConfiguration = new HostConfiguration(); /** * Creates an instance of ProxyClient using default {@link HttpClientParams parameter set}. * * @see HttpClientParams */ public ProxyClient() { this(new HttpClientParams()); } /** * Creates an instance of ProxyClient using the given * {@link HttpClientParams parameter set}. * * @param params The {@link HttpClientParams parameters} to use. * * @see HttpClientParams */ public ProxyClient(HttpClientParams params) { super(); if (params == null) { throw new IllegalArgumentException("Params may not be null"); } this.params = params; } // ------------------------------------------------------------- Properties /** * Returns {@link HttpState HTTP state} associated with the ProxyClient. * * @see #setState(HttpState) * @return the shared client state */ public synchronized HttpState getState() { return state; } /** * Assigns {@link HttpState HTTP state} for the ProxyClient. * * @see #getState() * @param state the new {@link HttpState HTTP state} for the client */ public synchronized void setState(HttpState state) { this.state = state; } /** * Returns the {@link HostConfiguration host configuration} associated with the * ProxyClient. * * @return {@link HostConfiguration host configuration} */ public synchronized HostConfiguration getHostConfiguration() { return hostConfiguration; } /** * Assigns the {@link HostConfiguration host configuration} to use with the * ProxyClient. * * @param hostConfiguration The {@link HostConfiguration host configuration} to set */ public synchronized void setHostConfiguration(HostConfiguration hostConfiguration) { this.hostConfiguration = hostConfiguration; } /** * Returns {@link HttpClientParams HTTP protocol parameters} associated with this ProxyClient. * * @see HttpClientParams */ public synchronized HttpClientParams getParams() { return this.params; } /** * Assigns {@link HttpClientParams HTTP protocol parameters} for this ProxyClient. * * @see HttpClientParams */ public synchronized void setParams(final HttpClientParams params) { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } this.params = params; } /** * Creates a socket that is connected, via the HTTP CONNECT method, to a proxy. * *

* Even though HTTP CONNECT proxying is generally used for HTTPS tunneling, the returned * socket will not have been wrapped in an SSL socket. *

* *

* Both the proxy and destination hosts must be set via the * {@link #getHostConfiguration() host configuration} prior to calling this method. *

* * @return the connect response * * @throws IOException * @throws HttpException * * @see #getHostConfiguration() */ public ConnectResponse connect() throws IOException, HttpException { HostConfiguration hostconf = getHostConfiguration(); if (hostconf.getProxyHost() == null) { throw new IllegalStateException("proxy host must be configured"); } if (hostconf.getHost() == null) { throw new IllegalStateException("destination host must be configured"); } if (hostconf.getProtocol().isSecure()) { throw new IllegalStateException("secure protocol socket factory may not be used"); } ConnectMethod method = new ConnectMethod(getHostConfiguration()); method.getParams().setDefaults(getParams()); DummyConnectionManager connectionManager = new DummyConnectionManager(); connectionManager.setConnectionParams(getParams()); HttpMethodDirector director = new HttpMethodDirector( connectionManager, hostconf, getParams(), getState() ); director.executeMethod(method); ConnectResponse response = new ConnectResponse(); response.setConnectMethod(method); // only set the socket if the connect was successful if (method.getStatusCode() == HttpStatus.SC_OK) { response.setSocket(connectionManager.getConnection().getSocket()); } else { connectionManager.getConnection().close(); } return response; } /** * Contains the method used to execute the connect along with the created socket. */ public static class ConnectResponse { private ConnectMethod connectMethod; private Socket socket; private ConnectResponse() {} /** * Gets the method that was used to execute the connect. This method is useful for * analyzing the proxy's response when a connect fails. * * @return the connectMethod. */ public ConnectMethod getConnectMethod() { return connectMethod; } /** * @param connectMethod The connectMethod to set. */ private void setConnectMethod(ConnectMethod connectMethod) { this.connectMethod = connectMethod; } /** * Gets the socket connected and authenticated (if appropriate) to the configured * HTTP proxy, or null if a connection could not be made. It is the * responsibility of the user to close this socket when it is no longer needed. * * @return the socket. */ public Socket getSocket() { return socket; } /** * @param socket The socket to set. */ private void setSocket(Socket socket) { this.socket = socket; } } /** * A connection manager that creates a single connection. Meant to be used only once. */ static class DummyConnectionManager implements HttpConnectionManager { private HttpConnection httpConnection; private HttpParams connectionParams; public void closeIdleConnections(long idleTimeout) { } public HttpConnection getConnection() { return httpConnection; } public void setConnectionParams(HttpParams httpParams) { this.connectionParams = httpParams; } public HttpConnection getConnectionWithTimeout( HostConfiguration hostConfiguration, long timeout) { httpConnection = new HttpConnection(hostConfiguration); httpConnection.setHttpConnectionManager(this); httpConnection.getParams().setDefaults(connectionParams); return httpConnection; } /** * @deprecated */ public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout) throws HttpException { return getConnectionWithTimeout(hostConfiguration, timeout); } public HttpConnection getConnection(HostConfiguration hostConfiguration) { return getConnectionWithTimeout(hostConfiguration, -1); } public void releaseConnection(HttpConnection conn) { } public HttpConnectionManagerParams getParams() { return null; } public void setParams(HttpConnectionManagerParams params) { } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/ProxyHost.java100644 0 0 5771 10661532627 24550 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ProxyHost.java,v 1.2 2005/01/14 21:16:40 olegk Exp $ * $Revision: 510587 $ * $Date: 2007-02-22 17:56:08 +0100 (Thu, 22 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.protocol.Protocol; /** * Holds all of the variables needed to describe an HTTP connection to a proxy. Proxy hosts * always use plain HTTP connection when communicating with clients. * * @author Michael Becke * @author Mike Bowler * @author Oleg Kalnichevski * @author Laura Werner * * @since 3.0 */ public class ProxyHost extends HttpHost { /** * Copy constructor for HttpHost * * @param httpproxy the HTTP host to copy details from */ public ProxyHost (final ProxyHost httpproxy) { super(httpproxy); } /** * Constructor for ProxyHost. * * @param hostname the hostname (IP or DNS name). Can be null. * @param port the port. Value -1 can be used to set default protocol port */ public ProxyHost(final String hostname, int port) { super(hostname, port, Protocol.getProtocol("http")); } /** * Constructor for HttpHost. * * @param hostname the hostname (IP or DNS name). Can be null. */ public ProxyHost(final String hostname) { this(hostname, -1); } /** * @throws CloneNotSupportedException * @see java.lang.Object#clone() */ public Object clone() throws CloneNotSupportedException { ProxyHost copy = (ProxyHost) super.clone(); return copy; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/RedirectException.java100644 0 0 4760 10661532627 26206 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/RedirectException.java,v 1.2 2004/04/18 23:51:35 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * Signals violation of HTTP specification caused by an invalid redirect * * @author Oleg Kalnichevski * * @since 3.0 */ public class RedirectException extends ProtocolException { /** * Creates a new RedirectException with a null detail message. */ public RedirectException() { super(); } /** * Creates a new RedirectException with the specified detail message. * * @param message The exception detail message */ public RedirectException(String message) { super(message); } /** * Creates a new RedirectException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public RedirectException(String message, Throwable cause) { super(message, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/ResponseConsumedWatcher.java100644 0 0 4255 10661532626 27376 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ResponseConsumedWatcher.java,v 1.5 2004/04/18 23:51:35 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * When a response stream has been consumed, various parts of the HttpClient * implementation need to respond appropriately. * *

When one of the three types of {@link java.io.InputStream}, one of * AutoCloseInputStream (package), {@link ContentLengthInputStream}, or * {@link ChunkedInputStream} finishes with its content, either because * all content has been consumed, or because it was explicitly closed, * it notifies its corresponding method via this interface.

* * @see ContentLengthInputStream * @see ChunkedInputStream * @author Eric Johnson */ interface ResponseConsumedWatcher { /** * A response has been consumed. */ void responseConsumed(); } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/SimpleHttpConnectionManager.java100644 0 0 23717 10661532627 30215 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/SimpleHttpConnectionManager.java,v 1.23 2004/10/16 22:40:08 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A connection manager that provides access to a single HttpConnection. This * manager makes no attempt to provide exclusive access to the contained * HttpConnection. * * @author Michael Becke * @author Eric Johnson * @author Mike Bowler * @author Oleg Kalnichevski * @author Laura Werner * * @since 2.0 */ public class SimpleHttpConnectionManager implements HttpConnectionManager { private static final Log LOG = LogFactory.getLog(SimpleHttpConnectionManager.class); private static final String MISUSE_MESSAGE = "SimpleHttpConnectionManager being used incorrectly. Be sure that" + " HttpMethod.releaseConnection() is always called and that only one thread" + " and/or method is using this connection manager at a time."; /** * Since the same connection is about to be reused, make sure the * previous request was completely processed, and if not * consume it now. * @param conn The connection */ static void finishLastResponse(HttpConnection conn) { InputStream lastResponse = conn.getLastResponseInputStream(); if (lastResponse != null) { conn.setLastResponseInputStream(null); try { lastResponse.close(); } catch (IOException ioe) { conn.close(); } } } /** The http connection */ protected HttpConnection httpConnection; /** * Collection of parameters associated with this connection manager. */ private HttpConnectionManagerParams params = new HttpConnectionManagerParams(); /** * The time the connection was made idle. */ private long idleStartTime = Long.MAX_VALUE; /** * Used to test if {@link #httpConnection} is currently in use * (i.e. checked out). This is only used as a sanity check to help * debug cases where this connection manager is being used incorrectly. * It will not be used to enforce thread safety. */ private volatile boolean inUse = false; private boolean alwaysClose = false; /** * The connection manager created with this constructor will try to keep the * connection open (alive) between consecutive requests if the alwaysClose * parameter is set to false. Otherwise the connection manager will * always close connections upon release. * * @param alwaysClose if set true, the connection manager will always * close connections upon release. */ public SimpleHttpConnectionManager(boolean alwaysClose) { super(); this.alwaysClose = alwaysClose; } /** * The connection manager created with this constructor will always try to keep * the connection open (alive) between consecutive requests. */ public SimpleHttpConnectionManager() { super(); } /** * @see HttpConnectionManager#getConnection(HostConfiguration) */ public HttpConnection getConnection(HostConfiguration hostConfiguration) { return getConnection(hostConfiguration, 0); } /** * Gets the staleCheckingEnabled value to be set on HttpConnections that are created. * * @return true if stale checking will be enabled on HttpConections * * @see HttpConnection#isStaleCheckingEnabled() * * @deprecated Use {@link HttpConnectionManagerParams#isStaleCheckingEnabled()}, * {@link HttpConnectionManager#getParams()}. */ public boolean isConnectionStaleCheckingEnabled() { return this.params.isStaleCheckingEnabled(); } /** * Sets the staleCheckingEnabled value to be set on HttpConnections that are created. * * @param connectionStaleCheckingEnabled true if stale checking will be enabled * on HttpConections * * @see HttpConnection#setStaleCheckingEnabled(boolean) * * @deprecated Use {@link HttpConnectionManagerParams#setStaleCheckingEnabled(boolean)}, * {@link HttpConnectionManager#getParams()}. */ public void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled) { this.params.setStaleCheckingEnabled(connectionStaleCheckingEnabled); } /** * This method always returns the same connection object. If the connection is already * open, it will be closed and the new host configuration will be applied. * * @param hostConfiguration The host configuration specifying the connection * details. * @param timeout this parameter has no effect. The connection is always returned * immediately. * @since 3.0 */ public HttpConnection getConnectionWithTimeout( HostConfiguration hostConfiguration, long timeout) { if (httpConnection == null) { httpConnection = new HttpConnection(hostConfiguration); httpConnection.setHttpConnectionManager(this); httpConnection.getParams().setDefaults(this.params); } else { // make sure the host and proxy are correct for this connection // close it and set the values if they are not if (!hostConfiguration.hostEquals(httpConnection) || !hostConfiguration.proxyEquals(httpConnection)) { if (httpConnection.isOpen()) { httpConnection.close(); } httpConnection.setHost(hostConfiguration.getHost()); httpConnection.setPort(hostConfiguration.getPort()); httpConnection.setProtocol(hostConfiguration.getProtocol()); httpConnection.setLocalAddress(hostConfiguration.getLocalAddress()); httpConnection.setProxyHost(hostConfiguration.getProxyHost()); httpConnection.setProxyPort(hostConfiguration.getProxyPort()); } else { finishLastResponse(httpConnection); } } // remove the connection from the timeout handler idleStartTime = Long.MAX_VALUE; if (inUse) LOG.warn(MISUSE_MESSAGE); inUse = true; return httpConnection; } /** * @see HttpConnectionManager#getConnection(HostConfiguration, long) * * @deprecated Use #getConnectionWithTimeout(HostConfiguration, long) */ public HttpConnection getConnection( HostConfiguration hostConfiguration, long timeout) { return getConnectionWithTimeout(hostConfiguration, timeout); } /** * @see HttpConnectionManager#releaseConnection(org.apache.commons.httpclient.HttpConnection) */ public void releaseConnection(HttpConnection conn) { if (conn != httpConnection) { throw new IllegalStateException("Unexpected release of an unknown connection."); } if (this.alwaysClose) { httpConnection.close(); } else { // make sure the connection is reuseable finishLastResponse(httpConnection); } inUse = false; // track the time the connection was made idle idleStartTime = System.currentTimeMillis(); } /** * Returns {@link HttpConnectionManagerParams parameters} associated * with this connection manager. * * @since 2.1 * * @see HttpConnectionManagerParams */ public HttpConnectionManagerParams getParams() { return this.params; } /** * Assigns {@link HttpConnectionManagerParams parameters} for this * connection manager. * * @since 2.1 * * @see HttpConnectionManagerParams */ public void setParams(final HttpConnectionManagerParams params) { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } this.params = params; } /** * @since 3.0 */ public void closeIdleConnections(long idleTimeout) { long maxIdleTime = System.currentTimeMillis() - idleTimeout; if (idleStartTime <= maxIdleTime) { httpConnection.close(); } } /** * since 3.1 */ public void shutdown() { httpConnection.close(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/StatusLine.java100644 0 0 14104 10661532626 24671 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/StatusLine.java,v 1.14 2004/07/19 20:24:21 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * Represents a Status-Line as returned from a HTTP server. * * RFC2616 states * the following regarding the Status-Line: *
 * 6.1 Status-Line
 *
 *  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
 * 
*

* This class is immutable and is inherently thread safe. * * @see HttpStatus * @author Jeff Dever * @author Mike Bowler * @version $Id: StatusLine.java 480424 2006-11-29 05:56:49Z bayard $ * @since 2.0 */ public class StatusLine { // ----------------------------------------------------- Instance Variables /** The original Status-Line. */ private final String statusLine; /** The HTTP-Version. */ private final String httpVersion; /** The Status-Code. */ private final int statusCode; /** The Reason-Phrase. */ private final String reasonPhrase; // ----------------------------------------------------------- Constructors /** * Default constructor. * * @param statusLine the status line returned from the HTTP server * @throws HttpException if the status line is invalid */ public StatusLine(final String statusLine) throws HttpException { int length = statusLine.length(); int at = 0; int start = 0; try { while (Character.isWhitespace(statusLine.charAt(at))) { ++at; ++start; } if (!"HTTP".equals(statusLine.substring(at, at += 4))) { throw new HttpException("Status-Line '" + statusLine + "' does not start with HTTP"); } //handle the HTTP-Version at = statusLine.indexOf(" ", at); if (at <= 0) { throw new ProtocolException( "Unable to parse HTTP-Version from the status line: '" + statusLine + "'"); } this.httpVersion = (statusLine.substring(start, at)).toUpperCase(); //advance through spaces while (statusLine.charAt(at) == ' ') { at++; } //handle the Status-Code int to = statusLine.indexOf(" ", at); if (to < 0) { to = length; } try { this.statusCode = Integer.parseInt(statusLine.substring(at, to)); } catch (NumberFormatException e) { throw new ProtocolException( "Unable to parse status code from status line: '" + statusLine + "'"); } //handle the Reason-Phrase at = to + 1; if (at < length) { this.reasonPhrase = statusLine.substring(at).trim(); } else { this.reasonPhrase = ""; } } catch (StringIndexOutOfBoundsException e) { throw new HttpException("Status-Line '" + statusLine + "' is not valid"); } //save the original Status-Line this.statusLine = statusLine; } // --------------------------------------------------------- Public Methods /** * @return the Status-Code */ public final int getStatusCode() { return statusCode; } /** * @return the HTTP-Version */ public final String getHttpVersion() { return httpVersion; } /** * @return the Reason-Phrase */ public final String getReasonPhrase() { return reasonPhrase; } /** * Return a string representation of this object. * @return a string represenation of this object. */ public final String toString() { return statusLine; } /** * Tests if the string starts with 'HTTP' signature. * @param s string to test * @return true if the line starts with 'HTTP' * signature, false otherwise. */ public static boolean startsWithHTTP(final String s) { try { int at = 0; while (Character.isWhitespace(s.charAt(at))) { ++at; } return ("HTTP".equals(s.substring(at, at + 4))); } catch (StringIndexOutOfBoundsException e) { return false; } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/URI.java100644 0 0 364632 10661532626 23273 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/URI.java $ * $Revision: 564973 $ * $Date: 2007-08-11 22:51:47 +0200 (Sat, 11 Aug 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.Locale; import java.util.BitSet; import java.util.Hashtable; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.net.URLCodec; import org.apache.commons.httpclient.util.EncodingUtil; /** * The interface for the URI(Uniform Resource Identifiers) version of RFC 2396. * This class has the purpose of supportting of parsing a URI reference to * extend any specific protocols, the character encoding of the protocol to * be transported and the charset of the document. *

* A URI is always in an "escaped" form, since escaping or unescaping a * completed URI might change its semantics. *

* Implementers should be careful not to escape or unescape the same string * more than once, since unescaping an already unescaped string might lead to * misinterpreting a percent data character as another escaped character, * or vice versa in the case of escaping an already escaped string. *

* In order to avoid these problems, data types used as follows: *

 *   URI character sequence: char
 *   octet sequence: byte
 *   original character sequence: String
 * 

* * So, a URI is a sequence of characters as an array of a char type, which * is not always represented as a sequence of octets as an array of byte. *

* * URI Syntactic Components *

 * - In general, written as follows:
 *   Absolute URI = <scheme>:<scheme-specific-part>
 *   Generic URI = <scheme>://<authority><path>?<query>
 *
 * - Syntax
 *   absoluteURI   = scheme ":" ( hier_part | opaque_part )
 *   hier_part     = ( net_path | abs_path ) [ "?" query ]
 *   net_path      = "//" authority [ abs_path ]
 *   abs_path      = "/"  path_segments
 * 

* * The following examples illustrate URI that are in common use. *

 * ftp://ftp.is.co.za/rfc/rfc1808.txt
 *    -- ftp scheme for File Transfer Protocol services
 * gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles
 *    -- gopher scheme for Gopher and Gopher+ Protocol services
 * http://www.math.uio.no/faq/compression-faq/part1.html
 *    -- http scheme for Hypertext Transfer Protocol services
 * mailto:mduerst@ifi.unizh.ch
 *    -- mailto scheme for electronic mail addresses
 * news:comp.infosystems.www.servers.unix
 *    -- news scheme for USENET news groups and articles
 * telnet://melvyl.ucop.edu/
 *    -- telnet scheme for interactive services via the TELNET Protocol
 * 
* Please, notice that there are many modifications from URL(RFC 1738) and * relative URL(RFC 1808). *

* The expressions for a URI *

 * For escaped URI forms
 *  - URI(char[]) // constructor
 *  - char[] getRawXxx() // method
 *  - String getEscapedXxx() // method
 *  - String toString() // method
 * 

* For unescaped URI forms * - URI(String) // constructor * - String getXXX() // method *

* * @author Sung-Gu * @author Mike Bowler * @version $Revision: 564973 $ $Date: 2002/03/14 15:14:01 */ public class URI implements Cloneable, Comparable, Serializable { // ----------------------------------------------------------- Constructors /** Create an instance as an internal use */ protected URI() { } /** * Construct a URI from a string with the given charset. The input string can * be either in escaped or unescaped form. * * @param s URI character sequence * @param escaped true if URI character sequence is in escaped form. * false otherwise. * @param charset the charset string to do escape encoding, if required * * @throws URIException If the URI cannot be created. * @throws NullPointerException if input string is null * * @see #getProtocolCharset * * @since 3.0 */ public URI(String s, boolean escaped, String charset) throws URIException, NullPointerException { protocolCharset = charset; parseUriReference(s, escaped); } /** * Construct a URI from a string with the given charset. The input string can * be either in escaped or unescaped form. * * @param s URI character sequence * @param escaped true if URI character sequence is in escaped form. * false otherwise. * * @throws URIException If the URI cannot be created. * @throws NullPointerException if input string is null * * @see #getProtocolCharset * * @since 3.0 */ public URI(String s, boolean escaped) throws URIException, NullPointerException { parseUriReference(s, escaped); } /** * Construct a URI as an escaped form of a character array with the given * charset. * * @param escaped the URI character sequence * @param charset the charset string to do escape encoding * @throws URIException If the URI cannot be created. * @throws NullPointerException if escaped is null * @see #getProtocolCharset * * @deprecated Use #URI(String, boolean, String) */ public URI(char[] escaped, String charset) throws URIException, NullPointerException { protocolCharset = charset; parseUriReference(new String(escaped), true); } /** * Construct a URI as an escaped form of a character array. * An URI can be placed within double-quotes or angle brackets like * "http://test.com/" and <http://test.com/> * * @param escaped the URI character sequence * @throws URIException If the URI cannot be created. * @throws NullPointerException if escaped is null * @see #getDefaultProtocolCharset * * @deprecated Use #URI(String, boolean) */ public URI(char[] escaped) throws URIException, NullPointerException { parseUriReference(new String(escaped), true); } /** * Construct a URI from the given string with the given charset. * * @param original the string to be represented to URI character sequence * It is one of absoluteURI and relativeURI. * @param charset the charset string to do escape encoding * @throws URIException If the URI cannot be created. * @see #getProtocolCharset * * @deprecated Use #URI(String, boolean, String) */ public URI(String original, String charset) throws URIException { protocolCharset = charset; parseUriReference(original, false); } /** * Construct a URI from the given string. *

     *   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
     * 

* An URI can be placed within double-quotes or angle brackets like * "http://test.com/" and <http://test.com/> * * @param original the string to be represented to URI character sequence * It is one of absoluteURI and relativeURI. * @throws URIException If the URI cannot be created. * @see #getDefaultProtocolCharset * * @deprecated Use #URI(String, boolean) */ public URI(String original) throws URIException { parseUriReference(original, false); } /** * Construct a general URI from the given components. *

     *   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
     *   absoluteURI   = scheme ":" ( hier_part | opaque_part )
     *   opaque_part   = uric_no_slash *uric
     * 

* It's for absolute URI = <scheme>:<scheme-specific-part># * <fragment>. * * @param scheme the scheme string * @param schemeSpecificPart scheme_specific_part * @param fragment the fragment string * @throws URIException If the URI cannot be created. * @see #getDefaultProtocolCharset */ public URI(String scheme, String schemeSpecificPart, String fragment) throws URIException { // validate and contruct the URI character sequence if (scheme == null) { throw new URIException(URIException.PARSING, "scheme required"); } char[] s = scheme.toLowerCase().toCharArray(); if (validate(s, URI.scheme)) { _scheme = s; // is_absoluteURI } else { throw new URIException(URIException.PARSING, "incorrect scheme"); } _opaque = encode(schemeSpecificPart, allowed_opaque_part, getProtocolCharset()); // Set flag _is_opaque_part = true; _fragment = fragment == null ? null : fragment.toCharArray(); setURI(); } /** * Construct a general URI from the given components. *

     *   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
     *   absoluteURI   = scheme ":" ( hier_part | opaque_part )
     *   relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
     *   hier_part     = ( net_path | abs_path ) [ "?" query ]
     * 

* It's for absolute URI = <scheme>:<path>?<query>#< * fragment> and relative URI = <path>?<query>#<fragment * >. * * @param scheme the scheme string * @param authority the authority string * @param path the path string * @param query the query string * @param fragment the fragment string * @throws URIException If the new URI cannot be created. * @see #getDefaultProtocolCharset */ public URI(String scheme, String authority, String path, String query, String fragment) throws URIException { // validate and contruct the URI character sequence StringBuffer buff = new StringBuffer(); if (scheme != null) { buff.append(scheme); buff.append(':'); } if (authority != null) { buff.append("//"); buff.append(authority); } if (path != null) { // accept empty path if ((scheme != null || authority != null) && !path.startsWith("/")) { throw new URIException(URIException.PARSING, "abs_path requested"); } buff.append(path); } if (query != null) { buff.append('?'); buff.append(query); } if (fragment != null) { buff.append('#'); buff.append(fragment); } parseUriReference(buff.toString(), false); } /** * Construct a general URI from the given components. * * @param scheme the scheme string * @param userinfo the userinfo string * @param host the host string * @param port the port number * @throws URIException If the new URI cannot be created. * @see #getDefaultProtocolCharset */ public URI(String scheme, String userinfo, String host, int port) throws URIException { this(scheme, userinfo, host, port, null, null, null); } /** * Construct a general URI from the given components. * * @param scheme the scheme string * @param userinfo the userinfo string * @param host the host string * @param port the port number * @param path the path string * @throws URIException If the new URI cannot be created. * @see #getDefaultProtocolCharset */ public URI(String scheme, String userinfo, String host, int port, String path) throws URIException { this(scheme, userinfo, host, port, path, null, null); } /** * Construct a general URI from the given components. * * @param scheme the scheme string * @param userinfo the userinfo string * @param host the host string * @param port the port number * @param path the path string * @param query the query string * @throws URIException If the new URI cannot be created. * @see #getDefaultProtocolCharset */ public URI(String scheme, String userinfo, String host, int port, String path, String query) throws URIException { this(scheme, userinfo, host, port, path, query, null); } /** * Construct a general URI from the given components. * * @param scheme the scheme string * @param userinfo the userinfo string * @param host the host string * @param port the port number * @param path the path string * @param query the query string * @param fragment the fragment string * @throws URIException If the new URI cannot be created. * @see #getDefaultProtocolCharset */ public URI(String scheme, String userinfo, String host, int port, String path, String query, String fragment) throws URIException { this(scheme, (host == null) ? null : ((userinfo != null) ? userinfo + '@' : "") + host + ((port != -1) ? ":" + port : ""), path, query, fragment); } /** * Construct a general URI from the given components. * * @param scheme the scheme string * @param host the host string * @param path the path string * @param fragment the fragment string * @throws URIException If the new URI cannot be created. * @see #getDefaultProtocolCharset */ public URI(String scheme, String host, String path, String fragment) throws URIException { this(scheme, host, path, null, fragment); } /** * Construct a general URI with the given relative URI string. * * @param base the base URI * @param relative the relative URI string * @throws URIException If the new URI cannot be created. * * @deprecated Use #URI(URI, String, boolean) */ public URI(URI base, String relative) throws URIException { this(base, new URI(relative)); } /** * Construct a general URI with the given relative URI string. * * @param base the base URI * @param relative the relative URI string * @param escaped true if URI character sequence is in escaped form. * false otherwise. * * @throws URIException If the new URI cannot be created. * * @since 3.0 */ public URI(URI base, String relative, boolean escaped) throws URIException { this(base, new URI(relative, escaped)); } /** * Construct a general URI with the given relative URI. *

     *   URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
     *   relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
     * 

* Resolving Relative References to Absolute Form. * * Examples of Resolving Relative URI References * * Within an object with a well-defined base URI of *

     *   http://a/b/c/d;p?q
     * 

* the relative URI would be resolved as follows: * * Normal Examples * *

     *   g:h           =  g:h
     *   g             =  http://a/b/c/g
     *   ./g           =  http://a/b/c/g
     *   g/            =  http://a/b/c/g/
     *   /g            =  http://a/g
     *   //g           =  http://g
     *   ?y            =  http://a/b/c/?y
     *   g?y           =  http://a/b/c/g?y
     *   #s            =  (current document)#s
     *   g#s           =  http://a/b/c/g#s
     *   g?y#s         =  http://a/b/c/g?y#s
     *   ;x            =  http://a/b/c/;x
     *   g;x           =  http://a/b/c/g;x
     *   g;x?y#s       =  http://a/b/c/g;x?y#s
     *   .             =  http://a/b/c/
     *   ./            =  http://a/b/c/
     *   ..            =  http://a/b/
     *   ../           =  http://a/b/
     *   ../g          =  http://a/b/g
     *   ../..         =  http://a/
     *   ../../        =  http://a/ 
     *   ../../g       =  http://a/g
     * 

* * Some URI schemes do not allow a hierarchical syntax matching the * syntax, and thus cannot use relative references. * * @param base the base URI * @param relative the relative URI * @throws URIException If the new URI cannot be created. */ public URI(URI base, URI relative) throws URIException { if (base._scheme == null) { throw new URIException(URIException.PARSING, "base URI required"); } if (base._scheme != null) { this._scheme = base._scheme; this._authority = base._authority; this._is_net_path = base._is_net_path; } if (base._is_opaque_part || relative._is_opaque_part) { this._scheme = base._scheme; this._is_opaque_part = base._is_opaque_part || relative._is_opaque_part; this._opaque = relative._opaque; this._fragment = relative._fragment; this.setURI(); return; } boolean schemesEqual = Arrays.equals(base._scheme,relative._scheme); if (relative._scheme != null && (!schemesEqual || relative._authority != null)) { this._scheme = relative._scheme; this._is_net_path = relative._is_net_path; this._authority = relative._authority; if (relative._is_server) { this._is_server = relative._is_server; this._userinfo = relative._userinfo; this._host = relative._host; this._port = relative._port; } else if (relative._is_reg_name) { this._is_reg_name = relative._is_reg_name; } this._is_abs_path = relative._is_abs_path; this._is_rel_path = relative._is_rel_path; this._path = relative._path; } else if (base._authority != null && relative._scheme == null) { this._is_net_path = base._is_net_path; this._authority = base._authority; if (base._is_server) { this._is_server = base._is_server; this._userinfo = base._userinfo; this._host = base._host; this._port = base._port; } else if (base._is_reg_name) { this._is_reg_name = base._is_reg_name; } } if (relative._authority != null) { this._is_net_path = relative._is_net_path; this._authority = relative._authority; if (relative._is_server) { this._is_server = relative._is_server; this._userinfo = relative._userinfo; this._host = relative._host; this._port = relative._port; } else if (relative._is_reg_name) { this._is_reg_name = relative._is_reg_name; } this._is_abs_path = relative._is_abs_path; this._is_rel_path = relative._is_rel_path; this._path = relative._path; } // resolve the path and query if necessary if (relative._authority == null && (relative._scheme == null || schemesEqual)) { if ((relative._path == null || relative._path.length == 0) && relative._query == null) { // handle a reference to the current document, see RFC 2396 // section 5.2 step 2 this._path = base._path; this._query = base._query; } else { this._path = resolvePath(base._path, relative._path); } } // base._query removed if (relative._query != null) { this._query = relative._query; } // base._fragment removed if (relative._fragment != null) { this._fragment = relative._fragment; } this.setURI(); // reparse the newly built URI, this will ensure that all flags are set correctly. // TODO there must be a better way to do this parseUriReference(new String(_uri), true); } // --------------------------------------------------- Instance Variables /** Version ID for serialization */ static final long serialVersionUID = 604752400577948726L; /** * Cache the hash code for this URI. */ protected int hash = 0; /** * This Uniform Resource Identifier (URI). * The URI is always in an "escaped" form, since escaping or unescaping * a completed URI might change its semantics. */ protected char[] _uri = null; /** * The charset of the protocol used by this URI instance. */ protected String protocolCharset = null; /** * The default charset of the protocol. RFC 2277, 2396 */ protected static String defaultProtocolCharset = "UTF-8"; /** * The default charset of the document. RFC 2277, 2396 * The platform's charset is used for the document by default. */ protected static String defaultDocumentCharset = null; protected static String defaultDocumentCharsetByLocale = null; protected static String defaultDocumentCharsetByPlatform = null; // Static initializer for defaultDocumentCharset static { Locale locale = Locale.getDefault(); // in order to support backward compatiblity if (locale != null) { defaultDocumentCharsetByLocale = LocaleToCharsetMap.getCharset(locale); // set the default document charset defaultDocumentCharset = defaultDocumentCharsetByLocale; } // in order to support platform encoding try { defaultDocumentCharsetByPlatform = System.getProperty("file.encoding"); } catch (SecurityException ignore) { } if (defaultDocumentCharset == null) { // set the default document charset defaultDocumentCharset = defaultDocumentCharsetByPlatform; } } /** * The scheme. */ protected char[] _scheme = null; /** * The opaque. */ protected char[] _opaque = null; /** * The authority. */ protected char[] _authority = null; /** * The userinfo. */ protected char[] _userinfo = null; /** * The host. */ protected char[] _host = null; /** * The port. */ protected int _port = -1; /** * The path. */ protected char[] _path = null; /** * The query. */ protected char[] _query = null; /** * The fragment. */ protected char[] _fragment = null; /** * The root path. */ protected static final char[] rootPath = { '/' }; // ---------------------- Generous characters for each component validation /** * The percent "%" character always has the reserved purpose of being the * escape indicator, it must be escaped as "%25" in order to be used as * data within a URI. */ protected static final BitSet percent = new BitSet(256); // Static initializer for percent static { percent.set('%'); } /** * BitSet for digit. *

     * digit    = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
     *            "8" | "9"
     * 

*/ protected static final BitSet digit = new BitSet(256); // Static initializer for digit static { for (int i = '0'; i <= '9'; i++) { digit.set(i); } } /** * BitSet for alpha. *

     * alpha         = lowalpha | upalpha
     * 

*/ protected static final BitSet alpha = new BitSet(256); // Static initializer for alpha static { for (int i = 'a'; i <= 'z'; i++) { alpha.set(i); } for (int i = 'A'; i <= 'Z'; i++) { alpha.set(i); } } /** * BitSet for alphanum (join of alpha & digit). *

     *  alphanum      = alpha | digit
     * 

*/ protected static final BitSet alphanum = new BitSet(256); // Static initializer for alphanum static { alphanum.or(alpha); alphanum.or(digit); } /** * BitSet for hex. *

     * hex           = digit | "A" | "B" | "C" | "D" | "E" | "F" |
     *                         "a" | "b" | "c" | "d" | "e" | "f"
     * 

*/ protected static final BitSet hex = new BitSet(256); // Static initializer for hex static { hex.or(digit); for (int i = 'a'; i <= 'f'; i++) { hex.set(i); } for (int i = 'A'; i <= 'F'; i++) { hex.set(i); } } /** * BitSet for escaped. *

     * escaped       = "%" hex hex
     * 

*/ protected static final BitSet escaped = new BitSet(256); // Static initializer for escaped static { escaped.or(percent); escaped.or(hex); } /** * BitSet for mark. *

     * mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
     *                 "(" | ")"
     * 

*/ protected static final BitSet mark = new BitSet(256); // Static initializer for mark static { mark.set('-'); mark.set('_'); mark.set('.'); mark.set('!'); mark.set('~'); mark.set('*'); mark.set('\''); mark.set('('); mark.set(')'); } /** * Data characters that are allowed in a URI but do not have a reserved * purpose are called unreserved. *

     * unreserved    = alphanum | mark
     * 

*/ protected static final BitSet unreserved = new BitSet(256); // Static initializer for unreserved static { unreserved.or(alphanum); unreserved.or(mark); } /** * BitSet for reserved. *

     * reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
     *                 "$" | ","
     * 

*/ protected static final BitSet reserved = new BitSet(256); // Static initializer for reserved static { reserved.set(';'); reserved.set('/'); reserved.set('?'); reserved.set(':'); reserved.set('@'); reserved.set('&'); reserved.set('='); reserved.set('+'); reserved.set('$'); reserved.set(','); } /** * BitSet for uric. *

     * uric          = reserved | unreserved | escaped
     * 

*/ protected static final BitSet uric = new BitSet(256); // Static initializer for uric static { uric.or(reserved); uric.or(unreserved); uric.or(escaped); } /** * BitSet for fragment (alias for uric). *

     * fragment      = *uric
     * 

*/ protected static final BitSet fragment = uric; /** * BitSet for query (alias for uric). *

     * query         = *uric
     * 

*/ protected static final BitSet query = uric; /** * BitSet for pchar. *

     * pchar         = unreserved | escaped |
     *                 ":" | "@" | "&" | "=" | "+" | "$" | ","
     * 

*/ protected static final BitSet pchar = new BitSet(256); // Static initializer for pchar static { pchar.or(unreserved); pchar.or(escaped); pchar.set(':'); pchar.set('@'); pchar.set('&'); pchar.set('='); pchar.set('+'); pchar.set('$'); pchar.set(','); } /** * BitSet for param (alias for pchar). *

     * param         = *pchar
     * 

*/ protected static final BitSet param = pchar; /** * BitSet for segment. *

     * segment       = *pchar *( ";" param )
     * 

*/ protected static final BitSet segment = new BitSet(256); // Static initializer for segment static { segment.or(pchar); segment.set(';'); segment.or(param); } /** * BitSet for path segments. *

     * path_segments = segment *( "/" segment )
     * 

*/ protected static final BitSet path_segments = new BitSet(256); // Static initializer for path_segments static { path_segments.set('/'); path_segments.or(segment); } /** * URI absolute path. *

     * abs_path      = "/"  path_segments
     * 

*/ protected static final BitSet abs_path = new BitSet(256); // Static initializer for abs_path static { abs_path.set('/'); abs_path.or(path_segments); } /** * URI bitset for encoding typical non-slash characters. *

     * uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
     *                 "&" | "=" | "+" | "$" | ","
     * 

*/ protected static final BitSet uric_no_slash = new BitSet(256); // Static initializer for uric_no_slash static { uric_no_slash.or(unreserved); uric_no_slash.or(escaped); uric_no_slash.set(';'); uric_no_slash.set('?'); uric_no_slash.set(';'); uric_no_slash.set('@'); uric_no_slash.set('&'); uric_no_slash.set('='); uric_no_slash.set('+'); uric_no_slash.set('$'); uric_no_slash.set(','); } /** * URI bitset that combines uric_no_slash and uric. *

     * opaque_part   = uric_no_slash *uric
     * 

*/ protected static final BitSet opaque_part = new BitSet(256); // Static initializer for opaque_part static { // it's generous. because first character must not include a slash opaque_part.or(uric_no_slash); opaque_part.or(uric); } /** * URI bitset that combines absolute path and opaque part. *

     * path          = [ abs_path | opaque_part ]
     * 

*/ protected static final BitSet path = new BitSet(256); // Static initializer for path static { path.or(abs_path); path.or(opaque_part); } /** * Port, a logical alias for digit. */ protected static final BitSet port = digit; /** * Bitset that combines digit and dot fo IPv$address. *

     * IPv4address   = 1*digit "." 1*digit "." 1*digit "." 1*digit
     * 

*/ protected static final BitSet IPv4address = new BitSet(256); // Static initializer for IPv4address static { IPv4address.or(digit); IPv4address.set('.'); } /** * RFC 2373. *

     * IPv6address = hexpart [ ":" IPv4address ]
     * 

*/ protected static final BitSet IPv6address = new BitSet(256); // Static initializer for IPv6address reference static { IPv6address.or(hex); // hexpart IPv6address.set(':'); IPv6address.or(IPv4address); } /** * RFC 2732, 2373. *

     * IPv6reference   = "[" IPv6address "]"
     * 

*/ protected static final BitSet IPv6reference = new BitSet(256); // Static initializer for IPv6reference static { IPv6reference.set('['); IPv6reference.or(IPv6address); IPv6reference.set(']'); } /** * BitSet for toplabel. *

     * toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
     * 

*/ protected static final BitSet toplabel = new BitSet(256); // Static initializer for toplabel static { toplabel.or(alphanum); toplabel.set('-'); } /** * BitSet for domainlabel. *

     * domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
     * 

*/ protected static final BitSet domainlabel = toplabel; /** * BitSet for hostname. *

     * hostname      = *( domainlabel "." ) toplabel [ "." ]
     * 

*/ protected static final BitSet hostname = new BitSet(256); // Static initializer for hostname static { hostname.or(toplabel); // hostname.or(domainlabel); hostname.set('.'); } /** * BitSet for host. *

     * host          = hostname | IPv4address | IPv6reference
     * 

*/ protected static final BitSet host = new BitSet(256); // Static initializer for host static { host.or(hostname); // host.or(IPv4address); host.or(IPv6reference); // IPv4address } /** * BitSet for hostport. *

     * hostport      = host [ ":" port ]
     * 

*/ protected static final BitSet hostport = new BitSet(256); // Static initializer for hostport static { hostport.or(host); hostport.set(':'); hostport.or(port); } /** * Bitset for userinfo. *

     * userinfo      = *( unreserved | escaped |
     *                    ";" | ":" | "&" | "=" | "+" | "$" | "," )
     * 

*/ protected static final BitSet userinfo = new BitSet(256); // Static initializer for userinfo static { userinfo.or(unreserved); userinfo.or(escaped); userinfo.set(';'); userinfo.set(':'); userinfo.set('&'); userinfo.set('='); userinfo.set('+'); userinfo.set('$'); userinfo.set(','); } /** * BitSet for within the userinfo component like user and password. */ public static final BitSet within_userinfo = new BitSet(256); // Static initializer for within_userinfo static { within_userinfo.or(userinfo); within_userinfo.clear(';'); // reserved within authority within_userinfo.clear(':'); within_userinfo.clear('@'); within_userinfo.clear('?'); within_userinfo.clear('/'); } /** * Bitset for server. *

     * server        = [ [ userinfo "@" ] hostport ]
     * 

*/ protected static final BitSet server = new BitSet(256); // Static initializer for server static { server.or(userinfo); server.set('@'); server.or(hostport); } /** * BitSet for reg_name. *

     * reg_name      = 1*( unreserved | escaped | "$" | "," |
     *                     ";" | ":" | "@" | "&" | "=" | "+" )
     * 

*/ protected static final BitSet reg_name = new BitSet(256); // Static initializer for reg_name static { reg_name.or(unreserved); reg_name.or(escaped); reg_name.set('$'); reg_name.set(','); reg_name.set(';'); reg_name.set(':'); reg_name.set('@'); reg_name.set('&'); reg_name.set('='); reg_name.set('+'); } /** * BitSet for authority. *

     * authority     = server | reg_name
     * 

*/ protected static final BitSet authority = new BitSet(256); // Static initializer for authority static { authority.or(server); authority.or(reg_name); } /** * BitSet for scheme. *

     * scheme        = alpha *( alpha | digit | "+" | "-" | "." )
     * 

*/ protected static final BitSet scheme = new BitSet(256); // Static initializer for scheme static { scheme.or(alpha); scheme.or(digit); scheme.set('+'); scheme.set('-'); scheme.set('.'); } /** * BitSet for rel_segment. *

     * rel_segment   = 1*( unreserved | escaped |
     *                     ";" | "@" | "&" | "=" | "+" | "$" | "," )
     * 

*/ protected static final BitSet rel_segment = new BitSet(256); // Static initializer for rel_segment static { rel_segment.or(unreserved); rel_segment.or(escaped); rel_segment.set(';'); rel_segment.set('@'); rel_segment.set('&'); rel_segment.set('='); rel_segment.set('+'); rel_segment.set('$'); rel_segment.set(','); } /** * BitSet for rel_path. *

     * rel_path      = rel_segment [ abs_path ]
     * 

*/ protected static final BitSet rel_path = new BitSet(256); // Static initializer for rel_path static { rel_path.or(rel_segment); rel_path.or(abs_path); } /** * BitSet for net_path. *

     * net_path      = "//" authority [ abs_path ]
     * 

*/ protected static final BitSet net_path = new BitSet(256); // Static initializer for net_path static { net_path.set('/'); net_path.or(authority); net_path.or(abs_path); } /** * BitSet for hier_part. *

     * hier_part     = ( net_path | abs_path ) [ "?" query ]
     * 

*/ protected static final BitSet hier_part = new BitSet(256); // Static initializer for hier_part static { hier_part.or(net_path); hier_part.or(abs_path); // hier_part.set('?'); aleady included hier_part.or(query); } /** * BitSet for relativeURI. *

     * relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
     * 

*/ protected static final BitSet relativeURI = new BitSet(256); // Static initializer for relativeURI static { relativeURI.or(net_path); relativeURI.or(abs_path); relativeURI.or(rel_path); // relativeURI.set('?'); aleady included relativeURI.or(query); } /** * BitSet for absoluteURI. *

     * absoluteURI   = scheme ":" ( hier_part | opaque_part )
     * 

*/ protected static final BitSet absoluteURI = new BitSet(256); // Static initializer for absoluteURI static { absoluteURI.or(scheme); absoluteURI.set(':'); absoluteURI.or(hier_part); absoluteURI.or(opaque_part); } /** * BitSet for URI-reference. *

     * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
     * 

*/ protected static final BitSet URI_reference = new BitSet(256); // Static initializer for URI_reference static { URI_reference.or(absoluteURI); URI_reference.or(relativeURI); URI_reference.set('#'); URI_reference.or(fragment); } // ---------------------------- Characters disallowed within the URI syntax // Excluded US-ASCII Characters are like control, space, delims and unwise /** * BitSet for control. */ public static final BitSet control = new BitSet(256); // Static initializer for control static { for (int i = 0; i <= 0x1F; i++) { control.set(i); } control.set(0x7F); } /** * BitSet for space. */ public static final BitSet space = new BitSet(256); // Static initializer for space static { space.set(0x20); } /** * BitSet for delims. */ public static final BitSet delims = new BitSet(256); // Static initializer for delims static { delims.set('<'); delims.set('>'); delims.set('#'); delims.set('%'); delims.set('"'); } /** * BitSet for unwise. */ public static final BitSet unwise = new BitSet(256); // Static initializer for unwise static { unwise.set('{'); unwise.set('}'); unwise.set('|'); unwise.set('\\'); unwise.set('^'); unwise.set('['); unwise.set(']'); unwise.set('`'); } /** * Disallowed rel_path before escaping. */ public static final BitSet disallowed_rel_path = new BitSet(256); // Static initializer for disallowed_rel_path static { disallowed_rel_path.or(uric); disallowed_rel_path.andNot(rel_path); } /** * Disallowed opaque_part before escaping. */ public static final BitSet disallowed_opaque_part = new BitSet(256); // Static initializer for disallowed_opaque_part static { disallowed_opaque_part.or(uric); disallowed_opaque_part.andNot(opaque_part); } // ----------------------- Characters allowed within and for each component /** * Those characters that are allowed for the authority component. */ public static final BitSet allowed_authority = new BitSet(256); // Static initializer for allowed_authority static { allowed_authority.or(authority); allowed_authority.clear('%'); } /** * Those characters that are allowed for the opaque_part. */ public static final BitSet allowed_opaque_part = new BitSet(256); // Static initializer for allowed_opaque_part static { allowed_opaque_part.or(opaque_part); allowed_opaque_part.clear('%'); } /** * Those characters that are allowed for the reg_name. */ public static final BitSet allowed_reg_name = new BitSet(256); // Static initializer for allowed_reg_name static { allowed_reg_name.or(reg_name); // allowed_reg_name.andNot(percent); allowed_reg_name.clear('%'); } /** * Those characters that are allowed for the userinfo component. */ public static final BitSet allowed_userinfo = new BitSet(256); // Static initializer for allowed_userinfo static { allowed_userinfo.or(userinfo); // allowed_userinfo.andNot(percent); allowed_userinfo.clear('%'); } /** * Those characters that are allowed for within the userinfo component. */ public static final BitSet allowed_within_userinfo = new BitSet(256); // Static initializer for allowed_within_userinfo static { allowed_within_userinfo.or(within_userinfo); allowed_within_userinfo.clear('%'); } /** * Those characters that are allowed for the IPv6reference component. * The characters '[', ']' in IPv6reference should be excluded. */ public static final BitSet allowed_IPv6reference = new BitSet(256); // Static initializer for allowed_IPv6reference static { allowed_IPv6reference.or(IPv6reference); // allowed_IPv6reference.andNot(unwise); allowed_IPv6reference.clear('['); allowed_IPv6reference.clear(']'); } /** * Those characters that are allowed for the host component. * The characters '[', ']' in IPv6reference should be excluded. */ public static final BitSet allowed_host = new BitSet(256); // Static initializer for allowed_host static { allowed_host.or(hostname); allowed_host.or(allowed_IPv6reference); } /** * Those characters that are allowed for the authority component. */ public static final BitSet allowed_within_authority = new BitSet(256); // Static initializer for allowed_within_authority static { allowed_within_authority.or(server); allowed_within_authority.or(reg_name); allowed_within_authority.clear(';'); allowed_within_authority.clear(':'); allowed_within_authority.clear('@'); allowed_within_authority.clear('?'); allowed_within_authority.clear('/'); } /** * Those characters that are allowed for the abs_path. */ public static final BitSet allowed_abs_path = new BitSet(256); // Static initializer for allowed_abs_path static { allowed_abs_path.or(abs_path); // allowed_abs_path.set('/'); // aleady included allowed_abs_path.andNot(percent); allowed_abs_path.clear('+'); } /** * Those characters that are allowed for the rel_path. */ public static final BitSet allowed_rel_path = new BitSet(256); // Static initializer for allowed_rel_path static { allowed_rel_path.or(rel_path); allowed_rel_path.clear('%'); allowed_rel_path.clear('+'); } /** * Those characters that are allowed within the path. */ public static final BitSet allowed_within_path = new BitSet(256); // Static initializer for allowed_within_path static { allowed_within_path.or(abs_path); allowed_within_path.clear('/'); allowed_within_path.clear(';'); allowed_within_path.clear('='); allowed_within_path.clear('?'); } /** * Those characters that are allowed for the query component. */ public static final BitSet allowed_query = new BitSet(256); // Static initializer for allowed_query static { allowed_query.or(uric); allowed_query.clear('%'); } /** * Those characters that are allowed within the query component. */ public static final BitSet allowed_within_query = new BitSet(256); // Static initializer for allowed_within_query static { allowed_within_query.or(allowed_query); allowed_within_query.andNot(reserved); // excluded 'reserved' } /** * Those characters that are allowed for the fragment component. */ public static final BitSet allowed_fragment = new BitSet(256); // Static initializer for allowed_fragment static { allowed_fragment.or(uric); allowed_fragment.clear('%'); } // ------------------------------------------- Flags for this URI-reference // TODO: Figure out what all these variables are for and provide javadoc // URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] // absoluteURI = scheme ":" ( hier_part | opaque_part ) protected boolean _is_hier_part; protected boolean _is_opaque_part; // relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ] // hier_part = ( net_path | abs_path ) [ "?" query ] protected boolean _is_net_path; protected boolean _is_abs_path; protected boolean _is_rel_path; // net_path = "//" authority [ abs_path ] // authority = server | reg_name protected boolean _is_reg_name; protected boolean _is_server; // = _has_server // server = [ [ userinfo "@" ] hostport ] // host = hostname | IPv4address | IPv6reference protected boolean _is_hostname; protected boolean _is_IPv4address; protected boolean _is_IPv6reference; // ------------------------------------------ Character and escape encoding /** * Encodes URI string. * * This is a two mapping, one from original characters to octets, and * subsequently a second from octets to URI characters: *

     *   original character sequence->octet sequence->URI character sequence
     * 

* * An escaped octet is encoded as a character triplet, consisting of the * percent character "%" followed by the two hexadecimal digits * representing the octet code. For example, "%20" is the escaped * encoding for the US-ASCII space character. *

* Conversion from the local filesystem character set to UTF-8 will * normally involve a two step process. First convert the local character * set to the UCS; then convert the UCS to UTF-8. * The first step in the process can be performed by maintaining a mapping * table that includes the local character set code and the corresponding * UCS code. * The next step is to convert the UCS character code to the UTF-8 encoding. *

* Mapping between vendor codepages can be done in a very similar manner * as described above. *

* The only time escape encodings can allowedly be made is when a URI is * being created from its component parts. The escape and validate methods * are internally performed within this method. * * @param original the original character sequence * @param allowed those characters that are allowed within a component * @param charset the protocol charset * @return URI character sequence * @throws URIException null component or unsupported character encoding */ protected static char[] encode(String original, BitSet allowed, String charset) throws URIException { if (original == null) { throw new IllegalArgumentException("Original string may not be null"); } if (allowed == null) { throw new IllegalArgumentException("Allowed bitset may not be null"); } byte[] rawdata = URLCodec.encodeUrl(allowed, EncodingUtil.getBytes(original, charset)); return EncodingUtil.getAsciiString(rawdata).toCharArray(); } /** * Decodes URI encoded string. * * This is a two mapping, one from URI characters to octets, and * subsequently a second from octets to original characters: *

     *   URI character sequence->octet sequence->original character sequence
     * 

* * A URI must be separated into its components before the escaped * characters within those components can be allowedly decoded. *

* Notice that there is a chance that URI characters that are non UTF-8 * may be parsed as valid UTF-8. A recent non-scientific analysis found * that EUC encoded Japanese words had a 2.7% false reading; SJIS had a * 0.0005% false reading; other encoding such as ASCII or KOI-8 have a 0% * false reading. *

* The percent "%" character always has the reserved purpose of being * the escape indicator, it must be escaped as "%25" in order to be used * as data within a URI. *

* The unescape method is internally performed within this method. * * @param component the URI character sequence * @param charset the protocol charset * @return original character sequence * @throws URIException incomplete trailing escape pattern or unsupported * character encoding */ protected static String decode(char[] component, String charset) throws URIException { if (component == null) { throw new IllegalArgumentException("Component array of chars may not be null"); } return decode(new String(component), charset); } /** * Decodes URI encoded string. * * This is a two mapping, one from URI characters to octets, and * subsequently a second from octets to original characters: *

     *   URI character sequence->octet sequence->original character sequence
     * 

* * A URI must be separated into its components before the escaped * characters within those components can be allowedly decoded. *

* Notice that there is a chance that URI characters that are non UTF-8 * may be parsed as valid UTF-8. A recent non-scientific analysis found * that EUC encoded Japanese words had a 2.7% false reading; SJIS had a * 0.0005% false reading; other encoding such as ASCII or KOI-8 have a 0% * false reading. *

* The percent "%" character always has the reserved purpose of being * the escape indicator, it must be escaped as "%25" in order to be used * as data within a URI. *

* The unescape method is internally performed within this method. * * @param component the URI character sequence * @param charset the protocol charset * @return original character sequence * @throws URIException incomplete trailing escape pattern or unsupported * character encoding * * @since 3.0 */ protected static String decode(String component, String charset) throws URIException { if (component == null) { throw new IllegalArgumentException("Component array of chars may not be null"); } byte[] rawdata = null; try { rawdata = URLCodec.decodeUrl(EncodingUtil.getAsciiBytes(component)); } catch (DecoderException e) { throw new URIException(e.getMessage()); } return EncodingUtil.getString(rawdata, charset); } /** * Pre-validate the unescaped URI string within a specific component. * * @param component the component string within the component * @param disallowed those characters disallowed within the component * @return if true, it doesn't have the disallowed characters * if false, the component is undefined or an incorrect one */ protected boolean prevalidate(String component, BitSet disallowed) { // prevalidate the given component by disallowed characters if (component == null) { return false; // undefined } char[] target = component.toCharArray(); for (int i = 0; i < target.length; i++) { if (disallowed.get(target[i])) { return false; } } return true; } /** * Validate the URI characters within a specific component. * The component must be performed after escape encoding. Or it doesn't * include escaped characters. * * @param component the characters sequence within the component * @param generous those characters that are allowed within a component * @return if true, it's the correct URI character sequence */ protected boolean validate(char[] component, BitSet generous) { // validate each component by generous characters return validate(component, 0, -1, generous); } /** * Validate the URI characters within a specific component. * The component must be performed after escape encoding. Or it doesn't * include escaped characters. *

* It's not that much strict, generous. The strict validation might be * performed before being called this method. * * @param component the characters sequence within the component * @param soffset the starting offset of the given component * @param eoffset the ending offset of the given component * if -1, it means the length of the component * @param generous those characters that are allowed within a component * @return if true, it's the correct URI character sequence */ protected boolean validate(char[] component, int soffset, int eoffset, BitSet generous) { // validate each component by generous characters if (eoffset == -1) { eoffset = component.length - 1; } for (int i = soffset; i <= eoffset; i++) { if (!generous.get(component[i])) { return false; } } return true; } /** * In order to avoid any possilbity of conflict with non-ASCII characters, * Parse a URI reference as a String with the character * encoding of the local system or the document. *

* The following line is the regular expression for breaking-down a URI * reference into its components. *

     *   ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
     *    12            3  4          5       6  7        8 9
     * 

* For example, matching the above expression to * http://jakarta.apache.org/ietf/uri/#Related * results in the following subexpression matches: *

     *               $1 = http:
     *  scheme    =  $2 = http
     *               $3 = //jakarta.apache.org
     *  authority =  $4 = jakarta.apache.org
     *  path      =  $5 = /ietf/uri/
     *               $6 = 
     *  query     =  $7 = 
     *               $8 = #Related
     *  fragment  =  $9 = Related
     * 

* * @param original the original character sequence * @param escaped true if original is escaped * @throws URIException If an error occurs. */ protected void parseUriReference(String original, boolean escaped) throws URIException { // validate and contruct the URI character sequence if (original == null) { throw new URIException("URI-Reference required"); } /* @ * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? */ String tmp = original.trim(); /* * The length of the string sequence of characters. * It may not be equal to the length of the byte array. */ int length = tmp.length(); /* * Remove the delimiters like angle brackets around an URI. */ if (length > 0) { char[] firstDelimiter = { tmp.charAt(0) }; if (validate(firstDelimiter, delims)) { if (length >= 2) { char[] lastDelimiter = { tmp.charAt(length - 1) }; if (validate(lastDelimiter, delims)) { tmp = tmp.substring(1, length - 1); length = length - 2; } } } } /* * The starting index */ int from = 0; /* * The test flag whether the URI is started from the path component. */ boolean isStartedFromPath = false; int atColon = tmp.indexOf(':'); int atSlash = tmp.indexOf('/'); if ((atColon <= 0 && !tmp.startsWith("//")) || (atSlash >= 0 && atSlash < atColon)) { isStartedFromPath = true; } /* *

         *     @@@@@@@@
         *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
         * 

*/ int at = indexFirstOf(tmp, isStartedFromPath ? "/?#" : ":/?#", from); if (at == -1) { at = 0; } /* * Parse the scheme. *

         *  scheme    =  $2 = http
         *              @
         *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
         * 

*/ if (at > 0 && at < length && tmp.charAt(at) == ':') { char[] target = tmp.substring(0, at).toLowerCase().toCharArray(); if (validate(target, scheme)) { _scheme = target; } else { throw new URIException("incorrect scheme"); } from = ++at; } /* * Parse the authority component. *

         *  authority =  $4 = jakarta.apache.org
         *                  @@
         *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
         * 

*/ // Reset flags _is_net_path = _is_abs_path = _is_rel_path = _is_hier_part = false; if (0 <= at && at < length && tmp.charAt(at) == '/') { // Set flag _is_hier_part = true; if (at + 2 < length && tmp.charAt(at + 1) == '/' && !isStartedFromPath) { // the temporary index to start the search from int next = indexFirstOf(tmp, "/?#", at + 2); if (next == -1) { next = (tmp.substring(at + 2).length() == 0) ? at + 2 : tmp.length(); } parseAuthority(tmp.substring(at + 2, next), escaped); from = at = next; // Set flag _is_net_path = true; } if (from == at) { // Set flag _is_abs_path = true; } } /* * Parse the path component. *

         *  path      =  $5 = /ietf/uri/
         *                                @@@@@@
         *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
         * 

*/ if (from < length) { // rel_path = rel_segment [ abs_path ] int next = indexFirstOf(tmp, "?#", from); if (next == -1) { next = tmp.length(); } if (!_is_abs_path) { if (!escaped && prevalidate(tmp.substring(from, next), disallowed_rel_path) || escaped && validate(tmp.substring(from, next).toCharArray(), rel_path)) { // Set flag _is_rel_path = true; } else if (!escaped && prevalidate(tmp.substring(from, next), disallowed_opaque_part) || escaped && validate(tmp.substring(from, next).toCharArray(), opaque_part)) { // Set flag _is_opaque_part = true; } else { // the path component may be empty _path = null; } } String s = tmp.substring(from, next); if (escaped) { setRawPath(s.toCharArray()); } else { setPath(s); } at = next; } // set the charset to do escape encoding String charset = getProtocolCharset(); /* * Parse the query component. *

         *  query     =  $7 = 
         *                                        @@@@@@@@@
         *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
         * 

*/ if (0 <= at && at + 1 < length && tmp.charAt(at) == '?') { int next = tmp.indexOf('#', at + 1); if (next == -1) { next = tmp.length(); } if (escaped) { _query = tmp.substring(at + 1, next).toCharArray(); if (!validate(_query, uric)) { throw new URIException("Invalid query"); } } else { _query = encode(tmp.substring(at + 1, next), allowed_query, charset); } at = next; } /* * Parse the fragment component. *

         *  fragment  =  $9 = Related
         *                                                   @@@@@@@@
         *  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
         * 

*/ if (0 <= at && at + 1 <= length && tmp.charAt(at) == '#') { if (at + 1 == length) { // empty fragment _fragment = "".toCharArray(); } else { _fragment = (escaped) ? tmp.substring(at + 1).toCharArray() : encode(tmp.substring(at + 1), allowed_fragment, charset); } } // set this URI. setURI(); } /** * Get the earlier index that to be searched for the first occurrance in * one of any of the given string. * * @param s the string to be indexed * @param delims the delimiters used to index * @return the earlier index if there are delimiters */ protected int indexFirstOf(String s, String delims) { return indexFirstOf(s, delims, -1); } /** * Get the earlier index that to be searched for the first occurrance in * one of any of the given string. * * @param s the string to be indexed * @param delims the delimiters used to index * @param offset the from index * @return the earlier index if there are delimiters */ protected int indexFirstOf(String s, String delims, int offset) { if (s == null || s.length() == 0) { return -1; } if (delims == null || delims.length() == 0) { return -1; } // check boundaries if (offset < 0) { offset = 0; } else if (offset > s.length()) { return -1; } // s is never null int min = s.length(); char[] delim = delims.toCharArray(); for (int i = 0; i < delim.length; i++) { int at = s.indexOf(delim[i], offset); if (at >= 0 && at < min) { min = at; } } return (min == s.length()) ? -1 : min; } /** * Get the earlier index that to be searched for the first occurrance in * one of any of the given array. * * @param s the character array to be indexed * @param delim the delimiter used to index * @return the ealier index if there are a delimiter */ protected int indexFirstOf(char[] s, char delim) { return indexFirstOf(s, delim, 0); } /** * Get the earlier index that to be searched for the first occurrance in * one of any of the given array. * * @param s the character array to be indexed * @param delim the delimiter used to index * @param offset The offset. * @return the ealier index if there is a delimiter */ protected int indexFirstOf(char[] s, char delim, int offset) { if (s == null || s.length == 0) { return -1; } // check boundaries if (offset < 0) { offset = 0; } else if (offset > s.length) { return -1; } for (int i = offset; i < s.length; i++) { if (s[i] == delim) { return i; } } return -1; } /** * Parse the authority component. * * @param original the original character sequence of authority component * @param escaped true if original is escaped * @throws URIException If an error occurs. */ protected void parseAuthority(String original, boolean escaped) throws URIException { // Reset flags _is_reg_name = _is_server = _is_hostname = _is_IPv4address = _is_IPv6reference = false; // set the charset to do escape encoding String charset = getProtocolCharset(); boolean hasPort = true; int from = 0; int next = original.indexOf('@'); if (next != -1) { // neither -1 and 0 // each protocol extented from URI supports the specific userinfo _userinfo = (escaped) ? original.substring(0, next).toCharArray() : encode(original.substring(0, next), allowed_userinfo, charset); from = next + 1; } next = original.indexOf('[', from); if (next >= from) { next = original.indexOf(']', from); if (next == -1) { throw new URIException(URIException.PARSING, "IPv6reference"); } else { next++; } // In IPv6reference, '[', ']' should be excluded _host = (escaped) ? original.substring(from, next).toCharArray() : encode(original.substring(from, next), allowed_IPv6reference, charset); // Set flag _is_IPv6reference = true; } else { // only for !_is_IPv6reference next = original.indexOf(':', from); if (next == -1) { next = original.length(); hasPort = false; } // REMINDME: it doesn't need the pre-validation _host = original.substring(from, next).toCharArray(); if (validate(_host, IPv4address)) { // Set flag _is_IPv4address = true; } else if (validate(_host, hostname)) { // Set flag _is_hostname = true; } else { // Set flag _is_reg_name = true; } } if (_is_reg_name) { // Reset flags for a server-based naming authority _is_server = _is_hostname = _is_IPv4address = _is_IPv6reference = false; // set a registry-based naming authority if (escaped) { _authority = original.toCharArray(); if (!validate(_authority, reg_name)) { throw new URIException("Invalid authority"); } } else { _authority = encode(original, allowed_reg_name, charset); } } else { if (original.length() - 1 > next && hasPort && original.charAt(next) == ':') { // not empty from = next + 1; try { _port = Integer.parseInt(original.substring(from)); } catch (NumberFormatException error) { throw new URIException(URIException.PARSING, "invalid port number"); } } // set a server-based naming authority StringBuffer buf = new StringBuffer(); if (_userinfo != null) { // has_userinfo buf.append(_userinfo); buf.append('@'); } if (_host != null) { buf.append(_host); if (_port != -1) { buf.append(':'); buf.append(_port); } } _authority = buf.toString().toCharArray(); // Set flag _is_server = true; } } /** * Once it's parsed successfully, set this URI. * * @see #getRawURI */ protected void setURI() { // set _uri StringBuffer buf = new StringBuffer(); // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? if (_scheme != null) { buf.append(_scheme); buf.append(':'); } if (_is_net_path) { buf.append("//"); if (_authority != null) { // has_authority buf.append(_authority); } } if (_opaque != null && _is_opaque_part) { buf.append(_opaque); } else if (_path != null) { // _is_hier_part or _is_relativeURI if (_path.length != 0) { buf.append(_path); } } if (_query != null) { // has_query buf.append('?'); buf.append(_query); } // ignore the fragment identifier _uri = buf.toString().toCharArray(); hash = 0; } // ----------------------------------------------------------- Test methods /** * Tell whether or not this URI is absolute. * * @return true iif this URI is absoluteURI */ public boolean isAbsoluteURI() { return (_scheme != null); } /** * Tell whether or not this URI is relative. * * @return true iif this URI is relativeURI */ public boolean isRelativeURI() { return (_scheme == null); } /** * Tell whether or not the absoluteURI of this URI is hier_part. * * @return true iif the absoluteURI is hier_part */ public boolean isHierPart() { return _is_hier_part; } /** * Tell whether or not the absoluteURI of this URI is opaque_part. * * @return true iif the absoluteURI is opaque_part */ public boolean isOpaquePart() { return _is_opaque_part; } /** * Tell whether or not the relativeURI or heir_part of this URI is net_path. * It's the same function as the has_authority() method. * * @return true iif the relativeURI or heir_part is net_path * @see #hasAuthority */ public boolean isNetPath() { return _is_net_path || (_authority != null); } /** * Tell whether or not the relativeURI or hier_part of this URI is abs_path. * * @return true iif the relativeURI or hier_part is abs_path */ public boolean isAbsPath() { return _is_abs_path; } /** * Tell whether or not the relativeURI of this URI is rel_path. * * @return true iif the relativeURI is rel_path */ public boolean isRelPath() { return _is_rel_path; } /** * Tell whether or not this URI has authority. * It's the same function as the is_net_path() method. * * @return true iif this URI has authority * @see #isNetPath */ public boolean hasAuthority() { return (_authority != null) || _is_net_path; } /** * Tell whether or not the authority component of this URI is reg_name. * * @return true iif the authority component is reg_name */ public boolean isRegName() { return _is_reg_name; } /** * Tell whether or not the authority component of this URI is server. * * @return true iif the authority component is server */ public boolean isServer() { return _is_server; } /** * Tell whether or not this URI has userinfo. * * @return true iif this URI has userinfo */ public boolean hasUserinfo() { return (_userinfo != null); } /** * Tell whether or not the host part of this URI is hostname. * * @return true iif the host part is hostname */ public boolean isHostname() { return _is_hostname; } /** * Tell whether or not the host part of this URI is IPv4address. * * @return true iif the host part is IPv4address */ public boolean isIPv4address() { return _is_IPv4address; } /** * Tell whether or not the host part of this URI is IPv6reference. * * @return true iif the host part is IPv6reference */ public boolean isIPv6reference() { return _is_IPv6reference; } /** * Tell whether or not this URI has query. * * @return true iif this URI has query */ public boolean hasQuery() { return (_query != null); } /** * Tell whether or not this URI has fragment. * * @return true iif this URI has fragment */ public boolean hasFragment() { return (_fragment != null); } // ---------------------------------------------------------------- Charset /** * Set the default charset of the protocol. *

* The character set used to store files SHALL remain a local decision and * MAY depend on the capability of local operating systems. Prior to the * exchange of URIs they SHOULD be converted into a ISO/IEC 10646 format * and UTF-8 encoded. This approach, while allowing international exchange * of URIs, will still allow backward compatibility with older systems * because the code set positions for ASCII characters are identical to the * one byte sequence in UTF-8. *

* An individual URI scheme may require a single charset, define a default * charset, or provide a way to indicate the charset used. * *

* Always all the time, the setter method is always succeeded and throws * DefaultCharsetChanged exception. * * So API programmer must follow the following way: *

     *  import org.apache.util.URI$DefaultCharsetChanged;
     *      .
     *      .
     *      .
     *  try {
     *      URI.setDefaultProtocolCharset("UTF-8");
     *  } catch (DefaultCharsetChanged cc) {
     *      // CASE 1: the exception could be ignored, when it is set by user
     *      if (cc.getReasonCode() == DefaultCharsetChanged.PROTOCOL_CHARSET) {
     *      // CASE 2: let user know the default protocol charset changed
     *      } else {
     *      // CASE 2: let user know the default document charset changed
     *      }
     *  }
     *  
* * The API programmer is responsible to set the correct charset. * And each application should remember its own charset to support. * * @param charset the default charset for each protocol * @throws DefaultCharsetChanged default charset changed */ public static void setDefaultProtocolCharset(String charset) throws DefaultCharsetChanged { defaultProtocolCharset = charset; throw new DefaultCharsetChanged(DefaultCharsetChanged.PROTOCOL_CHARSET, "the default protocol charset changed"); } /** * Get the default charset of the protocol. *

* An individual URI scheme may require a single charset, define a default * charset, or provide a way to indicate the charset used. *

* To work globally either requires support of a number of character sets * and to be able to convert between them, or the use of a single preferred * character set. * For support of global compatibility it is STRONGLY RECOMMENDED that * clients and servers use UTF-8 encoding when exchanging URIs. * * @return the default charset string */ public static String getDefaultProtocolCharset() { return defaultProtocolCharset; } /** * Get the protocol charset used by this current URI instance. * It was set by the constructor for this instance. If it was not set by * contructor, it will return the default protocol charset. * * @return the protocol charset string * @see #getDefaultProtocolCharset */ public String getProtocolCharset() { return (protocolCharset != null) ? protocolCharset : defaultProtocolCharset; } /** * Set the default charset of the document. *

* Notice that it will be possible to contain mixed characters (e.g. * ftp://host/KoreanNamespace/ChineseResource). To handle the Bi-directional * display of these character sets, the protocol charset could be simply * used again. Because it's not yet implemented that the insertion of BIDI * control characters at different points during composition is extracted. *

* * Always all the time, the setter method is always succeeded and throws * DefaultCharsetChanged exception. * * So API programmer must follow the following way: *

     *  import org.apache.util.URI$DefaultCharsetChanged;
     *      .
     *      .
     *      .
     *  try {
     *      URI.setDefaultDocumentCharset("EUC-KR");
     *  } catch (DefaultCharsetChanged cc) {
     *      // CASE 1: the exception could be ignored, when it is set by user
     *      if (cc.getReasonCode() == DefaultCharsetChanged.DOCUMENT_CHARSET) {
     *      // CASE 2: let user know the default document charset changed
     *      } else {
     *      // CASE 2: let user know the default protocol charset changed
     *      }
     *  }
     *  
* * The API programmer is responsible to set the correct charset. * And each application should remember its own charset to support. * * @param charset the default charset for the document * @throws DefaultCharsetChanged default charset changed */ public static void setDefaultDocumentCharset(String charset) throws DefaultCharsetChanged { defaultDocumentCharset = charset; throw new DefaultCharsetChanged(DefaultCharsetChanged.DOCUMENT_CHARSET, "the default document charset changed"); } /** * Get the recommended default charset of the document. * * @return the default charset string */ public static String getDefaultDocumentCharset() { return defaultDocumentCharset; } /** * Get the default charset of the document by locale. * * @return the default charset string by locale */ public static String getDefaultDocumentCharsetByLocale() { return defaultDocumentCharsetByLocale; } /** * Get the default charset of the document by platform. * * @return the default charset string by platform */ public static String getDefaultDocumentCharsetByPlatform() { return defaultDocumentCharsetByPlatform; } // ------------------------------------------------------------- The scheme /** * Get the scheme. * * @return the scheme */ public char[] getRawScheme() { return _scheme; } /** * Get the scheme. * * @return the scheme * null if undefined scheme */ public String getScheme() { return (_scheme == null) ? null : new String(_scheme); } // ---------------------------------------------------------- The authority /** * Set the authority. It can be one type of server, hostport, hostname, * IPv4address, IPv6reference and reg_name. *

     *   authority     = server | reg_name
     * 

* * @param escapedAuthority the raw escaped authority * @throws URIException If {@link * #parseAuthority(java.lang.String,boolean)} fails * @throws NullPointerException null authority */ public void setRawAuthority(char[] escapedAuthority) throws URIException, NullPointerException { parseAuthority(new String(escapedAuthority), true); setURI(); } /** * Set the authority. It can be one type of server, hostport, hostname, * IPv4address, IPv6reference and reg_name. * Note that there is no setAuthority method by the escape encoding reason. * * @param escapedAuthority the escaped authority string * @throws URIException If {@link * #parseAuthority(java.lang.String,boolean)} fails */ public void setEscapedAuthority(String escapedAuthority) throws URIException { parseAuthority(escapedAuthority, true); setURI(); } /** * Get the raw-escaped authority. * * @return the raw-escaped authority */ public char[] getRawAuthority() { return _authority; } /** * Get the escaped authority. * * @return the escaped authority */ public String getEscapedAuthority() { return (_authority == null) ? null : new String(_authority); } /** * Get the authority. * * @return the authority * @throws URIException If {@link #decode} fails */ public String getAuthority() throws URIException { return (_authority == null) ? null : decode(_authority, getProtocolCharset()); } // ----------------------------------------------------------- The userinfo /** * Get the raw-escaped userinfo. * * @return the raw-escaped userinfo * @see #getAuthority */ public char[] getRawUserinfo() { return _userinfo; } /** * Get the escaped userinfo. * * @return the escaped userinfo * @see #getAuthority */ public String getEscapedUserinfo() { return (_userinfo == null) ? null : new String(_userinfo); } /** * Get the userinfo. * * @return the userinfo * @throws URIException If {@link #decode} fails * @see #getAuthority */ public String getUserinfo() throws URIException { return (_userinfo == null) ? null : decode(_userinfo, getProtocolCharset()); } // --------------------------------------------------------------- The host /** * Get the host. *

     *   host          = hostname | IPv4address | IPv6reference
     * 

* * @return the host * @see #getAuthority */ public char[] getRawHost() { return _host; } /** * Get the host. *

     *   host          = hostname | IPv4address | IPv6reference
     * 

* * @return the host * @throws URIException If {@link #decode} fails * @see #getAuthority */ public String getHost() throws URIException { if (_host != null) { return decode(_host, getProtocolCharset()); } else { return null; } } // --------------------------------------------------------------- The port /** * Get the port. In order to get the specfic default port, the specific * protocol-supported class extended from the URI class should be used. * It has the server-based naming authority. * * @return the port * if -1, it has the default port for the scheme or the server-based * naming authority is not supported in the specific URI. */ public int getPort() { return _port; } // --------------------------------------------------------------- The path /** * Set the raw-escaped path. * * @param escapedPath the path character sequence * @throws URIException encoding error or not proper for initial instance * @see #encode */ public void setRawPath(char[] escapedPath) throws URIException { if (escapedPath == null || escapedPath.length == 0) { _path = _opaque = escapedPath; setURI(); return; } // remove the fragment identifier escapedPath = removeFragmentIdentifier(escapedPath); if (_is_net_path || _is_abs_path) { if (escapedPath[0] != '/') { throw new URIException(URIException.PARSING, "not absolute path"); } if (!validate(escapedPath, abs_path)) { throw new URIException(URIException.ESCAPING, "escaped absolute path not valid"); } _path = escapedPath; } else if (_is_rel_path) { int at = indexFirstOf(escapedPath, '/'); if (at == 0) { throw new URIException(URIException.PARSING, "incorrect path"); } if (at > 0 && !validate(escapedPath, 0, at - 1, rel_segment) && !validate(escapedPath, at, -1, abs_path) || at < 0 && !validate(escapedPath, 0, -1, rel_segment)) { throw new URIException(URIException.ESCAPING, "escaped relative path not valid"); } _path = escapedPath; } else if (_is_opaque_part) { if (!uric_no_slash.get(escapedPath[0]) && !validate(escapedPath, 1, -1, uric)) { throw new URIException(URIException.ESCAPING, "escaped opaque part not valid"); } _opaque = escapedPath; } else { throw new URIException(URIException.PARSING, "incorrect path"); } setURI(); } /** * Set the escaped path. * * @param escapedPath the escaped path string * @throws URIException encoding error or not proper for initial instance * @see #encode */ public void setEscapedPath(String escapedPath) throws URIException { if (escapedPath == null) { _path = _opaque = null; setURI(); return; } setRawPath(escapedPath.toCharArray()); } /** * Set the path. * * @param path the path string * @throws URIException set incorrectly or fragment only * @see #encode */ public void setPath(String path) throws URIException { if (path == null || path.length() == 0) { _path = _opaque = (path == null) ? null : path.toCharArray(); setURI(); return; } // set the charset to do escape encoding String charset = getProtocolCharset(); if (_is_net_path || _is_abs_path) { _path = encode(path, allowed_abs_path, charset); } else if (_is_rel_path) { StringBuffer buff = new StringBuffer(path.length()); int at = path.indexOf('/'); if (at == 0) { // never 0 throw new URIException(URIException.PARSING, "incorrect relative path"); } if (at > 0) { buff.append(encode(path.substring(0, at), allowed_rel_path, charset)); buff.append(encode(path.substring(at), allowed_abs_path, charset)); } else { buff.append(encode(path, allowed_rel_path, charset)); } _path = buff.toString().toCharArray(); } else if (_is_opaque_part) { StringBuffer buf = new StringBuffer(); buf.insert(0, encode(path.substring(0, 1), uric_no_slash, charset)); buf.insert(1, encode(path.substring(1), uric, charset)); _opaque = buf.toString().toCharArray(); } else { throw new URIException(URIException.PARSING, "incorrect path"); } setURI(); } /** * Resolve the base and relative path. * * @param basePath a character array of the basePath * @param relPath a character array of the relPath * @return the resolved path * @throws URIException no more higher path level to be resolved */ protected char[] resolvePath(char[] basePath, char[] relPath) throws URIException { // REMINDME: paths are never null String base = (basePath == null) ? "" : new String(basePath); // _path could be empty if (relPath == null || relPath.length == 0) { return normalize(basePath); } else if (relPath[0] == '/') { return normalize(relPath); } else { int at = base.lastIndexOf('/'); if (at != -1) { basePath = base.substring(0, at + 1).toCharArray(); } StringBuffer buff = new StringBuffer(base.length() + relPath.length); buff.append((at != -1) ? base.substring(0, at + 1) : "/"); buff.append(relPath); return normalize(buff.toString().toCharArray()); } } /** * Get the raw-escaped current hierarchy level in the given path. * If the last namespace is a collection, the slash mark ('/') should be * ended with at the last character of the path string. * * @param path the path * @return the current hierarchy level * @throws URIException no hierarchy level */ protected char[] getRawCurrentHierPath(char[] path) throws URIException { if (_is_opaque_part) { throw new URIException(URIException.PARSING, "no hierarchy level"); } if (path == null) { throw new URIException(URIException.PARSING, "empty path"); } String buff = new String(path); int first = buff.indexOf('/'); int last = buff.lastIndexOf('/'); if (last == 0) { return rootPath; } else if (first != last && last != -1) { return buff.substring(0, last).toCharArray(); } // FIXME: it could be a document on the server side return path; } /** * Get the raw-escaped current hierarchy level. * * @return the raw-escaped current hierarchy level * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. */ public char[] getRawCurrentHierPath() throws URIException { return (_path == null) ? null : getRawCurrentHierPath(_path); } /** * Get the escaped current hierarchy level. * * @return the escaped current hierarchy level * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. */ public String getEscapedCurrentHierPath() throws URIException { char[] path = getRawCurrentHierPath(); return (path == null) ? null : new String(path); } /** * Get the current hierarchy level. * * @return the current hierarchy level * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. * @see #decode */ public String getCurrentHierPath() throws URIException { char[] path = getRawCurrentHierPath(); return (path == null) ? null : decode(path, getProtocolCharset()); } /** * Get the level above the this hierarchy level. * * @return the raw above hierarchy level * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. */ public char[] getRawAboveHierPath() throws URIException { char[] path = getRawCurrentHierPath(); return (path == null) ? null : getRawCurrentHierPath(path); } /** * Get the level above the this hierarchy level. * * @return the raw above hierarchy level * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. */ public String getEscapedAboveHierPath() throws URIException { char[] path = getRawAboveHierPath(); return (path == null) ? null : new String(path); } /** * Get the level above the this hierarchy level. * * @return the above hierarchy level * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. * @see #decode */ public String getAboveHierPath() throws URIException { char[] path = getRawAboveHierPath(); return (path == null) ? null : decode(path, getProtocolCharset()); } /** * Get the raw-escaped path. *

     *   path          = [ abs_path | opaque_part ]
     * 

* * @return the raw-escaped path */ public char[] getRawPath() { return _is_opaque_part ? _opaque : _path; } /** * Get the escaped path. *

     *   path          = [ abs_path | opaque_part ]
     *   abs_path      = "/"  path_segments 
     *   opaque_part   = uric_no_slash *uric
     * 

* * @return the escaped path string */ public String getEscapedPath() { char[] path = getRawPath(); return (path == null) ? null : new String(path); } /** * Get the path. *

     *   path          = [ abs_path | opaque_part ]
     * 

* @return the path string * @throws URIException If {@link #decode} fails. * @see #decode */ public String getPath() throws URIException { char[] path = getRawPath(); return (path == null) ? null : decode(path, getProtocolCharset()); } /** * Get the raw-escaped basename of the path. * * @return the raw-escaped basename */ public char[] getRawName() { if (_path == null) { return null; } int at = 0; for (int i = _path.length - 1; i >= 0; i--) { if (_path[i] == '/') { at = i + 1; break; } } int len = _path.length - at; char[] basename = new char[len]; System.arraycopy(_path, at, basename, 0, len); return basename; } /** * Get the escaped basename of the path. * * @return the escaped basename string */ public String getEscapedName() { char[] basename = getRawName(); return (basename == null) ? null : new String(basename); } /** * Get the basename of the path. * * @return the basename string * @throws URIException incomplete trailing escape pattern or unsupported * character encoding * @see #decode */ public String getName() throws URIException { char[] basename = getRawName(); return (basename == null) ? null : decode(getRawName(), getProtocolCharset()); } // ----------------------------------------------------- The path and query /** * Get the raw-escaped path and query. * * @return the raw-escaped path and query */ public char[] getRawPathQuery() { if (_path == null && _query == null) { return null; } StringBuffer buff = new StringBuffer(); if (_path != null) { buff.append(_path); } if (_query != null) { buff.append('?'); buff.append(_query); } return buff.toString().toCharArray(); } /** * Get the escaped query. * * @return the escaped path and query string */ public String getEscapedPathQuery() { char[] rawPathQuery = getRawPathQuery(); return (rawPathQuery == null) ? null : new String(rawPathQuery); } /** * Get the path and query. * * @return the path and query string. * @throws URIException incomplete trailing escape pattern or unsupported * character encoding * @see #decode */ public String getPathQuery() throws URIException { char[] rawPathQuery = getRawPathQuery(); return (rawPathQuery == null) ? null : decode(rawPathQuery, getProtocolCharset()); } // -------------------------------------------------------------- The query /** * Set the raw-escaped query. * * @param escapedQuery the raw-escaped query * @throws URIException escaped query not valid */ public void setRawQuery(char[] escapedQuery) throws URIException { if (escapedQuery == null || escapedQuery.length == 0) { _query = escapedQuery; setURI(); return; } // remove the fragment identifier escapedQuery = removeFragmentIdentifier(escapedQuery); if (!validate(escapedQuery, query)) { throw new URIException(URIException.ESCAPING, "escaped query not valid"); } _query = escapedQuery; setURI(); } /** * Set the escaped query string. * * @param escapedQuery the escaped query string * @throws URIException escaped query not valid */ public void setEscapedQuery(String escapedQuery) throws URIException { if (escapedQuery == null) { _query = null; setURI(); return; } setRawQuery(escapedQuery.toCharArray()); } /** * Set the query. *

* When a query string is not misunderstood the reserved special characters * ("&", "=", "+", ",", and "$") within a query component, it is * recommended to use in encoding the whole query with this method. *

* The additional APIs for the special purpose using by the reserved * special characters used in each protocol are implemented in each protocol * classes inherited from URI. So refer to the same-named APIs * implemented in each specific protocol instance. * * @param query the query string. * @throws URIException incomplete trailing escape pattern or unsupported * character encoding * @see #encode */ public void setQuery(String query) throws URIException { if (query == null || query.length() == 0) { _query = (query == null) ? null : query.toCharArray(); setURI(); return; } setRawQuery(encode(query, allowed_query, getProtocolCharset())); } /** * Get the raw-escaped query. * * @return the raw-escaped query */ public char[] getRawQuery() { return _query; } /** * Get the escaped query. * * @return the escaped query string */ public String getEscapedQuery() { return (_query == null) ? null : new String(_query); } /** * Get the query. * * @return the query string. * @throws URIException incomplete trailing escape pattern or unsupported * character encoding * @see #decode */ public String getQuery() throws URIException { return (_query == null) ? null : decode(_query, getProtocolCharset()); } // ----------------------------------------------------------- The fragment /** * Set the raw-escaped fragment. * * @param escapedFragment the raw-escaped fragment * @throws URIException escaped fragment not valid */ public void setRawFragment(char[] escapedFragment) throws URIException { if (escapedFragment == null || escapedFragment.length == 0) { _fragment = escapedFragment; hash = 0; return; } if (!validate(escapedFragment, fragment)) { throw new URIException(URIException.ESCAPING, "escaped fragment not valid"); } _fragment = escapedFragment; hash = 0; } /** * Set the escaped fragment string. * * @param escapedFragment the escaped fragment string * @throws URIException escaped fragment not valid */ public void setEscapedFragment(String escapedFragment) throws URIException { if (escapedFragment == null) { _fragment = null; hash = 0; return; } setRawFragment(escapedFragment.toCharArray()); } /** * Set the fragment. * * @param fragment the fragment string. * @throws URIException If an error occurs. */ public void setFragment(String fragment) throws URIException { if (fragment == null || fragment.length() == 0) { _fragment = (fragment == null) ? null : fragment.toCharArray(); hash = 0; return; } _fragment = encode(fragment, allowed_fragment, getProtocolCharset()); hash = 0; } /** * Get the raw-escaped fragment. *

* The optional fragment identifier is not part of a URI, but is often used * in conjunction with a URI. *

* The format and interpretation of fragment identifiers is dependent on * the media type [RFC2046] of the retrieval result. *

* A fragment identifier is only meaningful when a URI reference is * intended for retrieval and the result of that retrieval is a document * for which the identified fragment is consistently defined. * * @return the raw-escaped fragment */ public char[] getRawFragment() { return _fragment; } /** * Get the escaped fragment. * * @return the escaped fragment string */ public String getEscapedFragment() { return (_fragment == null) ? null : new String(_fragment); } /** * Get the fragment. * * @return the fragment string * @throws URIException incomplete trailing escape pattern or unsupported * character encoding * @see #decode */ public String getFragment() throws URIException { return (_fragment == null) ? null : decode(_fragment, getProtocolCharset()); } // ------------------------------------------------------------- Utilities /** * Remove the fragment identifier of the given component. * * @param component the component that a fragment may be included * @return the component that the fragment identifier is removed */ protected char[] removeFragmentIdentifier(char[] component) { if (component == null) { return null; } int lastIndex = new String(component).indexOf('#'); if (lastIndex != -1) { component = new String(component).substring(0, lastIndex).toCharArray(); } return component; } /** * Normalize the given hier path part. * *

Algorithm taken from URI reference parser at * http://www.apache.org/~fielding/uri/rev-2002/issues.html. * * @param path the path to normalize * @return the normalized path * @throws URIException no more higher path level to be normalized */ protected char[] normalize(char[] path) throws URIException { if (path == null) { return null; } String normalized = new String(path); // If the buffer begins with "./" or "../", the "." or ".." is removed. if (normalized.startsWith("./")) { normalized = normalized.substring(1); } else if (normalized.startsWith("../")) { normalized = normalized.substring(2); } else if (normalized.startsWith("..")) { normalized = normalized.substring(2); } // All occurrences of "/./" in the buffer are replaced with "/" int index = -1; while ((index = normalized.indexOf("/./")) != -1) { normalized = normalized.substring(0, index) + normalized.substring(index + 2); } // If the buffer ends with "/.", the "." is removed. if (normalized.endsWith("/.")) { normalized = normalized.substring(0, normalized.length() - 1); } int startIndex = 0; // All occurrences of "//../" in the buffer, where ".." // and are complete path segments, are iteratively replaced // with "/" in order from left to right until no matching pattern remains. // If the buffer ends with "//..", that is also replaced // with "/". Note that may be empty. while ((index = normalized.indexOf("/../", startIndex)) != -1) { int slashIndex = normalized.lastIndexOf('/', index - 1); if (slashIndex >= 0) { normalized = normalized.substring(0, slashIndex) + normalized.substring(index + 3); } else { startIndex = index + 3; } } if (normalized.endsWith("/..")) { int slashIndex = normalized.lastIndexOf('/', normalized.length() - 4); if (slashIndex >= 0) { normalized = normalized.substring(0, slashIndex + 1); } } // All prefixes of "/../" in the buffer, where ".." // and are complete path segments, are iteratively replaced // with "/" in order from left to right until no matching pattern remains. // If the buffer ends with "/..", that is also replaced // with "/". Note that may be empty. while ((index = normalized.indexOf("/../")) != -1) { int slashIndex = normalized.lastIndexOf('/', index - 1); if (slashIndex >= 0) { break; } else { normalized = normalized.substring(index + 3); } } if (normalized.endsWith("/..")) { int slashIndex = normalized.lastIndexOf('/', normalized.length() - 4); if (slashIndex < 0) { normalized = "/"; } } return normalized.toCharArray(); } /** * Normalizes the path part of this URI. Normalization is only meant to be performed on * URIs with an absolute path. Calling this method on a relative path URI will have no * effect. * * @throws URIException no more higher path level to be normalized * * @see #isAbsPath() */ public void normalize() throws URIException { if (isAbsPath()) { _path = normalize(_path); setURI(); } } /** * Test if the first array is equal to the second array. * * @param first the first character array * @param second the second character array * @return true if they're equal */ protected boolean equals(char[] first, char[] second) { if (first == null && second == null) { return true; } if (first == null || second == null) { return false; } if (first.length != second.length) { return false; } for (int i = 0; i < first.length; i++) { if (first[i] != second[i]) { return false; } } return true; } /** * Test an object if this URI is equal to another. * * @param obj an object to compare * @return true if two URI objects are equal */ public boolean equals(Object obj) { // normalize and test each components if (obj == this) { return true; } if (!(obj instanceof URI)) { return false; } URI another = (URI) obj; // scheme if (!equals(_scheme, another._scheme)) { return false; } // is_opaque_part or is_hier_part? and opaque if (!equals(_opaque, another._opaque)) { return false; } // is_hier_part // has_authority if (!equals(_authority, another._authority)) { return false; } // path if (!equals(_path, another._path)) { return false; } // has_query if (!equals(_query, another._query)) { return false; } // has_fragment? should be careful of the only fragment case. if (!equals(_fragment, another._fragment)) { return false; } return true; } // ---------------------------------------------------------- Serialization /** * Write the content of this URI. * * @param oos the object-output stream * @throws IOException If an IO problem occurs. */ private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); } /** * Read a URI. * * @param ois the object-input stream * @throws ClassNotFoundException If one of the classes specified in the * input stream cannot be found. * @throws IOException If an IO problem occurs. */ private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); } // -------------------------------------------------------------- Hash code /** * Return a hash code for this URI. * * @return a has code value for this URI */ public int hashCode() { if (hash == 0) { char[] c = _uri; if (c != null) { for (int i = 0, len = c.length; i < len; i++) { hash = 31 * hash + c[i]; } } c = _fragment; if (c != null) { for (int i = 0, len = c.length; i < len; i++) { hash = 31 * hash + c[i]; } } } return hash; } // ------------------------------------------------------------- Comparison /** * Compare this URI to another object. * * @param obj the object to be compared. * @return 0, if it's same, * -1, if failed, first being compared with in the authority component * @throws ClassCastException not URI argument */ public int compareTo(Object obj) throws ClassCastException { URI another = (URI) obj; if (!equals(_authority, another.getRawAuthority())) { return -1; } return toString().compareTo(another.toString()); } // ------------------------------------------------------------------ Clone /** * Create and return a copy of this object, the URI-reference containing * the userinfo component. Notice that the whole URI-reference including * the userinfo component counld not be gotten as a String. *

* To copy the identical URI object including the userinfo * component, it should be used. * * @return a clone of this instance */ public synchronized Object clone() throws CloneNotSupportedException { URI instance = (URI) super.clone(); instance._uri = _uri; instance._scheme = _scheme; instance._opaque = _opaque; instance._authority = _authority; instance._userinfo = _userinfo; instance._host = _host; instance._port = _port; instance._path = _path; instance._query = _query; instance._fragment = _fragment; // the charset to do escape encoding for this instance instance.protocolCharset = protocolCharset; // flags instance._is_hier_part = _is_hier_part; instance._is_opaque_part = _is_opaque_part; instance._is_net_path = _is_net_path; instance._is_abs_path = _is_abs_path; instance._is_rel_path = _is_rel_path; instance._is_reg_name = _is_reg_name; instance._is_server = _is_server; instance._is_hostname = _is_hostname; instance._is_IPv4address = _is_IPv4address; instance._is_IPv6reference = _is_IPv6reference; return instance; } // ------------------------------------------------------------ Get the URI /** * It can be gotten the URI character sequence. It's raw-escaped. * For the purpose of the protocol to be transported, it will be useful. *

* It is clearly unwise to use a URL that contains a password which is * intended to be secret. In particular, the use of a password within * the 'userinfo' component of a URL is strongly disrecommended except * in those rare cases where the 'password' parameter is intended to be * public. *

* When you want to get each part of the userinfo, you need to use the * specific methods in the specific URL. It depends on the specific URL. * * @return the URI character sequence */ public char[] getRawURI() { return _uri; } /** * It can be gotten the URI character sequence. It's escaped. * For the purpose of the protocol to be transported, it will be useful. * * @return the escaped URI string */ public String getEscapedURI() { return (_uri == null) ? null : new String(_uri); } /** * It can be gotten the URI character sequence. * * @return the original URI string * @throws URIException incomplete trailing escape pattern or unsupported * character encoding * @see #decode */ public String getURI() throws URIException { return (_uri == null) ? null : decode(_uri, getProtocolCharset()); } /** * Get the URI reference character sequence. * * @return the URI reference character sequence */ public char[] getRawURIReference() { if (_fragment == null) { return _uri; } if (_uri == null) { return _fragment; } // if _uri != null && _fragment != null String uriReference = new String(_uri) + "#" + new String(_fragment); return uriReference.toCharArray(); } /** * Get the escaped URI reference string. * * @return the escaped URI reference string */ public String getEscapedURIReference() { char[] uriReference = getRawURIReference(); return (uriReference == null) ? null : new String(uriReference); } /** * Get the original URI reference string. * * @return the original URI reference string * @throws URIException If {@link #decode} fails. */ public String getURIReference() throws URIException { char[] uriReference = getRawURIReference(); return (uriReference == null) ? null : decode(uriReference, getProtocolCharset()); } /** * Get the escaped URI string. *

* On the document, the URI-reference form is only used without the userinfo * component like http://jakarta.apache.org/ by the security reason. * But the URI-reference form with the userinfo component could be parsed. *

* In other words, this URI and any its subclasses must not expose the * URI-reference expression with the userinfo component like * http://user:password@hostport/restricted_zone.
* It means that the API client programmer should extract each user and * password to access manually. Probably it will be supported in the each * subclass, however, not a whole URI-reference expression. * * @return the escaped URI string * @see #clone() */ public String toString() { return getEscapedURI(); } // ------------------------------------------------------------ Inner class /** * The charset-changed normal operation to represent to be required to * alert to user the fact the default charset is changed. */ public static class DefaultCharsetChanged extends RuntimeException { // ------------------------------------------------------- constructors /** * The constructor with a reason string and its code arguments. * * @param reasonCode the reason code * @param reason the reason */ public DefaultCharsetChanged(int reasonCode, String reason) { super(reason); this.reason = reason; this.reasonCode = reasonCode; } // ---------------------------------------------------------- constants /** No specified reason code. */ public static final int UNKNOWN = 0; /** Protocol charset changed. */ public static final int PROTOCOL_CHARSET = 1; /** Document charset changed. */ public static final int DOCUMENT_CHARSET = 2; // ------------------------------------------------- instance variables /** The reason code. */ private int reasonCode; /** The reason message. */ private String reason; // ------------------------------------------------------------ methods /** * Get the reason code. * * @return the reason code */ public int getReasonCode() { return reasonCode; } /** * Get the reason message. * * @return the reason message */ public String getReason() { return reason; } } /** * A mapping to determine the (somewhat arbitrarily) preferred charset for a * given locale. Supports all locales recognized in JDK 1.1. *

* The distribution of this class is Servlets.com. It was originally * written by Jason Hunter [jhunter at acm.org] and used by with permission. */ public static class LocaleToCharsetMap { /** A mapping of language code to charset */ private static final Hashtable LOCALE_TO_CHARSET_MAP; static { LOCALE_TO_CHARSET_MAP = new Hashtable(); LOCALE_TO_CHARSET_MAP.put("ar", "ISO-8859-6"); LOCALE_TO_CHARSET_MAP.put("be", "ISO-8859-5"); LOCALE_TO_CHARSET_MAP.put("bg", "ISO-8859-5"); LOCALE_TO_CHARSET_MAP.put("ca", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("cs", "ISO-8859-2"); LOCALE_TO_CHARSET_MAP.put("da", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("de", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("el", "ISO-8859-7"); LOCALE_TO_CHARSET_MAP.put("en", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("es", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("et", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("fi", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("fr", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("hr", "ISO-8859-2"); LOCALE_TO_CHARSET_MAP.put("hu", "ISO-8859-2"); LOCALE_TO_CHARSET_MAP.put("is", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("it", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("iw", "ISO-8859-8"); LOCALE_TO_CHARSET_MAP.put("ja", "Shift_JIS"); LOCALE_TO_CHARSET_MAP.put("ko", "EUC-KR"); LOCALE_TO_CHARSET_MAP.put("lt", "ISO-8859-2"); LOCALE_TO_CHARSET_MAP.put("lv", "ISO-8859-2"); LOCALE_TO_CHARSET_MAP.put("mk", "ISO-8859-5"); LOCALE_TO_CHARSET_MAP.put("nl", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("no", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("pl", "ISO-8859-2"); LOCALE_TO_CHARSET_MAP.put("pt", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("ro", "ISO-8859-2"); LOCALE_TO_CHARSET_MAP.put("ru", "ISO-8859-5"); LOCALE_TO_CHARSET_MAP.put("sh", "ISO-8859-5"); LOCALE_TO_CHARSET_MAP.put("sk", "ISO-8859-2"); LOCALE_TO_CHARSET_MAP.put("sl", "ISO-8859-2"); LOCALE_TO_CHARSET_MAP.put("sq", "ISO-8859-2"); LOCALE_TO_CHARSET_MAP.put("sr", "ISO-8859-5"); LOCALE_TO_CHARSET_MAP.put("sv", "ISO-8859-1"); LOCALE_TO_CHARSET_MAP.put("tr", "ISO-8859-9"); LOCALE_TO_CHARSET_MAP.put("uk", "ISO-8859-5"); LOCALE_TO_CHARSET_MAP.put("zh", "GB2312"); LOCALE_TO_CHARSET_MAP.put("zh_TW", "Big5"); } /** * Get the preferred charset for the given locale. * * @param locale the locale * @return the preferred charset or null if the locale is not * recognized. */ public static String getCharset(Locale locale) { // try for an full name match (may include country) String charset = (String) LOCALE_TO_CHARSET_MAP.get(locale.toString()); if (charset != null) { return charset; } // if a full name didn't match, try just the language charset = (String) LOCALE_TO_CHARSET_MAP.get(locale.getLanguage()); return charset; // may be null } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/URIException.java100644 0 0 11072 10661532626 25115 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/URIException.java,v 1.12 2004/09/30 18:53:20 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * The URI parsing and escape encoding exception. * * @author Sung-Gu * @author Oleg Kalnichevski * @version $Revision: 480424 $ $Date: 2002/03/14 15:14:01 */ public class URIException extends HttpException { // ----------------------------------------------------------- constructors /** * Default constructor. */ public URIException() { } /** * The constructor with a reason code argument. * * @param reasonCode the reason code */ public URIException(int reasonCode) { this.reasonCode = reasonCode; } /** * The constructor with a reason string and its code arguments. * * @param reasonCode the reason code * @param reason the reason */ public URIException(int reasonCode, String reason) { super(reason); // for backward compatibility of Throwable this.reason = reason; this.reasonCode = reasonCode; } /** * The constructor with a reason string argument. * * @param reason the reason */ public URIException(String reason) { super(reason); // for backward compatibility of Throwable this.reason = reason; this.reasonCode = UNKNOWN; } // -------------------------------------------------------------- constants /** * No specified reason code. */ public static final int UNKNOWN = 0; /** * The URI parsing error. */ public static final int PARSING = 1; /** * The unsupported character encoding. */ public static final int UNSUPPORTED_ENCODING = 2; /** * The URI escape encoding and decoding error. */ public static final int ESCAPING = 3; /** * The DNS punycode encoding or decoding error. */ public static final int PUNYCODE = 4; // ------------------------------------------------------------- properties /** * The reason code. */ protected int reasonCode; /** * The reason message. */ protected String reason; // ---------------------------------------------------------------- methods /** * Get the reason code. * * @return the reason code */ public int getReasonCode() { return reasonCode; } /** * Set the reason code. * * @param reasonCode the reason code * * @deprecated Callers should set the reason code as a parameter to the * constructor. */ public void setReasonCode(int reasonCode) { this.reasonCode = reasonCode; } /** * Get the reason message. * * @return the reason message * * @deprecated You should instead call {@link #getMessage()}. */ public String getReason() { return reason; } /** * Set the reason message. * * @param reason the reason message * * @deprecated Callers should instead set this via a parameter to the constructor. */ public void setReason(String reason) { this.reason = reason; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/UsernamePasswordCredentials.java100644 0 0 14436 10661532626 30266 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/UsernamePasswordCredentials.java,v 1.14 2004/04/18 23:51:35 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.util.LangUtils; /** *

Username and password {@link Credentials}.

* * @author Remy Maucherat * @author Sean C. Sullivan * @author Mike Bowler * @author Oleg Kalnichevski * * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * */ public class UsernamePasswordCredentials implements Credentials { // ----------------------------------------------------------- Constructors /** * Default constructor. * * @deprecated Do not use. Null user name no longer allowed */ public UsernamePasswordCredentials() { super(); } /** * The constructor with the username and password combined string argument. * * @param usernamePassword the username:password formed string * @see #toString */ public UsernamePasswordCredentials(String usernamePassword) { super(); if (usernamePassword == null) { throw new IllegalArgumentException("Username:password string may not be null"); } int atColon = usernamePassword.indexOf(':'); if (atColon >= 0) { this.userName = usernamePassword.substring(0, atColon); this.password = usernamePassword.substring(atColon + 1); } else { this.userName = usernamePassword; } } /** * The constructor with the username and password arguments. * * @param userName the user name * @param password the password */ public UsernamePasswordCredentials(String userName, String password) { super(); if (userName == null) { throw new IllegalArgumentException("Username may not be null"); } this.userName = userName; this.password = password; } // ----------------------------------------------------- Instance Variables /** * User name. */ private String userName; /** * Password. */ private String password; // ------------------------------------------------------------- Properties /** * User name property setter. User name may not be null. * * @param userName * @see #getUserName() * * @deprecated Do not use. The UsernamePasswordCredentials objects should be immutable */ public void setUserName(String userName) { if (userName == null) { throw new IllegalArgumentException("Username may not be null"); } this.userName = userName; } /** * User name property getter. * * @return the userName * @see #setUserName(String) */ public String getUserName() { return userName; } /** * Password property setter. * * @param password * @see #getPassword() * * @deprecated Do not use. The UsernamePasswordCredentials objects should be immutable */ public void setPassword(String password) { this.password = password; } /** * Password property getter. * * @return the password * @see #setPassword(String) */ public String getPassword() { return password; } /** * Get this object string. * * @return the username:password formed string */ public String toString() { StringBuffer result = new StringBuffer(); result.append(this.userName); result.append(":"); result.append((this.password == null) ? "null" : this.password); return result.toString(); } /** * Does a hash of both user name and password. * * @return The hash code including user name and password. */ public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.userName); hash = LangUtils.hashCode(hash, this.password); return hash; } /** * These credentials are assumed equal if the username and password are the * same. * * @param o The other object to compare with. * * @return true if the object is equivalent. */ public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; // note - to allow for sub-classing, this checks that class is the same // rather than do "instanceof". if (this.getClass().equals(o.getClass())) { UsernamePasswordCredentials that = (UsernamePasswordCredentials) o; if (LangUtils.equals(this.userName, that.userName) && LangUtils.equals(this.password, that.password) ) { return true; } } return false; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/Wire.java100644 0 0 12230 10661532626 23502 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Wire.java,v 1.9 2004/06/24 21:39:52 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InputStream; import java.io.ByteArrayInputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Logs data to the wire LOG. * * @author Oleg Kalnichevski * * @since 2.0beta1 */ class Wire { public static Wire HEADER_WIRE = new Wire(LogFactory.getLog("httpclient.wire.header")); public static Wire CONTENT_WIRE = new Wire(LogFactory.getLog("httpclient.wire.content")); /** Log for any wire messages. */ private Log log; private Wire(Log log) { this.log = log; } private void wire(String header, InputStream instream) throws IOException { StringBuffer buffer = new StringBuffer(); int ch; while ((ch = instream.read()) != -1) { if (ch == 13) { buffer.append("[\\r]"); } else if (ch == 10) { buffer.append("[\\n]\""); buffer.insert(0, "\""); buffer.insert(0, header); log.debug(buffer.toString()); buffer.setLength(0); } else if ((ch < 32) || (ch > 127)) { buffer.append("[0x"); buffer.append(Integer.toHexString(ch)); buffer.append("]"); } else { buffer.append((char) ch); } } if (buffer.length() > 0) { buffer.append("\""); buffer.insert(0, "\""); buffer.insert(0, header); log.debug(buffer.toString()); } } public boolean enabled() { return log.isDebugEnabled(); } public void output(InputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output may not be null"); } wire(">> ", outstream); } public void input(InputStream instream) throws IOException { if (instream == null) { throw new IllegalArgumentException("Input may not be null"); } wire("<< ", instream); } public void output(byte[] b, int off, int len) throws IOException { if (b == null) { throw new IllegalArgumentException("Output may not be null"); } wire(">> ", new ByteArrayInputStream(b, off, len)); } public void input(byte[] b, int off, int len) throws IOException { if (b == null) { throw new IllegalArgumentException("Input may not be null"); } wire("<< ", new ByteArrayInputStream(b, off, len)); } public void output(byte[] b) throws IOException { if (b == null) { throw new IllegalArgumentException("Output may not be null"); } wire(">> ", new ByteArrayInputStream(b)); } public void input(byte[] b) throws IOException { if (b == null) { throw new IllegalArgumentException("Input may not be null"); } wire("<< ", new ByteArrayInputStream(b)); } public void output(int b) throws IOException { output(new byte[] {(byte) b}); } public void input(int b) throws IOException { input(new byte[] {(byte) b}); } public void output(final String s) throws IOException { if (s == null) { throw new IllegalArgumentException("Output may not be null"); } output(s.getBytes()); } public void input(final String s) throws IOException { if (s == null) { throw new IllegalArgumentException("Input may not be null"); } input(s.getBytes()); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/WireLogInputStream.java100644 0 0 5777 10661532626 26342 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/WireLogInputStream.java,v 1.15 2004/06/24 21:39:52 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * Logs all data read to the wire LOG. * * @author Ortwin Gl�ck * @author Mike Bowler * @author Oleg Kalnichevski * * @since 2.0 */ class WireLogInputStream extends FilterInputStream { /** Original input stream. */ private InputStream in; /** The wire log to use for writing. */ private Wire wire; /** * Create an instance that wraps the specified input stream. * @param in The input stream. * @param wire The wire log to use. */ public WireLogInputStream(InputStream in, Wire wire) { super(in); this.in = in; this.wire = wire; } /** * * @see java.io.InputStream#read(byte[], int, int) */ public int read(byte[] b, int off, int len) throws IOException { int l = this.in.read(b, off, len); if (l > 0) { wire.input(b, off, l); } return l; } /** * * @see java.io.InputStream#read() */ public int read() throws IOException { int l = this.in.read(); if (l > 0) { wire.input(l); } return l; } /** * * @see java.io.InputStream#read(byte[]) */ public int read(byte[] b) throws IOException { int l = this.in.read(b); if (l > 0) { wire.input(b, 0, l); } return l; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/WireLogOutputStream.java100644 0 0 5406 10661532626 26530 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/WireLogOutputStream.java,v 1.7 2004/06/24 21:39:52 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Logs all data written to the wire LOG. * * @author Oleg Kalnichevski * * @since 2.0beta1 */ class WireLogOutputStream extends FilterOutputStream { /** Original input stream. */ private OutputStream out; /** The wire log to use. */ private Wire wire; /** * Create an instance that wraps the specified output stream. * @param out The output stream. * @param wire The Wire log to use. */ public WireLogOutputStream(OutputStream out, Wire wire) { super(out); this.out = out; this.wire = wire; } /** * * @see java.io.OutputStream#write(byte[], int, int) */ public void write(byte[] b, int off, int len) throws IOException { this.out.write(b, off, len); wire.output(b, off, len); } /** * * @see java.io.OutputStream#write() */ public void write(int b) throws IOException { this.out.write(b); wire.output(b); } /** * * @see java.io.OutputStream#write(byte[]) */ public void write(byte[] b) throws IOException { this.out.write(b); wire.output(b); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/AuthChallengeException.java100644 0 0 5021 10661532626 30100 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthChallengeException.java,v 1.2 2004/04/18 23:51:36 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; /** * Signals a failure processing authentication challenge * * @author Oleg Kalnichevski * * @since 3.0 */ public class AuthChallengeException extends AuthenticationException { /** * Creates a new AuthChallengeException with a null detail message. */ public AuthChallengeException() { super(); } /** * Creates a new AuthChallengeException with the specified message. * * @param message the exception detail message */ public AuthChallengeException(String message) { super(message); } /** * Creates a new AuthChallengeException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public AuthChallengeException(String message, Throwable cause) { super(message, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/AuthChallengeParser.java100644 0 0 11742 10661532627 27426 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthChallengeParser.java,v 1.10 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.util.ParameterParser; /** * This class provides utility methods for parsing HTTP www and proxy authentication * challenges. * * @author Oleg Kalnichevski * * @since 2.0beta1 */ public final class AuthChallengeParser { /** * Extracts authentication scheme from the given authentication * challenge. * * @param challengeStr the authentication challenge string * @return authentication scheme * * @throws MalformedChallengeException when the authentication challenge string * is malformed * * @since 2.0beta1 */ public static String extractScheme(final String challengeStr) throws MalformedChallengeException { if (challengeStr == null) { throw new IllegalArgumentException("Challenge may not be null"); } int idx = challengeStr.indexOf(' '); String s = null; if (idx == -1) { s = challengeStr; } else { s = challengeStr.substring(0, idx); } if (s.equals("")) { throw new MalformedChallengeException("Invalid challenge: " + challengeStr); } return s.toLowerCase(); } /** * Extracts a map of challenge parameters from an authentication challenge. * Keys in the map are lower-cased * * @param challengeStr the authentication challenge string * @return a map of authentication challenge parameters * @throws MalformedChallengeException when the authentication challenge string * is malformed * * @since 2.0beta1 */ public static Map extractParams(final String challengeStr) throws MalformedChallengeException { if (challengeStr == null) { throw new IllegalArgumentException("Challenge may not be null"); } int idx = challengeStr.indexOf(' '); if (idx == -1) { throw new MalformedChallengeException("Invalid challenge: " + challengeStr); } Map map = new HashMap(); ParameterParser parser = new ParameterParser(); List params = parser.parse( challengeStr.substring(idx + 1, challengeStr.length()), ','); for (int i = 0; i < params.size(); i++) { NameValuePair param = (NameValuePair) params.get(i); map.put(param.getName().toLowerCase(), param.getValue()); } return map; } /** * Extracts a map of challenges ordered by authentication scheme name * * @param headers the array of authorization challenges * @return a map of authorization challenges * * @throws MalformedChallengeException if any of challenge strings * is malformed * * @since 3.0 */ public static Map parseChallenges(final Header[] headers) throws MalformedChallengeException { if (headers == null) { throw new IllegalArgumentException("Array of challenges may not be null"); } String challenge = null; Map challengemap = new HashMap(headers.length); for (int i = 0; i < headers.length; i++) { challenge = headers[i].getValue(); String s = AuthChallengeParser.extractScheme(challenge); challengemap.put(s, challenge); } return challengemap; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/AuthChallengeProcessor.java100644 0 0 14651 10661532626 30152 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthChallengeProcessor.java,v 1.2 2004/04/18 23:51:36 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.apache.commons.httpclient.params.HttpParams; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class provides utility methods for processing HTTP www and proxy authentication * challenges. * * @author Oleg Kalnichevski * * @since 3.0 */ public final class AuthChallengeProcessor { private static final Log LOG = LogFactory.getLog(AuthChallengeProcessor.class); private HttpParams params = null; /** * Creates an authentication challenge processor with the given {@link HttpParams HTTP * parameters} * * @param params the {@link HttpParams HTTP parameters} used by this processor */ public AuthChallengeProcessor(final HttpParams params) { super(); if (params == null) { throw new IllegalArgumentException("Parameter collection may not be null"); } this.params = params; } /** * Determines the preferred {@link AuthScheme authentication scheme} that can be used * to respond to the given collection of challenges. * * @param challenges the collection of authentication challenges * * @return the preferred {@link AuthScheme authentication scheme} * * @throws AuthChallengeException if the preferred authentication scheme * cannot be determined or is not supported */ public AuthScheme selectAuthScheme(final Map challenges) throws AuthChallengeException { if (challenges == null) { throw new IllegalArgumentException("Challenge map may not be null"); } Collection authPrefs = (Collection) this.params.getParameter( AuthPolicy.AUTH_SCHEME_PRIORITY); if (authPrefs == null || authPrefs.isEmpty()) { authPrefs = AuthPolicy.getDefaultAuthPrefs(); } if (LOG.isDebugEnabled()) { LOG.debug("Supported authentication schemes in the order of preference: " + authPrefs); } AuthScheme authscheme = null; String challenge = null; Iterator item = authPrefs.iterator(); while (item.hasNext()) { String id = (String) item.next(); challenge = (String) challenges.get(id.toLowerCase()); if (challenge != null) { if (LOG.isInfoEnabled()) { LOG.info(id + " authentication scheme selected"); } try { authscheme = AuthPolicy.getAuthScheme(id); } catch (IllegalStateException e) { throw new AuthChallengeException(e.getMessage()); } break; } else { if (LOG.isDebugEnabled()) { LOG.debug("Challenge for " + id + " authentication scheme not available"); // Try again } } } if (authscheme == null) { // If none selected, something is wrong throw new AuthChallengeException( "Unable to respond to any of these challenges: " + challenges); } return authscheme; } /** * Processes the given collection of challenges and updates the * {@link AuthState state} of the authentication process. * * @param challenges the collection of authentication challenges * * @return the {@link AuthScheme authentication scheme} used to * process the challenge * * @throws AuthChallengeException if authentication challenges cannot be * successfully processed or the preferred authentication scheme cannot * be determined */ public AuthScheme processChallenge(final AuthState state, final Map challenges) throws MalformedChallengeException, AuthenticationException { if (state == null) { throw new IllegalArgumentException("Authentication state may not be null"); } if (challenges == null) { throw new IllegalArgumentException("Challenge map may not be null"); } if (state.isPreemptive() || state.getAuthScheme() == null) { // Authentication not attempted before state.setAuthScheme(selectAuthScheme(challenges)); } AuthScheme authscheme = state.getAuthScheme(); String id = authscheme.getSchemeName(); if (LOG.isDebugEnabled()) { LOG.debug("Using authentication scheme: " + id); } String challenge = (String) challenges.get(id.toLowerCase()); if (challenge == null) { throw new AuthenticationException(id + " authorization challenge expected, but not found"); } authscheme.processChallenge(challenge); LOG.debug("Authorization challenge processed"); return authscheme; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/AuthPolicy.java100644 0 0 16452 10661532626 25630 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthPolicy.java,v 1.6 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Authentication policy class. The Authentication policy provides corresponding * authentication scheme interfrace for a given type of authorization challenge. *

The following specifications are provided: *

    *
  • Basic: Basic authentication scheme as defined in RFC2617 * (considered inherently insecure, but most widely supported) *
  • Digest: Digest authentication scheme as defined in RFC2617 *
  • NTLM: The NTLM scheme is a proprietary Microsoft Windows * Authentication protocol (considered to be the most secure among * currently supported authentication schemes) *
* * @author Oleg Kalnichevski * * @version $Revision: 480424 $ * @since 3.0 */ public abstract class AuthPolicy { private static final HashMap SCHEMES = new HashMap(); private static final ArrayList SCHEME_LIST = new ArrayList(); /** * The key used to look up the list of IDs of supported {@link AuthScheme * authentication schemes} in their order of preference. The scheme IDs are * stored in a {@link java.util.Collection} as {@link java.lang.String}s. * *

* If several schemes are returned in the WWW-Authenticate * or Proxy-Authenticate header, this parameter defines which * {@link AuthScheme authentication schemes} takes precedence over others. * The first item in the collection represents the most preferred * {@link AuthScheme authentication scheme}, the last item represents the ID * of the least preferred one. *

* * @see org.apache.commons.httpclient.params.DefaultHttpParams */ public static final String AUTH_SCHEME_PRIORITY = "http.auth.scheme-priority"; /** * The NTLM scheme is a proprietary Microsoft Windows Authentication * protocol (considered to be the most secure among currently supported * authentication schemes). */ public static final String NTLM = "NTLM"; /** * Digest authentication scheme as defined in RFC2617. */ public static final String DIGEST = "Digest"; /** * Basic authentication scheme as defined in RFC2617 (considered inherently * insecure, but most widely supported) */ public static final String BASIC = "Basic"; static { AuthPolicy.registerAuthScheme(NTLM, NTLMScheme.class); AuthPolicy.registerAuthScheme(DIGEST, DigestScheme.class); AuthPolicy.registerAuthScheme(BASIC, BasicScheme.class); } /** Log object. */ protected static final Log LOG = LogFactory.getLog(AuthPolicy.class); /** * Registers a class implementing an {@link AuthScheme authentication scheme} with * the given identifier. If a class with the given ID already exists it will be overridden. * This ID is the same one used to retrieve the {@link AuthScheme authentication scheme} * from {@link #getAuthScheme(String)}. * *

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

* * @param id the identifier for this scheme * @param clazz the class to register * * @see #getAuthScheme(String) * @see #AUTH_SCHEME_PRIORITY */ public static synchronized void registerAuthScheme(final String id, Class clazz) { if (id == null) { throw new IllegalArgumentException("Id may not be null"); } if (clazz == null) { throw new IllegalArgumentException("Authentication scheme class may not be null"); } SCHEMES.put(id.toLowerCase(), clazz); SCHEME_LIST.add(id.toLowerCase()); } /** * Unregisters the class implementing an {@link AuthScheme authentication scheme} with * the given ID. * * @param id the ID of the class to unregister */ public static synchronized void unregisterAuthScheme(final String id) { if (id == null) { throw new IllegalArgumentException("Id may not be null"); } SCHEMES.remove(id.toLowerCase()); SCHEME_LIST.remove(id.toLowerCase()); } /** * Gets the {@link AuthScheme authentication scheme} with the given ID. * * @param id the {@link AuthScheme authentication scheme} ID * * @return {@link AuthScheme authentication scheme} * * @throws IllegalStateException if a scheme with the ID cannot be found */ public static synchronized AuthScheme getAuthScheme(final String id) throws IllegalStateException { if (id == null) { throw new IllegalArgumentException("Id may not be null"); } Class clazz = (Class)SCHEMES.get(id.toLowerCase()); if (clazz != null) { try { return (AuthScheme)clazz.newInstance(); } catch (Exception e) { LOG.error("Error initializing authentication scheme: " + id, e); throw new IllegalStateException(id + " authentication scheme implemented by " + clazz.getName() + " could not be initialized"); } } else { throw new IllegalStateException("Unsupported authentication scheme " + id); } } /** * Returns a list containing all registered {@link AuthScheme authentication * schemes} in their default order. * * @return {@link AuthScheme authentication scheme} */ public static synchronized List getDefaultAuthPrefs() { return (List)SCHEME_LIST.clone(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/AuthScheme.java100644 0 0 16365 10661532626 25600 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthScheme.java,v 1.12 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpMethod; /** *

* This interface represents an abstract challenge-response oriented * authentication scheme. *

*

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

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

*

* Authentication schemes may ignore method name and URI parameters * if they are not relevant for the given authentication mechanism *

*

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

* * @author Oleg Kalnichevski * @author Adrian Sutton * * @since 2.0beta1 */ public interface AuthScheme { /** * Processes the given challenge token. Some authentication schemes * may involve multiple challenge-response exchanges. Such schemes must be able * to maintain the state information when dealing with sequential challenges * * @param challenge the challenge string * * @since 3.0 */ void processChallenge(final String challenge) throws MalformedChallengeException; /** * Returns textual designation of the given authentication scheme. * * @return the name of the given authentication scheme */ String getSchemeName(); /** * Returns authentication parameter with the given name, if available. * * @param name The name of the parameter to be returned * * @return the parameter with the given name */ String getParameter(final String name); /** * Returns authentication realm. If the concept of an authentication * realm is not applicable to the given authentication scheme, returns * null. * * @return the authentication realm */ String getRealm(); /** * Returns a String identifying the authentication challenge. This is * used, in combination with the host and port to determine if * authorization has already been attempted or not. Schemes which * require multiple requests to complete the authentication should * return a different value for each stage in the request. * *

Additionally, the ID should take into account any changes to the * authentication challenge and return a different value when appropriate. * For example when the realm changes in basic authentication it should be * considered a different authentication attempt and a different value should * be returned.

* * @return String a String identifying the authentication challenge. The * returned value may be null. * * @deprecated no longer used */ String getID(); /** * Tests if the authentication scheme is provides authorization on a per * connection basis instead of usual per request basis * * @return true if the scheme is connection based, false * if the scheme is request based. * * @since 3.0 */ boolean isConnectionBased(); /** * Authentication process may involve a series of challenge-response exchanges. * This method tests if the authorization process has been completed, either * successfully or unsuccessfully, that is, all the required authorization * challenges have been processed in their entirety. * * @return true if the authentication process has been completed, * false otherwise. * * @since 3.0 */ boolean isComplete(); /** * @deprecated Use {@link #authenticate(Credentials, HttpMethod)} * * Produces an authorization string for the given set of {@link Credentials}, * method name and URI using the given authentication scheme in response to * the actual authorization challenge. * * @param credentials The set of credentials to be used for athentication * @param method The name of the method that requires authorization. * This parameter may be ignored, if it is irrelevant * or not applicable to the given authentication scheme * @param uri The URI for which authorization is needed. * This parameter may be ignored, if it is irrelevant or not * applicable to the given authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return the authorization string * * @see org.apache.commons.httpclient.HttpMethod#getName() * @see org.apache.commons.httpclient.HttpMethod#getPath() */ String authenticate(Credentials credentials, String method, String uri) throws AuthenticationException; /** * Produces an authorization string for the given set of {@link Credentials}. * * @param credentials The set of credentials to be used for athentication * @param method The method being authenticated * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return the authorization string * * @since 3.0 */ String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException; } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/AuthSchemeBase.java100644 0 0 6116 10661532626 26344 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthSchemeBase.java,v 1.7 2004/04/18 23:51:36 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; /** *

* Abstract authentication scheme class that implements {@link AuthScheme} * interface and provides a default contstructor. *

* @deprecated No longer used * * @author Oleg Kalnichevski */ public abstract class AuthSchemeBase implements AuthScheme { /** * Original challenge string as received from the server. */ private String challenge = null; /** * Constructor for an abstract authetication schemes. * * @param challenge authentication challenge * * @throws MalformedChallengeException is thrown if the authentication challenge * is malformed * * @deprecated Use parameterless constructor and {@link AuthScheme#processChallenge(String)} * method */ public AuthSchemeBase(final String challenge) throws MalformedChallengeException { super(); if (challenge == null) { throw new IllegalArgumentException("Challenge may not be null"); } this.challenge = challenge; } /** * @see java.lang.Object#equals(Object) */ public boolean equals(Object obj) { if (obj instanceof AuthSchemeBase) { return this.challenge.equals(((AuthSchemeBase) obj).challenge); } else { return super.equals(obj); } } /** * @see java.lang.Object#hashCode() */ public int hashCode() { return this.challenge.hashCode(); } /** * @see java.lang.Object#toString() */ public String toString() { return this.challenge; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/AuthScope.java100644 0 0 24206 10661532627 25437 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthScope.java,v 1.2 2004/06/23 06:50:25 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import org.apache.commons.httpclient.util.LangUtils; /** * The class represents an authentication scope consisting of a host name, * a port number, a realm name and an authentication scheme name which * {@link org.apache.commons.httpclient.Credentials} apply to. * * @author Oleg Kalnichevski * @author Adrian Sutton * * @since 3.0 */ public class AuthScope { /** * The null value represents any host. In the future versions of * HttpClient the use of this parameter will be discontinued. */ public static final String ANY_HOST = null; /** * The -1 value represents any port. */ public static final int ANY_PORT = -1; /** * The null value represents any realm. */ public static final String ANY_REALM = null; /** * The null value represents any authentication scheme. */ public static final String ANY_SCHEME = null; /** * Default scope matching any host, port, realm and authentication scheme. * In the future versions of HttpClient the use of this parameter will be * discontinued. */ public static final AuthScope ANY = new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, ANY_SCHEME); /** The authentication scheme the credentials apply to. */ private String scheme = null; /** The realm the credentials apply to. */ private String realm = null; /** The host the credentials apply to. */ private String host = null; /** The port the credentials apply to. */ private int port = -1; /** Creates a new credentials scope for the given * host, port, realm, and * authentication scheme. * * @param host the host the credentials apply to. May be set * to null if credenticals are applicable to * any host. * @param port the port the credentials apply to. May be set * to negative value if credenticals are applicable to * any port. * @param realm the realm the credentials apply to. May be set * to null if credenticals are applicable to * any realm. * @param scheme the authentication scheme the credentials apply to. * May be set to null if credenticals are applicable to * any authentication scheme. * * @since 3.0 */ public AuthScope(final String host, int port, final String realm, final String scheme) { this.host = (host == null) ? ANY_HOST: host.toLowerCase(); this.port = (port < 0) ? ANY_PORT: port; this.realm = (realm == null) ? ANY_REALM: realm; this.scheme = (scheme == null) ? ANY_SCHEME: scheme.toUpperCase();; } /** Creates a new credentials scope for the given * host, port, realm, and any * authentication scheme. * * @param host the host the credentials apply to. May be set * to null if credenticals are applicable to * any host. * @param port the port the credentials apply to. May be set * to negative value if credenticals are applicable to * any port. * @param realm the realm the credentials apply to. May be set * to null if credenticals are applicable to * any realm. * * @since 3.0 */ public AuthScope(final String host, int port, final String realm) { this(host, port, realm, ANY_SCHEME); } /** Creates a new credentials scope for the given * host, port, any realm name, and any * authentication scheme. * * @param host the host the credentials apply to. May be set * to null if credenticals are applicable to * any host. * @param port the port the credentials apply to. May be set * to negative value if credenticals are applicable to * any port. * * @since 3.0 */ public AuthScope(final String host, int port) { this(host, port, ANY_REALM, ANY_SCHEME); } /** * Creates a copy of the given credentials scope. * * @since 3.0 */ public AuthScope(final AuthScope authscope) { super(); if (authscope == null) { throw new IllegalArgumentException("Scope may not be null"); } this.host = authscope.getHost(); this.port = authscope.getPort(); this.realm = authscope.getRealm(); this.scheme = authscope.getScheme(); } /** * @return the host * * @since 3.0 */ public String getHost() { return this.host; } /** * @return the port * * @since 3.0 */ public int getPort() { return this.port; } /** * @return the realm name * * @since 3.0 */ public String getRealm() { return this.realm; } /** * @return the scheme type * * @since 3.0 */ public String getScheme() { return this.scheme; } /** Determines if the given parameters are equal. * * @param p1 the parameter * @param p2 the other parameter * @return boolean true if the parameters are equal, otherwise false. */ private static boolean paramsEqual(final String p1, final String p2) { if (p1 == null) { return p1 == p2; } else { return p1.equals(p2); } } /** Determines if the given parameters are equal. * * @param p1 the parameter * @param p2 the other parameter * @return boolean true if the parameters are equal, otherwise false. */ private static boolean paramsEqual(int p1, int p2) { return p1 == p2; } /** * Tests if the authentication scopes match. * * @return the match factor. Negative value signifies no match. * Non-negative signifies a match. The greater the returned value * the closer the match. * * @since 3.0 */ public int match(final AuthScope that) { int factor = 0; if (paramsEqual(this.scheme, that.scheme)) { factor += 1; } else { if (this.scheme != ANY_SCHEME && that.scheme != ANY_SCHEME) { return -1; } } if (paramsEqual(this.realm, that.realm)) { factor += 2; } else { if (this.realm != ANY_REALM && that.realm != ANY_REALM) { return -1; } } if (paramsEqual(this.port, that.port)) { factor += 4; } else { if (this.port != ANY_PORT && that.port != ANY_PORT) { return -1; } } if (paramsEqual(this.host, that.host)) { factor += 8; } else { if (this.host != ANY_HOST && that.host != ANY_HOST) { return -1; } } return factor; } /** * @see java.lang.Object#equals(Object) */ public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (!(o instanceof AuthScope)) { return super.equals(o); } AuthScope that = (AuthScope) o; return paramsEqual(this.host, that.host) && paramsEqual(this.port, that.port) && paramsEqual(this.realm, that.realm) && paramsEqual(this.scheme, that.scheme); } /** * @see java.lang.Object#toString() */ public String toString() { StringBuffer buffer = new StringBuffer(); if (this.scheme != null) { buffer.append(this.scheme.toUpperCase()); buffer.append(' '); } if (this.realm != null) { buffer.append('\''); buffer.append(this.realm); buffer.append('\''); } else { buffer.append(""); } if (this.host != null) { buffer.append('@'); buffer.append(this.host); if (this.port >= 0) { buffer.append(':'); buffer.append(this.port); } } return buffer.toString(); } /** * @see java.lang.Object#hashCode() */ public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.host); hash = LangUtils.hashCode(hash, this.port); hash = LangUtils.hashCode(hash, this.realm); hash = LangUtils.hashCode(hash, this.scheme); return hash; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/AuthState.java100644 0 0 14100 10661532626 25435 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthState.java,v 1.3 2004/11/02 19:39:16 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; /** * This class provides detailed information about the state of the * authentication process. * * @author Oleg Kalnichevski * @since 3.0 */ public class AuthState { public static final String PREEMPTIVE_AUTH_SCHEME = "basic"; /** Actual authentication scheme */ private AuthScheme authScheme = null; /** Whether an authetication challenged has been received */ private boolean authRequested = false; /** Whether the authetication challenge has been responsed to */ private boolean authAttempted = false; /** Whether preemtive authentication is attempted */ private boolean preemptive = false; /** * Default constructor. * */ public AuthState() { super(); } /** * Invalidates the authentication state by resetting its parameters. */ public void invalidate() { this.authScheme = null; this.authRequested = false; this.authAttempted = false; this.preemptive = false; } /** * Tests whether authenication challenge has been received * * @return true if authenication challenge has been received, * false otherwise */ public boolean isAuthRequested() { return this.authRequested; } /** * Sets authentication request status * * @param challengeReceived true if authenication has been requested, * false otherwise */ public void setAuthRequested(boolean challengeReceived) { this.authRequested = challengeReceived; } /** * Tests whether authenication challenge has been responsed to * * @return true if authenication challenge has been responsed to, * false otherwise */ public boolean isAuthAttempted() { return this.authAttempted; } /** * Sets authentication attempt status * * @param challengeResponded true if authenication has been attempted, * false otherwise */ public void setAuthAttempted(boolean challengeResponded) { this.authAttempted = challengeResponded; } /** * Preemptively assigns Basic authentication scheme. */ public void setPreemptive() { if (!this.preemptive) { if (this.authScheme != null) { throw new IllegalStateException("Authentication state already initialized"); } this.authScheme = AuthPolicy.getAuthScheme(PREEMPTIVE_AUTH_SCHEME); this.preemptive = true; } } /** * Tests if preemptive authentication is used. * * @return true if using the default Basic {@link AuthScheme * authentication scheme}, false otherwise. */ public boolean isPreemptive() { return this.preemptive; } /** * Assigns the given {@link AuthScheme authentication scheme}. * * @param authScheme the {@link AuthScheme authentication scheme} */ public void setAuthScheme(final AuthScheme authScheme) { if (authScheme == null) { invalidate(); return; } if (this.preemptive && !(this.authScheme.getClass().isInstance(authScheme))) { this.preemptive = false; this.authAttempted = false; } this.authScheme = authScheme; } /** * Returns the {@link AuthScheme authentication scheme}. * * @return {@link AuthScheme authentication scheme} */ public AuthScheme getAuthScheme() { return authScheme; } /** * Returns the authentication realm. * * @return the name of the authentication realm */ public String getRealm() { if (this.authScheme != null) { return this.authScheme.getRealm(); } else { return null; } } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("Auth state: auth requested ["); buffer.append(this.authRequested); buffer.append("]; auth attempted ["); buffer.append(this.authAttempted); if (this.authScheme != null) { buffer.append("]; auth scheme ["); buffer.append(this.authScheme.getSchemeName()); buffer.append("]; realm ["); buffer.append(this.authScheme.getRealm()); } buffer.append("] preemptive ["); buffer.append(this.preemptive); buffer.append("]"); return buffer.toString(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/AuthenticationException.java100644 0 0 5133 10661532626 30357 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthenticationException.java,v 1.6 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import org.apache.commons.httpclient.ProtocolException; /** * Signals a failure in authentication process * * @author Oleg Kalnichevski * * @since 2.0 */ public class AuthenticationException extends ProtocolException { /** * Creates a new AuthenticationException with a null detail message. */ public AuthenticationException() { super(); } /** * Creates a new AuthenticationException with the specified message. * * @param message the exception detail message */ public AuthenticationException(String message) { super(message); } /** * Creates a new AuthenticationException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable * * @since 3.0 */ public AuthenticationException(String message, Throwable cause) { super(message, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/BasicScheme.java100644 0 0 21365 10661532626 25714 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/BasicScheme.java,v 1.17 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.util.EncodingUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

* Basic authentication scheme as defined in RFC 2617. *

* * @author Remy Maucherat * @author Rodney Waldhoff * @author Jeff Dever * @author Ortwin Gl?ck * @author Sean C. Sullivan * @author Adrian Sutton * @author Mike Bowler * @author Oleg Kalnichevski */ public class BasicScheme extends RFC2617Scheme { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(BasicScheme.class); /** Whether the basic authentication process is complete */ private boolean complete; /** * Default constructor for the basic authetication scheme. * * @since 3.0 */ public BasicScheme() { super(); this.complete = false; } /** * Constructor for the basic authetication scheme. * * @param challenge authentication challenge * * @throws MalformedChallengeException is thrown if the authentication challenge * is malformed * * @deprecated Use parameterless constructor and {@link AuthScheme#processChallenge(String)} * method */ public BasicScheme(final String challenge) throws MalformedChallengeException { super(challenge); this.complete = true; } /** * Returns textual designation of the basic authentication scheme. * * @return basic */ public String getSchemeName() { return "basic"; } /** * Processes the Basic challenge. * * @param challenge the challenge string * * @throws MalformedChallengeException is thrown if the authentication challenge * is malformed * * @since 3.0 */ public void processChallenge(String challenge) throws MalformedChallengeException { super.processChallenge(challenge); this.complete = true; } /** * Tests if the Basic authentication process has been completed. * * @return true if Basic authorization has been processed, * false otherwise. * * @since 3.0 */ public boolean isComplete() { return this.complete; } /** * Produces basic authorization string for the given set of * {@link Credentials}. * * @param credentials The set of credentials to be used for athentication * @param method Method name is ignored by the basic authentication scheme * @param uri URI is ignored by the basic authentication scheme * @throws InvalidCredentialsException if authentication credentials * are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return a basic authorization string * * @deprecated Use {@link #authenticate(Credentials, HttpMethod)} */ public String authenticate(Credentials credentials, String method, String uri) throws AuthenticationException { LOG.trace("enter BasicScheme.authenticate(Credentials, String, String)"); UsernamePasswordCredentials usernamepassword = null; try { usernamepassword = (UsernamePasswordCredentials) credentials; } catch (ClassCastException e) { throw new InvalidCredentialsException( "Credentials cannot be used for basic authentication: " + credentials.getClass().getName()); } return BasicScheme.authenticate(usernamepassword); } /** * Returns false. Basic authentication scheme is request based. * * @return false. * * @since 3.0 */ public boolean isConnectionBased() { return false; } /** * Produces basic authorization string for the given set of {@link Credentials}. * * @param credentials The set of credentials to be used for athentication * @param method The method being authenticated * @throws InvalidCredentialsException if authentication credentials * are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return a basic authorization string * * @since 3.0 */ public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException { LOG.trace("enter BasicScheme.authenticate(Credentials, HttpMethod)"); if (method == null) { throw new IllegalArgumentException("Method may not be null"); } UsernamePasswordCredentials usernamepassword = null; try { usernamepassword = (UsernamePasswordCredentials) credentials; } catch (ClassCastException e) { throw new InvalidCredentialsException( "Credentials cannot be used for basic authentication: " + credentials.getClass().getName()); } return BasicScheme.authenticate( usernamepassword, method.getParams().getCredentialCharset()); } /** * @deprecated Use {@link #authenticate(UsernamePasswordCredentials, String)} * * Returns a basic Authorization header value for the given * {@link UsernamePasswordCredentials}. * * @param credentials The credentials to encode. * * @return a basic authorization string */ public static String authenticate(UsernamePasswordCredentials credentials) { return authenticate(credentials, "ISO-8859-1"); } /** * Returns a basic Authorization header value for the given * {@link UsernamePasswordCredentials} and charset. * * @param credentials The credentials to encode. * @param charset The charset to use for encoding the credentials * * @return a basic authorization string * * @since 3.0 */ public static String authenticate(UsernamePasswordCredentials credentials, String charset) { LOG.trace("enter BasicScheme.authenticate(UsernamePasswordCredentials, String)"); if (credentials == null) { throw new IllegalArgumentException("Credentials may not be null"); } if (charset == null || charset.length() == 0) { throw new IllegalArgumentException("charset may not be null or empty"); } StringBuffer buffer = new StringBuffer(); buffer.append(credentials.getUserName()); buffer.append(":"); buffer.append(credentials.getPassword()); return "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getBytes(buffer.toString(), charset))); } } ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/CredentialsNotAvailableException.javacommons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/CredentialsNotAvailableException.100644 0 0 5213 10661532626 31254 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/CredentialsNotAvailableException.java,v 1.4 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; /** * Authentication credentials required to respond to a authentication * challenge are not available * * @author Oleg Kalnichevski * * @since 3.0 */ public class CredentialsNotAvailableException extends AuthenticationException { /** * Creates a new CredentialsNotAvailableException with a null detail message. */ public CredentialsNotAvailableException() { super(); } /** * Creates a new CredentialsNotAvailableException with the specified message. * * @param message the exception detail message */ public CredentialsNotAvailableException(String message) { super(message); } /** * Creates a new CredentialsNotAvailableException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public CredentialsNotAvailableException(String message, Throwable cause) { super(message, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/CredentialsProvider.java100644 0 0 6751 10661532627 27501 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/CredentialsProvider.java,v 1.6 2004/07/05 22:46:59 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import org.apache.commons.httpclient.Credentials; /** *

* Credentials provider interface can be used to provide {@link * org.apache.commons.httpclient.HttpMethod HTTP method} with a means to request * authentication credentials if no credentials have been given or given * credentials are incorrect. *

*

* HttpClient makes no provisions to check whether the same credentials have * been tried already. It is a responsibility of the custom credentials provider * to keep track of authentication attempts and to ensure that credentials known * to be invalid are not retried. HttpClient will simply store the set of * credentials returned by the custom credentials provider in the * {@link org.apache.commons.httpclient.HttpState http state} object and will * attempt to use these credentials for all subsequent requests with the given * authentication scope. *

*

* Classes implementing this interface must synchronize access to shared data as * methods of this interfrace may be executed from multiple threads *

* * * @author Ortwin Glueck * @author Oleg Kalnichevski * * @since 3.0 */ public interface CredentialsProvider { /** * Sets the credentials provider parameter. *

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

*/ public static final String PROVIDER = "http.authentication.credential-provider"; /** * Requests additional {@link Credentials authentication credentials}. * * @param scheme the {@link AuthScheme authentication scheme} * @param host the authentication host * @param port the port of the authentication host * @param proxy true if authenticating with a proxy, * false otherwise */ public Credentials getCredentials( final AuthScheme scheme, final String host, int port, boolean proxy) throws CredentialsNotAvailableException; } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/DigestScheme.java100644 0 0 50436 10661532626 26113 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/DigestScheme.java,v 1.22 2004/12/30 11:01:27 oglueck Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClientError; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.util.EncodingUtil; import org.apache.commons.httpclient.util.ParameterFormatter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

* Digest authentication scheme as defined in RFC 2617. * Both MD5 (default) and MD5-sess are supported. * Currently only qop=auth or no qop is supported. qop=auth-int * is unsupported. If auth and auth-int are provided, auth is * used. *

*

* Credential charset is configured via the * {@link org.apache.commons.httpclient.params.HttpMethodParams#CREDENTIAL_CHARSET credential * charset} parameter. Since the digest username is included as clear text in the generated * Authentication header, the charset of the username must be compatible with the * {@link org.apache.commons.httpclient.params.HttpMethodParams#HTTP_ELEMENT_CHARSET http element * charset}. *

* TODO: make class more stateful regarding repeated authentication requests * * @author Remy Maucherat * @author Rodney Waldhoff * @author Jeff Dever * @author Ortwin Gl?ck * @author Sean C. Sullivan * @author Adrian Sutton * @author Mike Bowler * @author Oleg Kalnichevski */ public class DigestScheme extends RFC2617Scheme { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(DigestScheme.class); /** * Hexa values used when creating 32 character long digest in HTTP DigestScheme * in case of authentication. * * @see #encode(byte[]) */ private static final char[] HEXADECIMAL = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** Whether the digest authentication process is complete */ private boolean complete; //TODO: supply a real nonce-count, currently a server will interprete a repeated request as a replay private static final String NC = "00000001"; //nonce-count is always 1 private static final int QOP_MISSING = 0; private static final int QOP_AUTH_INT = 1; private static final int QOP_AUTH = 2; private int qopVariant = QOP_MISSING; private String cnonce; private final ParameterFormatter formatter; /** * Default constructor for the digest authetication scheme. * * @since 3.0 */ public DigestScheme() { super(); this.complete = false; this.formatter = new ParameterFormatter(); } /** * Gets an ID based upon the realm and the nonce value. This ensures that requests * to the same realm with different nonce values will succeed. This differentiation * allows servers to request re-authentication using a fresh nonce value. * * @deprecated no longer used */ public String getID() { String id = getRealm(); String nonce = getParameter("nonce"); if (nonce != null) { id += "-" + nonce; } return id; } /** * Constructor for the digest authetication scheme. * * @param challenge authentication challenge * * @throws MalformedChallengeException is thrown if the authentication challenge * is malformed * * @deprecated Use parameterless constructor and {@link AuthScheme#processChallenge(String)} * method */ public DigestScheme(final String challenge) throws MalformedChallengeException { this(); processChallenge(challenge); } /** * Processes the Digest challenge. * * @param challenge the challenge string * * @throws MalformedChallengeException is thrown if the authentication challenge * is malformed * * @since 3.0 */ public void processChallenge(final String challenge) throws MalformedChallengeException { super.processChallenge(challenge); if (getParameter("realm") == null) { throw new MalformedChallengeException("missing realm in challange"); } if (getParameter("nonce") == null) { throw new MalformedChallengeException("missing nonce in challange"); } boolean unsupportedQop = false; // qop parsing String qop = getParameter("qop"); if (qop != null) { StringTokenizer tok = new StringTokenizer(qop,","); while (tok.hasMoreTokens()) { String variant = tok.nextToken().trim(); if (variant.equals("auth")) { qopVariant = QOP_AUTH; break; //that's our favourite, because auth-int is unsupported } else if (variant.equals("auth-int")) { qopVariant = QOP_AUTH_INT; } else { unsupportedQop = true; LOG.warn("Unsupported qop detected: "+ variant); } } } if (unsupportedQop && (qopVariant == QOP_MISSING)) { throw new MalformedChallengeException("None of the qop methods is supported"); } cnonce = createCnonce(); this.complete = true; } /** * Tests if the Digest authentication process has been completed. * * @return true if Digest authorization has been processed, * false otherwise. * * @since 3.0 */ public boolean isComplete() { String s = getParameter("stale"); if ("true".equalsIgnoreCase(s)) { return false; } else { return this.complete; } } /** * Returns textual designation of the digest authentication scheme. * * @return digest */ public String getSchemeName() { return "digest"; } /** * Returns false. Digest authentication scheme is request based. * * @return false. * * @since 3.0 */ public boolean isConnectionBased() { return false; } /** * Produces a digest authorization string for the given set of * {@link Credentials}, method name and URI. * * @param credentials A set of credentials to be used for athentication * @param method the name of the method that requires authorization. * @param uri The URI for which authorization is needed. * * @throws InvalidCredentialsException if authentication credentials * are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return a digest authorization string * * @see org.apache.commons.httpclient.HttpMethod#getName() * @see org.apache.commons.httpclient.HttpMethod#getPath() * * @deprecated Use {@link #authenticate(Credentials, HttpMethod)} */ public String authenticate(Credentials credentials, String method, String uri) throws AuthenticationException { LOG.trace("enter DigestScheme.authenticate(Credentials, String, String)"); UsernamePasswordCredentials usernamepassword = null; try { usernamepassword = (UsernamePasswordCredentials) credentials; } catch (ClassCastException e) { throw new InvalidCredentialsException( "Credentials cannot be used for digest authentication: " + credentials.getClass().getName()); } getParameters().put("methodname", method); getParameters().put("uri", uri); String digest = createDigest( usernamepassword.getUserName(), usernamepassword.getPassword()); return "Digest " + createDigestHeader(usernamepassword.getUserName(), digest); } /** * Produces a digest authorization string for the given set of * {@link Credentials}, method name and URI. * * @param credentials A set of credentials to be used for athentication * @param method The method being authenticated * * @throws InvalidCredentialsException if authentication credentials * are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return a digest authorization string * * @since 3.0 */ public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException { LOG.trace("enter DigestScheme.authenticate(Credentials, HttpMethod)"); UsernamePasswordCredentials usernamepassword = null; try { usernamepassword = (UsernamePasswordCredentials) credentials; } catch (ClassCastException e) { throw new InvalidCredentialsException( "Credentials cannot be used for digest authentication: " + credentials.getClass().getName()); } getParameters().put("methodname", method.getName()); StringBuffer buffer = new StringBuffer(method.getPath()); String query = method.getQueryString(); if (query != null) { if (query.indexOf("?") != 0) { buffer.append("?"); } buffer.append(method.getQueryString()); } getParameters().put("uri", buffer.toString()); String charset = getParameter("charset"); if (charset == null) { getParameters().put("charset", method.getParams().getCredentialCharset()); } String digest = createDigest( usernamepassword.getUserName(), usernamepassword.getPassword()); return "Digest " + createDigestHeader(usernamepassword.getUserName(), digest); } /** * Creates an MD5 response digest. * * @param uname Username * @param pwd Password * @param charset The credential charset * * @return The created digest as string. This will be the response tag's * value in the Authentication HTTP header. * @throws AuthenticationException when MD5 is an unsupported algorithm */ private String createDigest(final String uname, final String pwd) throws AuthenticationException { LOG.trace("enter DigestScheme.createDigest(String, String, Map)"); final String digAlg = "MD5"; // Collecting required tokens String uri = getParameter("uri"); String realm = getParameter("realm"); String nonce = getParameter("nonce"); String qop = getParameter("qop"); String method = getParameter("methodname"); String algorithm = getParameter("algorithm"); // If an algorithm is not specified, default to MD5. if (algorithm == null) { algorithm = "MD5"; } // If an charset is not specified, default to ISO-8859-1. String charset = getParameter("charset"); if (charset == null) { charset = "ISO-8859-1"; } if (qopVariant == QOP_AUTH_INT) { LOG.warn("qop=auth-int is not supported"); throw new AuthenticationException( "Unsupported qop in HTTP Digest authentication"); } MessageDigest md5Helper; try { md5Helper = MessageDigest.getInstance(digAlg); } catch (Exception e) { throw new AuthenticationException( "Unsupported algorithm in HTTP Digest authentication: " + digAlg); } // 3.2.2.2: Calculating digest StringBuffer tmp = new StringBuffer(uname.length() + realm.length() + pwd.length() + 2); tmp.append(uname); tmp.append(':'); tmp.append(realm); tmp.append(':'); tmp.append(pwd); // unq(username-value) ":" unq(realm-value) ":" passwd String a1 = tmp.toString(); //a1 is suitable for MD5 algorithm if(algorithm.equals("MD5-sess")) { // H( unq(username-value) ":" unq(realm-value) ":" passwd ) // ":" unq(nonce-value) // ":" unq(cnonce-value) String tmp2=encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset))); StringBuffer tmp3 = new StringBuffer(tmp2.length() + nonce.length() + cnonce.length() + 2); tmp3.append(tmp2); tmp3.append(':'); tmp3.append(nonce); tmp3.append(':'); tmp3.append(cnonce); a1 = tmp3.toString(); } else if(!algorithm.equals("MD5")) { LOG.warn("Unhandled algorithm " + algorithm + " requested"); } String md5a1 = encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset))); String a2 = null; if (qopVariant == QOP_AUTH_INT) { LOG.error("Unhandled qop auth-int"); //we do not have access to the entity-body or its hash //TODO: add Method ":" digest-uri-value ":" H(entity-body) } else { a2 = method + ":" + uri; } String md5a2 = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(a2))); // 3.2.2.1 String serverDigestValue; if (qopVariant == QOP_MISSING) { LOG.debug("Using null qop method"); StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length() + md5a2.length()); tmp2.append(md5a1); tmp2.append(':'); tmp2.append(nonce); tmp2.append(':'); tmp2.append(md5a2); serverDigestValue = tmp2.toString(); } else { if (LOG.isDebugEnabled()) { LOG.debug("Using qop method " + qop); } String qopOption = getQopVariantString(); StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length() + NC.length() + cnonce.length() + qopOption.length() + md5a2.length() + 5); tmp2.append(md5a1); tmp2.append(':'); tmp2.append(nonce); tmp2.append(':'); tmp2.append(NC); tmp2.append(':'); tmp2.append(cnonce); tmp2.append(':'); tmp2.append(qopOption); tmp2.append(':'); tmp2.append(md5a2); serverDigestValue = tmp2.toString(); } String serverDigest = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(serverDigestValue))); return serverDigest; } /** * Creates digest-response header as defined in RFC2617. * * @param uname Username * @param digest The response tag's value as String. * * @return The digest-response as String. */ private String createDigestHeader(final String uname, final String digest) throws AuthenticationException { LOG.trace("enter DigestScheme.createDigestHeader(String, Map, " + "String)"); String uri = getParameter("uri"); String realm = getParameter("realm"); String nonce = getParameter("nonce"); String opaque = getParameter("opaque"); String response = digest; String algorithm = getParameter("algorithm"); List params = new ArrayList(20); params.add(new NameValuePair("username", uname)); params.add(new NameValuePair("realm", realm)); params.add(new NameValuePair("nonce", nonce)); params.add(new NameValuePair("uri", uri)); params.add(new NameValuePair("response", response)); if (qopVariant != QOP_MISSING) { params.add(new NameValuePair("qop", getQopVariantString())); params.add(new NameValuePair("nc", NC)); params.add(new NameValuePair("cnonce", this.cnonce)); } if (algorithm != null) { params.add(new NameValuePair("algorithm", algorithm)); } if (opaque != null) { params.add(new NameValuePair("opaque", opaque)); } StringBuffer buffer = new StringBuffer(); for (int i = 0; i < params.size(); i++) { NameValuePair param = (NameValuePair) params.get(i); if (i > 0) { buffer.append(", "); } boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName()); this.formatter.setAlwaysUseQuotes(!noQuotes); this.formatter.format(buffer, param); } return buffer.toString(); } private String getQopVariantString() { String qopOption; if (qopVariant == QOP_AUTH_INT) { qopOption = "auth-int"; } else { qopOption = "auth"; } return qopOption; } /** * Encodes the 128 bit (16 bytes) MD5 digest into a 32 characters long * String according to RFC 2617. * * @param binaryData array containing the digest * @return encoded MD5, or null if encoding failed */ private static String encode(byte[] binaryData) { LOG.trace("enter DigestScheme.encode(byte[])"); if (binaryData.length != 16) { return null; } char[] buffer = new char[32]; for (int i = 0; i < 16; i++) { int low = (int) (binaryData[i] & 0x0f); int high = (int) ((binaryData[i] & 0xf0) >> 4); buffer[i * 2] = HEXADECIMAL[high]; buffer[(i * 2) + 1] = HEXADECIMAL[low]; } return new String(buffer); } /** * Creates a random cnonce value based on the current time. * * @return The cnonce value as String. * @throws HttpClientError if MD5 algorithm is not supported. */ public static String createCnonce() { LOG.trace("enter DigestScheme.createCnonce()"); String cnonce; final String digAlg = "MD5"; MessageDigest md5Helper; try { md5Helper = MessageDigest.getInstance(digAlg); } catch (NoSuchAlgorithmException e) { throw new HttpClientError( "Unsupported algorithm in HTTP Digest authentication: " + digAlg); } cnonce = Long.toString(System.currentTimeMillis()); cnonce = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(cnonce))); return cnonce; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/HttpAuthRealm.java100644 0 0 4462 10661532626 26247 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/HttpAuthRealm.java,v 1.9 2004/06/12 22:47:23 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; /** The key used to look up authentication credentials. * * @author Oleg Kalnichevski * @author Adrian Sutton * * @deprecated no longer used */ public class HttpAuthRealm extends AuthScope { /** Creates a new HttpAuthRealm for the given domain and * realm. * * @param domain the domain the credentials apply to. May be set * to null if credenticals are applicable to * any domain. * @param realm the realm the credentials apply to. May be set * to null if credenticals are applicable to * any realm. * */ public HttpAuthRealm(final String domain, final String realm) { super(domain, ANY_PORT, realm, ANY_SCHEME); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/HttpAuthenticator.java100644 0 0 36437 10661532626 27226 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/HttpAuthenticator.java,v 1.19 2004/10/06 17:32:04 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpConnection; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Utility methods for HTTP authorization and authentication. This class * provides utility methods for generating responses to HTTP www and proxy * authentication challenges. * *
* A client SHOULD assume that all paths at or deeper than the depth of the * last symbolic element in the path field of the Request-URI also are within * the protection space specified by the basic realm value of the current * challenge. A client MAY preemptively send the corresponding Authorization * header with requests for resources in that space without receipt of another * challenge from the server. Similarly, when a client sends a request to a * proxy, it may reuse a userid and password in the Proxy-Authorization header * field without receiving another challenge from the proxy server. *
*

* * @author Remy Maucherat * @author Rodney Waldhoff * @author Jeff Dever * @author Ortwin Gl�ck * @author Sean C. Sullivan * @author Adrian Sutton * @author Mike Bowler * @author Oleg Kalnichevski * * @deprecated no longer used */ public final class HttpAuthenticator { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HttpAuthenticator.class); /** * The www authenticate challange header. */ public static final String WWW_AUTH = "WWW-Authenticate"; /** * The www authenticate response header. */ public static final String WWW_AUTH_RESP = "Authorization"; /** * The proxy authenticate challange header. */ public static final String PROXY_AUTH = "Proxy-Authenticate"; /** * The proxy authenticate response header. */ public static final String PROXY_AUTH_RESP = "Proxy-Authorization"; /** Chooses the strongest authentication scheme supported from the * array of authentication challenges. Currently only NTLM, * Digest, Basic schemes are recognized. * The NTLM scheme is considered the strongest and is * preferred to all others. The Digest scheme is preferred to * the Basic one which provides no encryption for credentials. * The Basic scheme is used only if it is the only one * supported. * * @param challenges The array of authentication challenges * * @return The strongest authentication scheme supported * * @throws MalformedChallengeException is thrown if an authentication * challenge is malformed * @throws UnsupportedOperationException when none of challenge types * available is supported. * * @deprecated Use {@link AuthChallengeParser#parseChallenges(Header[])} and * {@link AuthPolicy#getAuthScheme(String)} */ public static AuthScheme selectAuthScheme(final Header[] challenges) throws MalformedChallengeException { LOG.trace("enter HttpAuthenticator.selectAuthScheme(Header[])"); if (challenges == null) { throw new IllegalArgumentException("Array of challenges may not be null"); } if (challenges.length == 0) { throw new IllegalArgumentException("Array of challenges may not be empty"); } String challenge = null; Map challengemap = new HashMap(challenges.length); for (int i = 0; i < challenges.length; i++) { challenge = challenges[i].getValue(); String s = AuthChallengeParser.extractScheme(challenge); challengemap.put(s, challenge); } challenge = (String) challengemap.get("ntlm"); if (challenge != null) { return new NTLMScheme(challenge); } challenge = (String) challengemap.get("digest"); if (challenge != null) { return new DigestScheme(challenge); } challenge = (String) challengemap.get("basic"); if (challenge != null) { return new BasicScheme(challenge); } throw new UnsupportedOperationException( "Authentication scheme(s) not supported: " + challengemap.toString()); } private static boolean doAuthenticateDefault( HttpMethod method, HttpConnection conn, HttpState state, boolean proxy) throws AuthenticationException { if (method == null) { throw new IllegalArgumentException("HTTP method may not be null"); } if (state == null) { throw new IllegalArgumentException("HTTP state may not be null"); } String host = null; if (conn != null) { host = proxy ? conn.getProxyHost() : conn.getHost(); } Credentials credentials = proxy ? state.getProxyCredentials(null, host) : state.getCredentials(null, host); if (credentials == null) { return false; } if (!(credentials instanceof UsernamePasswordCredentials)) { throw new InvalidCredentialsException( "Credentials cannot be used for basic authentication: " + credentials.toString()); } String auth = BasicScheme.authenticate( (UsernamePasswordCredentials) credentials, method.getParams().getCredentialCharset()); if (auth != null) { String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP; Header header = new Header(s, auth, true); method.addRequestHeader(header); return true; } else { return false; } } /** * Attempt to provide default authentication credentials * to the given method in the given context using basic * authentication scheme. * * @param method the HttpMethod which requires authentication * @param conn the connection to a specific host. This parameter * may be null if default credentials (not specific * to any particular host) are to be used * @param state the HttpState object providing Credentials * * @return true if the Authenticate response header * was added * * @throws InvalidCredentialsException if authentication credentials * are not valid or not applicable for basic scheme * @throws AuthenticationException when a parsing or other error occurs * * @see HttpState#setCredentials(String,String,Credentials) * * @deprecated use AuthScheme */ public static boolean authenticateDefault( HttpMethod method, HttpConnection conn, HttpState state) throws AuthenticationException { LOG.trace( "enter HttpAuthenticator.authenticateDefault(HttpMethod, HttpConnection, HttpState)"); return doAuthenticateDefault(method, conn, state, false); } /** * Attempt to provide default proxy authentication credentials * to the given method in the given context using basic * authentication scheme. * * @param method the HttpMethod which requires authentication * @param conn the connection to a specific host. This parameter * may be null if default credentials (not specific * to any particular host) are to be used * @param state the HttpState object providing Credentials * * @return true if the Proxy-Authenticate response header * was added * * @throws InvalidCredentialsException if authentication credentials * are not valid or not applicable for basic scheme * @throws AuthenticationException when a parsing or other error occurs * @see HttpState#setCredentials(String,String,Credentials) * * @deprecated use AuthScheme */ public static boolean authenticateProxyDefault( HttpMethod method, HttpConnection conn, HttpState state) throws AuthenticationException { LOG.trace("enter HttpAuthenticator.authenticateProxyDefault(HttpMethod, HttpState)"); return doAuthenticateDefault(method, conn, state, true); } private static boolean doAuthenticate( AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state, boolean proxy) throws AuthenticationException { if (authscheme == null) { throw new IllegalArgumentException("Authentication scheme may not be null"); } if (method == null) { throw new IllegalArgumentException("HTTP method may not be null"); } if (state == null) { throw new IllegalArgumentException("HTTP state may not be null"); } String host = null; if (conn != null) { if (proxy) { host = conn.getProxyHost(); } else { host = method.getParams().getVirtualHost(); if (host == null) { host = conn.getHost(); } } } String realm = authscheme.getRealm(); if (LOG.isDebugEnabled()) { StringBuffer buffer = new StringBuffer(); buffer.append("Using credentials for "); if (realm == null) { buffer.append("default"); } else { buffer.append('\''); buffer.append(realm); buffer.append('\''); } buffer.append(" authentication realm at "); buffer.append(host); LOG.debug(buffer.toString()); } Credentials credentials = proxy ? state.getProxyCredentials(realm, host) : state.getCredentials(realm, host); if (credentials == null) { StringBuffer buffer = new StringBuffer(); buffer.append("No credentials available for the "); if (realm == null) { buffer.append("default"); } else { buffer.append('\''); buffer.append(realm); buffer.append('\''); } buffer.append(" authentication realm at "); buffer.append(host); throw new CredentialsNotAvailableException(buffer.toString()); } String auth = authscheme.authenticate(credentials, method); if (auth != null) { String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP; Header header = new Header(s, auth, true); method.addRequestHeader(header); return true; } else { return false; } } /** * Attempt to provide requisite authentication credentials to the * given method in the given context using the given * authentication scheme. * * @param authscheme The authentication scheme to be used * @param method The HttpMethod which requires authentication * @param conn the connection to a specific host. This parameter * may be null if default credentials (not specific * to any particular host) are to be used * @param state The HttpState object providing Credentials * * @return true if the Authenticate response header was added * * @throws CredentialsNotAvailableException if authentication credentials * required to respond to the authentication challenge are not available * @throws AuthenticationException when a parsing or other error occurs * @see HttpState#setCredentials(String,String,Credentials) * * @deprecated use AuthScheme */ public static boolean authenticate( AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state) throws AuthenticationException { LOG.trace( "enter HttpAuthenticator.authenticate(AuthScheme, HttpMethod, HttpConnection, " + "HttpState)"); return doAuthenticate(authscheme, method, conn, state, false); } /** * Attempt to provide requisite proxy authentication credentials * to the given method in the given context using * the given authentication scheme. * * @param authscheme The authentication scheme to be used * @param method the HttpMethod which requires authentication * @param conn the connection to a specific host. This parameter * may be null if default credentials (not specific * to any particular host) are to be used * @param state the HttpState object providing Credentials * * @return true if the Proxy-Authenticate response header * was added * * @throws CredentialsNotAvailableException if authentication credentials * required to respond to the authentication challenge are not available * @throws AuthenticationException when a parsing or other error occurs * @see HttpState#setCredentials(String,String,Credentials) * * @deprecated use AuthScheme */ public static boolean authenticateProxy( AuthScheme authscheme, HttpMethod method, HttpConnection conn, HttpState state ) throws AuthenticationException { LOG.trace("enter HttpAuthenticator.authenticateProxy(AuthScheme, HttpMethod, HttpState)"); return doAuthenticate(authscheme, method, conn, state, true); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/InvalidCredentialsException.java100644 0 0 5135 10661532626 31146 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/InvalidCredentialsException.java,v 1.4 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; /** * Authentication credentials required to respond to a authentication * challenge are invalid * * @author Oleg Kalnichevski * * @since 3.0 */ public class InvalidCredentialsException extends AuthenticationException { /** * Creates a new InvalidCredentialsException with a null detail message. */ public InvalidCredentialsException() { super(); } /** * Creates a new InvalidCredentialsException with the specified message. * * @param message the exception detail message */ public InvalidCredentialsException(String message) { super(message); } /** * Creates a new InvalidCredentialsException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable */ public InvalidCredentialsException(String message, Throwable cause) { super(message, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/MalformedChallengeException.java100644 0 0 5257 10661532626 31120 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/MalformedChallengeException.java,v 1.6 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import org.apache.commons.httpclient.ProtocolException; /** * Signals that authentication challenge is in some way invalid or * illegal in the given context * * @author Oleg Kalnichevski * * @since 2.0 */ public class MalformedChallengeException extends ProtocolException { /** * Creates a new MalformedChallengeException with a null detail message. */ public MalformedChallengeException() { super(); } /** * Creates a new MalformedChallengeException with the specified message. * * @param message the exception detail message */ public MalformedChallengeException(String message) { super(message); } /** * Creates a new MalformedChallengeException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable * * @since 3.0 */ public MalformedChallengeException(String message, Throwable cause) { super(message, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/NTLM.java100644 0 0 45054 10661532626 24321 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/NTLM.java,v 1.11 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.util.EncodingUtil; /** * Provides an implementation of the NTLM authentication protocol. *

* This class provides methods for generating authentication * challenge responses for the NTLM authentication protocol. The NTLM * protocol is a proprietary Microsoft protocol and as such no RFC * exists for it. This class is based upon the reverse engineering * efforts of a wide range of people.

* *

Please note that an implementation of JCE must be correctly installed and configured when * using NTLM support.

* *

This class should not be used externally to HttpClient as it's API is specifically * designed to work with HttpClient's use case, in particular it's connection management.

* * @author Adrian Sutton * @author Jeff Dever * @author Mike Bowler * * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * @since 3.0 */ final class NTLM { /** Character encoding */ public static final String DEFAULT_CHARSET = "ASCII"; /** The current response */ private byte[] currentResponse; /** The current position */ private int currentPosition = 0; /** The character set to use for encoding the credentials */ private String credentialCharset = DEFAULT_CHARSET; /** * Returns the response for the given message. * * @param message the message that was received from the server. * @param username the username to authenticate with. * @param password the password to authenticate with. * @param host The host. * @param domain the NT domain to authenticate in. * @return The response. * @throws HttpException If the messages cannot be retrieved. */ public final String getResponseFor(String message, String username, String password, String host, String domain) throws AuthenticationException { final String response; if (message == null || message.trim().equals("")) { response = getType1Message(host, domain); } else { response = getType3Message(username, password, host, domain, parseType2Message(message)); } return response; } /** * Return the cipher for the specified key. * @param key The key. * @return Cipher The cipher. * @throws AuthenticationException If the cipher cannot be retrieved. */ private Cipher getCipher(byte[] key) throws AuthenticationException { try { final Cipher ecipher = Cipher.getInstance("DES/ECB/NoPadding"); key = setupKey(key); ecipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "DES")); return ecipher; } catch (NoSuchAlgorithmException e) { throw new AuthenticationException("DES encryption is not available.", e); } catch (InvalidKeyException e) { throw new AuthenticationException("Invalid key for DES encryption.", e); } catch (NoSuchPaddingException e) { throw new AuthenticationException( "NoPadding option for DES is not available.", e); } } /** * Adds parity bits to the key. * @param key56 The key * @return The modified key. */ private byte[] setupKey(byte[] key56) { byte[] key = new byte[8]; key[0] = (byte) ((key56[0] >> 1) & 0xff); key[1] = (byte) ((((key56[0] & 0x01) << 6) | (((key56[1] & 0xff) >> 2) & 0xff)) & 0xff); key[2] = (byte) ((((key56[1] & 0x03) << 5) | (((key56[2] & 0xff) >> 3) & 0xff)) & 0xff); key[3] = (byte) ((((key56[2] & 0x07) << 4) | (((key56[3] & 0xff) >> 4) & 0xff)) & 0xff); key[4] = (byte) ((((key56[3] & 0x0f) << 3) | (((key56[4] & 0xff) >> 5) & 0xff)) & 0xff); key[5] = (byte) ((((key56[4] & 0x1f) << 2) | (((key56[5] & 0xff) >> 6) & 0xff)) & 0xff); key[6] = (byte) ((((key56[5] & 0x3f) << 1) | (((key56[6] & 0xff) >> 7) & 0xff)) & 0xff); key[7] = (byte) (key56[6] & 0x7f); for (int i = 0; i < key.length; i++) { key[i] = (byte) (key[i] << 1); } return key; } /** * Encrypt the data. * @param key The key. * @param bytes The data * @return byte[] The encrypted data * @throws HttpException If {@link Cipher.doFinal(byte[])} fails */ private byte[] encrypt(byte[] key, byte[] bytes) throws AuthenticationException { Cipher ecipher = getCipher(key); try { byte[] enc = ecipher.doFinal(bytes); return enc; } catch (IllegalBlockSizeException e) { throw new AuthenticationException("Invalid block size for DES encryption.", e); } catch (BadPaddingException e) { throw new AuthenticationException("Data not padded correctly for DES encryption.", e); } } /** * Prepares the object to create a response of the given length. * @param length the length of the response to prepare. */ private void prepareResponse(int length) { currentResponse = new byte[length]; currentPosition = 0; } /** * Adds the given byte to the response. * @param b the byte to add. */ private void addByte(byte b) { currentResponse[currentPosition] = b; currentPosition++; } /** * Adds the given bytes to the response. * @param bytes the bytes to add. */ private void addBytes(byte[] bytes) { for (int i = 0; i < bytes.length; i++) { currentResponse[currentPosition] = bytes[i]; currentPosition++; } } /** * Returns the response that has been generated after shrinking the array if * required and base64 encodes the response. * @return The response as above. */ private String getResponse() { byte[] resp; if (currentResponse.length > currentPosition) { byte[] tmp = new byte[currentPosition]; for (int i = 0; i < currentPosition; i++) { tmp[i] = currentResponse[i]; } resp = tmp; } else { resp = currentResponse; } return EncodingUtil.getAsciiString(Base64.encodeBase64(resp)); } /** * Creates the first message (type 1 message) in the NTLM authentication sequence. * This message includes the user name, domain and host for the authentication session. * * @param host the computer name of the host requesting authentication. * @param domain The domain to authenticate with. * @return String the message to add to the HTTP request header. */ public String getType1Message(String host, String domain) { host = host.toUpperCase(); domain = domain.toUpperCase(); byte[] hostBytes = EncodingUtil.getBytes(host, DEFAULT_CHARSET); byte[] domainBytes = EncodingUtil.getBytes(domain, DEFAULT_CHARSET); int finalLength = 32 + hostBytes.length + domainBytes.length; prepareResponse(finalLength); // The initial id string. byte[] protocol = EncodingUtil.getBytes("NTLMSSP", DEFAULT_CHARSET); addBytes(protocol); addByte((byte) 0); // Type addByte((byte) 1); addByte((byte) 0); addByte((byte) 0); addByte((byte) 0); // Flags addByte((byte) 6); addByte((byte) 82); addByte((byte) 0); addByte((byte) 0); // Domain length (first time). int iDomLen = domainBytes.length; byte[] domLen = convertShort(iDomLen); addByte(domLen[0]); addByte(domLen[1]); // Domain length (second time). addByte(domLen[0]); addByte(domLen[1]); // Domain offset. byte[] domOff = convertShort(hostBytes.length + 32); addByte(domOff[0]); addByte(domOff[1]); addByte((byte) 0); addByte((byte) 0); // Host length (first time). byte[] hostLen = convertShort(hostBytes.length); addByte(hostLen[0]); addByte(hostLen[1]); // Host length (second time). addByte(hostLen[0]); addByte(hostLen[1]); // Host offset (always 32). byte[] hostOff = convertShort(32); addByte(hostOff[0]); addByte(hostOff[1]); addByte((byte) 0); addByte((byte) 0); // Host String. addBytes(hostBytes); // Domain String. addBytes(domainBytes); return getResponse(); } /** * Extracts the server nonce out of the given message type 2. * * @param message the String containing the base64 encoded message. * @return an array of 8 bytes that the server sent to be used when * hashing the password. */ public byte[] parseType2Message(String message) { // Decode the message first. byte[] msg = Base64.decodeBase64(EncodingUtil.getBytes(message, DEFAULT_CHARSET)); byte[] nonce = new byte[8]; // The nonce is the 8 bytes starting from the byte in position 24. for (int i = 0; i < 8; i++) { nonce[i] = msg[i + 24]; } return nonce; } /** * Creates the type 3 message using the given server nonce. The type 3 message includes all the * information for authentication, host, domain, username and the result of encrypting the * nonce sent by the server using the user's password as the key. * * @param user The user name. This should not include the domain name. * @param password The password. * @param host The host that is originating the authentication request. * @param domain The domain to authenticate within. * @param nonce the 8 byte array the server sent. * @return The type 3 message. * @throws AuthenticationException If {@encrypt(byte[],byte[])} fails. */ public String getType3Message(String user, String password, String host, String domain, byte[] nonce) throws AuthenticationException { int ntRespLen = 0; int lmRespLen = 24; domain = domain.toUpperCase(); host = host.toUpperCase(); user = user.toUpperCase(); byte[] domainBytes = EncodingUtil.getBytes(domain, DEFAULT_CHARSET); byte[] hostBytes = EncodingUtil.getBytes(host, DEFAULT_CHARSET); byte[] userBytes = EncodingUtil.getBytes(user, credentialCharset); int domainLen = domainBytes.length; int hostLen = hostBytes.length; int userLen = userBytes.length; int finalLength = 64 + ntRespLen + lmRespLen + domainLen + userLen + hostLen; prepareResponse(finalLength); byte[] ntlmssp = EncodingUtil.getBytes("NTLMSSP", DEFAULT_CHARSET); addBytes(ntlmssp); addByte((byte) 0); addByte((byte) 3); addByte((byte) 0); addByte((byte) 0); addByte((byte) 0); // LM Resp Length (twice) addBytes(convertShort(24)); addBytes(convertShort(24)); // LM Resp Offset addBytes(convertShort(finalLength - 24)); addByte((byte) 0); addByte((byte) 0); // NT Resp Length (twice) addBytes(convertShort(0)); addBytes(convertShort(0)); // NT Resp Offset addBytes(convertShort(finalLength)); addByte((byte) 0); addByte((byte) 0); // Domain length (twice) addBytes(convertShort(domainLen)); addBytes(convertShort(domainLen)); // Domain offset. addBytes(convertShort(64)); addByte((byte) 0); addByte((byte) 0); // User Length (twice) addBytes(convertShort(userLen)); addBytes(convertShort(userLen)); // User offset addBytes(convertShort(64 + domainLen)); addByte((byte) 0); addByte((byte) 0); // Host length (twice) addBytes(convertShort(hostLen)); addBytes(convertShort(hostLen)); // Host offset addBytes(convertShort(64 + domainLen + userLen)); for (int i = 0; i < 6; i++) { addByte((byte) 0); } // Message length addBytes(convertShort(finalLength)); addByte((byte) 0); addByte((byte) 0); // Flags addByte((byte) 6); addByte((byte) 82); addByte((byte) 0); addByte((byte) 0); addBytes(domainBytes); addBytes(userBytes); addBytes(hostBytes); addBytes(hashPassword(password, nonce)); return getResponse(); } /** * Creates the LANManager and NT response for the given password using the * given nonce. * @param password the password to create a hash for. * @param nonce the nonce sent by the server. * @return The response. * @throws HttpException If {@link #encrypt(byte[],byte[])} fails. */ private byte[] hashPassword(String password, byte[] nonce) throws AuthenticationException { byte[] passw = EncodingUtil.getBytes(password.toUpperCase(), credentialCharset); byte[] lmPw1 = new byte[7]; byte[] lmPw2 = new byte[7]; int len = passw.length; if (len > 7) { len = 7; } int idx; for (idx = 0; idx < len; idx++) { lmPw1[idx] = passw[idx]; } for (; idx < 7; idx++) { lmPw1[idx] = (byte) 0; } len = passw.length; if (len > 14) { len = 14; } for (idx = 7; idx < len; idx++) { lmPw2[idx - 7] = passw[idx]; } for (; idx < 14; idx++) { lmPw2[idx - 7] = (byte) 0; } // Create LanManager hashed Password byte[] magic = { (byte) 0x4B, (byte) 0x47, (byte) 0x53, (byte) 0x21, (byte) 0x40, (byte) 0x23, (byte) 0x24, (byte) 0x25 }; byte[] lmHpw1; lmHpw1 = encrypt(lmPw1, magic); byte[] lmHpw2 = encrypt(lmPw2, magic); byte[] lmHpw = new byte[21]; for (int i = 0; i < lmHpw1.length; i++) { lmHpw[i] = lmHpw1[i]; } for (int i = 0; i < lmHpw2.length; i++) { lmHpw[i + 8] = lmHpw2[i]; } for (int i = 0; i < 5; i++) { lmHpw[i + 16] = (byte) 0; } // Create the responses. byte[] lmResp = new byte[24]; calcResp(lmHpw, nonce, lmResp); return lmResp; } /** * Takes a 21 byte array and treats it as 3 56-bit DES keys. The 8 byte * plaintext is encrypted with each key and the resulting 24 bytes are * stored in the results array. * * @param keys The keys. * @param plaintext The plain text to encrypt. * @param results Where the results are stored. * @throws AuthenticationException If {@link #encrypt(byte[],byte[])} fails. */ private void calcResp(byte[] keys, byte[] plaintext, byte[] results) throws AuthenticationException { byte[] keys1 = new byte[7]; byte[] keys2 = new byte[7]; byte[] keys3 = new byte[7]; for (int i = 0; i < 7; i++) { keys1[i] = keys[i]; } for (int i = 0; i < 7; i++) { keys2[i] = keys[i + 7]; } for (int i = 0; i < 7; i++) { keys3[i] = keys[i + 14]; } byte[] results1 = encrypt(keys1, plaintext); byte[] results2 = encrypt(keys2, plaintext); byte[] results3 = encrypt(keys3, plaintext); for (int i = 0; i < 8; i++) { results[i] = results1[i]; } for (int i = 0; i < 8; i++) { results[i + 8] = results2[i]; } for (int i = 0; i < 8; i++) { results[i + 16] = results3[i]; } } /** * Converts a given number to a two byte array in little endian order. * @param num the number to convert. * @return The byte representation of num in little endian order. */ private byte[] convertShort(int num) { byte[] val = new byte[2]; String hex = Integer.toString(num, 16); while (hex.length() < 4) { hex = "0" + hex; } String low = hex.substring(2, 4); String high = hex.substring(0, 2); val[0] = (byte) Integer.parseInt(low, 16); val[1] = (byte) Integer.parseInt(high, 16); return val; } /** * @return Returns the credentialCharset. */ public String getCredentialCharset() { return credentialCharset; } /** * @param credentialCharset The credentialCharset to set. */ public void setCredentialCharset(String credentialCharset) { this.credentialCharset = credentialCharset; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/NTLMScheme.java100644 0 0 31063 10661532627 25442 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/NTLMScheme.java,v 1.21 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.NTCredentials; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** An implementation of the Microsoft proprietary NTLM authentication scheme. For a detailed * explanation of the NTLM scheme please see * http://davenport.sourceforge.net/ntlm.html. * * @author Remy Maucherat * @author Rodney Waldhoff * @author Jeff Dever * @author Ortwin Gl???ck * @author Sean C. Sullivan * @author Adrian Sutton * @author Mike Bowler * @author Oleg Kalnichevski */ public class NTLMScheme implements AuthScheme { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(NTLMScheme.class); /** NTLM challenge string. */ private String ntlmchallenge = null; private static final int UNINITIATED = 0; private static final int INITIATED = 1; private static final int TYPE1_MSG_GENERATED = 2; private static final int TYPE2_MSG_RECEIVED = 3; private static final int TYPE3_MSG_GENERATED = 4; private static final int FAILED = Integer.MAX_VALUE; /** Authentication process state */ private int state; /** * Default constructor for the NTLM authentication scheme. * * @since 3.0 */ public NTLMScheme() { super(); this.state = UNINITIATED; } /** * Constructor for the NTLM authentication scheme. * * @param challenge The authentication challenge * * @throws MalformedChallengeException is thrown if the authentication challenge * is malformed */ public NTLMScheme(final String challenge) throws MalformedChallengeException { super(); processChallenge(challenge); } /** * Processes the NTLM challenge. * * @param challenge the challenge string * * @throws MalformedChallengeException is thrown if the authentication challenge * is malformed * * @since 3.0 */ public void processChallenge(final String challenge) throws MalformedChallengeException { String s = AuthChallengeParser.extractScheme(challenge); if (!s.equalsIgnoreCase(getSchemeName())) { throw new MalformedChallengeException("Invalid NTLM challenge: " + challenge); } int i = challenge.indexOf(' '); if (i != -1) { s = challenge.substring(i, challenge.length()); this.ntlmchallenge = s.trim(); this.state = TYPE2_MSG_RECEIVED; } else { this.ntlmchallenge = ""; if (this.state == UNINITIATED) { this.state = INITIATED; } else { this.state = FAILED; } } } /** * Tests if the NTLM authentication process has been completed. * * @return true if Basic authorization has been processed, * false otherwise. * * @since 3.0 */ public boolean isComplete() { return this.state == TYPE3_MSG_GENERATED || this.state == FAILED; } /** * Returns textual designation of the NTLM authentication scheme. * * @return ntlm */ public String getSchemeName() { return "ntlm"; } /** * The concept of an authentication realm is not supported by the NTLM * authentication scheme. Always returns null. * * @return null */ public String getRealm() { return null; } /** * Returns a String identifying the authentication challenge. This is * used, in combination with the host and port to determine if * authorization has already been attempted or not. Schemes which * require multiple requests to complete the authentication should * return a different value for each stage in the request. * *

Additionally, the ID should take into account any changes to the * authentication challenge and return a different value when appropriate. * For example when the realm changes in basic authentication it should be * considered a different authentication attempt and a different value should * be returned.

* * @return String a String identifying the authentication challenge. The * returned value may be null. * * @deprecated no longer used */ public String getID() { return ntlmchallenge; } /** * Returns the authentication parameter with the given name, if available. * *

There are no valid parameters for NTLM authentication so this method always returns * null.

* * @param name The name of the parameter to be returned * * @return the parameter with the given name */ public String getParameter(String name) { if (name == null) { throw new IllegalArgumentException("Parameter name may not be null"); } return null; } /** * Returns true. NTLM authentication scheme is connection based. * * @return true. * * @since 3.0 */ public boolean isConnectionBased() { return true; } /** * Create a NTLM authorization string for the given * challenge and NT credentials. * * @param challenge The challenge. * @param credentials {@link NTCredentials} * * @return a ntlm authorization string * @throws AuthenticationException is thrown if authentication fails * * @deprecated Use non-static {@link #authenticate(Credentials, HttpMethod)} */ public static String authenticate( final NTCredentials credentials, final String challenge) throws AuthenticationException { LOG.trace("enter NTLMScheme.authenticate(NTCredentials, String)"); if (credentials == null) { throw new IllegalArgumentException("Credentials may not be null"); } NTLM ntlm = new NTLM(); String s = ntlm.getResponseFor(challenge, credentials.getUserName(), credentials.getPassword(), credentials.getHost(), credentials.getDomain()); return "NTLM " + s; } /** * Create a NTLM authorization string for the given * challenge and NT credentials. * * @param challenge The challenge. * @param credentials {@link NTCredentials} * @param charset The charset to use for encoding the credentials * * @return a ntlm authorization string * @throws AuthenticationException is thrown if authentication fails * * @deprecated Use non-static {@link #authenticate(Credentials, HttpMethod)} * * @since 3.0 */ public static String authenticate( final NTCredentials credentials, final String challenge, String charset ) throws AuthenticationException { LOG.trace("enter NTLMScheme.authenticate(NTCredentials, String)"); if (credentials == null) { throw new IllegalArgumentException("Credentials may not be null"); } NTLM ntlm = new NTLM(); ntlm.setCredentialCharset(charset); String s = ntlm.getResponseFor( challenge, credentials.getUserName(), credentials.getPassword(), credentials.getHost(), credentials.getDomain()); return "NTLM " + s; } /** * Produces NTLM authorization string for the given set of * {@link Credentials}. * * @param credentials The set of credentials to be used for athentication * @param method Method name is ignored by the NTLM authentication scheme * @param uri URI is ignored by the NTLM authentication scheme * @throws InvalidCredentialsException if authentication credentials * are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return an NTLM authorization string * * @deprecated Use {@link #authenticate(Credentials, HttpMethod)} */ public String authenticate(Credentials credentials, String method, String uri) throws AuthenticationException { LOG.trace("enter NTLMScheme.authenticate(Credentials, String, String)"); NTCredentials ntcredentials = null; try { ntcredentials = (NTCredentials) credentials; } catch (ClassCastException e) { throw new InvalidCredentialsException( "Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName()); } return NTLMScheme.authenticate(ntcredentials, this.ntlmchallenge); } /** * Produces NTLM authorization string for the given set of * {@link Credentials}. * * @param credentials The set of credentials to be used for athentication * @param method The method being authenticated * * @throws InvalidCredentialsException if authentication credentials * are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return an NTLM authorization string * * @since 3.0 */ public String authenticate( Credentials credentials, HttpMethod method ) throws AuthenticationException { LOG.trace("enter NTLMScheme.authenticate(Credentials, HttpMethod)"); if (this.state == UNINITIATED) { throw new IllegalStateException("NTLM authentication process has not been initiated"); } NTCredentials ntcredentials = null; try { ntcredentials = (NTCredentials) credentials; } catch (ClassCastException e) { throw new InvalidCredentialsException( "Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName()); } NTLM ntlm = new NTLM(); ntlm.setCredentialCharset(method.getParams().getCredentialCharset()); String response = null; if (this.state == INITIATED || this.state == FAILED) { response = ntlm.getType1Message( ntcredentials.getHost(), ntcredentials.getDomain()); this.state = TYPE1_MSG_GENERATED; } else { response = ntlm.getType3Message( ntcredentials.getUserName(), ntcredentials.getPassword(), ntcredentials.getHost(), ntcredentials.getDomain(), ntlm.parseType2Message(this.ntlmchallenge)); this.state = TYPE3_MSG_GENERATED; } return "NTLM " + response; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/RFC2617Scheme.java100644 0 0 12624 10661532627 25624 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/RFC2617Scheme.java,v 1.10 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import java.util.Map; /** *

* Abstract authentication scheme class that lays foundation for all * RFC 2617 compliant authetication schemes and provides capabilities common * to all authentication schemes defined in RFC 2617. *

* * @author Oleg Kalnichevski */ public abstract class RFC2617Scheme implements AuthScheme { /** * Authentication parameter map. */ private Map params = null; /** * Default constructor for RFC2617 compliant authetication schemes. * * @since 3.0 */ public RFC2617Scheme() { super(); } /** * Default constructor for RFC2617 compliant authetication schemes. * * @param challenge authentication challenge * * @throws MalformedChallengeException is thrown if the authentication challenge * is malformed * * @deprecated Use parameterless constructor and {@link AuthScheme#processChallenge(String)} * method */ public RFC2617Scheme(final String challenge) throws MalformedChallengeException { super(); processChallenge(challenge); } /** * Processes the given challenge token. Some authentication schemes * may involve multiple challenge-response exchanges. Such schemes must be able * to maintain the state information when dealing with sequential challenges * * @param challenge the challenge string * * @throws MalformedChallengeException is thrown if the authentication challenge * is malformed * * @since 3.0 */ public void processChallenge(final String challenge) throws MalformedChallengeException { String s = AuthChallengeParser.extractScheme(challenge); if (!s.equalsIgnoreCase(getSchemeName())) { throw new MalformedChallengeException( "Invalid " + getSchemeName() + " challenge: " + challenge); } this.params = AuthChallengeParser.extractParams(challenge); } /** * Returns authentication parameters map. Keys in the map are lower-cased. * * @return the map of authentication parameters */ protected Map getParameters() { return this.params; } /** * Returns authentication parameter with the given name, if available. * * @param name The name of the parameter to be returned * * @return the parameter with the given name */ public String getParameter(String name) { if (name == null) { throw new IllegalArgumentException("Parameter name may not be null"); } if (this.params == null) { return null; } return (String) this.params.get(name.toLowerCase()); } /** * Returns authentication realm. The realm may not be null. * * @return the authentication realm */ public String getRealm() { return getParameter("realm"); } /** * Returns a String identifying the authentication challenge. This is * used, in combination with the host and port to determine if * authorization has already been attempted or not. Schemes which * require multiple requests to complete the authentication should * return a different value for each stage in the request. * *

Additionally, the ID should take into account any changes to the * authentication challenge and return a different value when appropriate. * For example when the realm changes in basic authentication it should be * considered a different authentication attempt and a different value should * be returned.

* *

This method simply returns the realm for the challenge.

* * @return String a String identifying the authentication challenge. The * returned value may be null. * * @deprecated no longer used */ public String getID() { return getRealm(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/auth/package.html100644 0 0 457 10661532632 25120 0ustar 0 0 Package Documentation for org.apache.commons.httpclient.auth Provides implementation of various authentication schemes as well as utility classes that can be used to authenticate HTTP requests. @since 2.0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/Cookie2.java100644 0 0 23335 10661532626 25350 0ustar 0 0 /* * $Header: /cvsroot/httpc-cookie2/httpc-cookie2/httpcookie2SVN-patch.082805-2100.diff,v 1.1 2005/08/29 05:01:58 sjain700 Exp $ * $Revision:400312 $ * $Date:2006-05-06 14:49:41 +0200 (Sat, 06 May 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.Date; import org.apache.commons.httpclient.Cookie; /** *

* Cookie class for {@link org.apache.commons.httpclient.cookie.RFC2965Spec} * cookie specification. It extends {@link Cookie} class and adds newer cookie * attributes and functions required for this specification. *

* * @author Samit Jain (jain.samit@gmail.com) * * @since 3.1 */ public class Cookie2 extends Cookie { // string constants for cookie attributes public static final String DOMAIN = "domain"; public static final String PATH = "path"; public static final String PORT = "port"; public static final String VERSION = "version"; public static final String SECURE = "secure"; public static final String MAXAGE = "max-age"; public static final String COMMENT = "comment"; public static final String COMMENTURL = "commenturl"; public static final String DISCARD = "discard"; /** * Default constructor. Creates a blank cookie */ public Cookie2() { super(null, "noname", null, null, null, false); } /** * Creates a cookie with the given name, value and domain attribute. * * @param name the cookie name * @param value the cookie value * @param domain the domain this cookie can be sent to */ public Cookie2(String domain, String name, String value) { super(domain, name, value); } /** * Creates a cookie with the given name, value, domain attribute, * path attribute, expiration attribute, and secure attribute * * @param name the cookie name * @param value the cookie value * @param domain the domain this cookie can be sent to * @param path the path prefix for which this cookie can be sent * @param expires the {@link Date} at which this cookie expires, * or null if the cookie expires at the end * of the session * @param secure if true this cookie can only be sent over secure * connections * @throws IllegalArgumentException If cookie name is null or blank, * cookie name contains a blank, or cookie name starts with character $ * */ public Cookie2(String domain, String name, String value, String path, Date expires, boolean secure) { super(domain, name, value, path, expires, secure); } /** * Creates a cookie with the given name, value, domain attribute, * path attribute, expiration attribute, secure attribute, and ports * attribute. * * @param name the cookie name * @param value the cookie value * @param domain the domain this cookie can be sent to * @param path the path prefix for which this cookie can be sent * @param expires the {@link Date} at which this cookie expires, * or null if the cookie expires at the end * of the session * @param secure if true this cookie can only be sent over secure * connections * @param ports the ports for which this cookie can be sent * @throws IllegalArgumentException If cookie name is null or blank, * cookie name contains a blank, or cookie name starts with character $ * */ public Cookie2(String domain, String name, String value, String path, Date expires, boolean secure, int[] ports) { super(domain, name, value, path, expires, secure); setPorts(ports); } /** * If a user agent (web browser) presents this cookie to a user, the * cookie's purpose will be described by the information at this URL. * * @see #setCommentURL(String) */ public String getCommentURL() { return cookieCommentURL; } /** * If a user agent (web browser) presents this cookie to a user, the * cookie's purpose will be described by the information at this URL. * * @param commentURL * * @see #getCommentURL() */ public void setCommentURL(String commentURL) { this.cookieCommentURL = commentURL; } /** * Get the Port attribute. It restricts the ports to which a cookie * may be returned in a Cookie request header. * * @see #setPorts(int[]) */ public int[] getPorts() { return cookiePorts; } /** * Set the Port attribute. It restricts the ports to which a cookie * may be returned in a Cookie request header. * * @param ports * * @see #getPorts() */ public void setPorts(int[] ports) { this.cookiePorts = ports; } /** * Set the Discard attribute. * * Note: Discard attribute overrides Max-age. * * @see #isPersistent() */ public void setDiscard(boolean toDiscard) { discard = toDiscard; } /** * Returns false if the cookie should be discarded at the end * of the "session"; true otherwise. * * @return false if the cookie should be discarded at the end * of the "session"; true otherwise */ public boolean isPersistent() { return (null != getExpiryDate()) && !discard; } /** * Indicates whether the cookie had a port attribute specified in the * Set-Cookie2 response header. * * @param value true if port attribute is specified in response * header. * * @see #isPortAttributeSpecified */ public void setPortAttributeSpecified(boolean value) { hasPortAttribute = value; } /** * @return true if cookie port attribute was specified in the * Set-Cookie2 header. * * @see #setPortAttributeSpecified */ public boolean isPortAttributeSpecified() { return hasPortAttribute; } /** * Indicates whether the Port attribute in Set-Cookie2 header * contains no value (is of the form Port=""). *

* This value is required for generating * the Cookie request header because the specification requires that if * Set-Cookie2 header contains a blank value for port attribute, * the Cookie header should also contain a port attribute with no value. * * @param value true if port attribute is specified as blank in response * header. * * @see #isPortAttributeBlank */ public void setPortAttributeBlank(boolean value) { isPortAttributeBlank = value; } /** * @return true if the port attribute in Set-Cookie2 header * had no value (was of the form Port=""). * * @see #setPortAttributeBlank */ public boolean isPortAttributeBlank() { return isPortAttributeBlank; } /** * Indicates whether the cookie had a version attribute specified in the * Set-Cookie2 response header. * * @param value true if version attribute is specified in response * header. * @see #isVersionAttributeSpecified() */ public void setVersionAttributeSpecified(boolean value) { hasVersionAttribute = value; } /** * @return true if cookie version attribute was specified in the * Set-Cookie2 header. * * @see #setVersionAttributeSpecified */ public boolean isVersionAttributeSpecified() { return hasVersionAttribute; } /** * Return a textual representation of the cookie. * * @return string. */ public String toExternalForm() { CookieSpec spec = CookiePolicy.getCookieSpec(CookiePolicy.RFC_2965); return spec.formatCookie(this); } /** * Comment URL attribute */ private String cookieCommentURL; /** * Port attribute. */ private int[] cookiePorts; /** * Discard attribute. */ private boolean discard = false; /** * Indicates if the set-cookie2 header included a Port attribute for this * cookie */ private boolean hasPortAttribute = false; /** * Indicates if the set-cookie2 header's Port attribute did not have * any value. */ private boolean isPortAttributeBlank = false; /** * Indicates if the set-cookie2 header included a Version attribute */ private boolean hasVersionAttribute = false; } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/CookieAttributeHandler.java100644 0 0 6124 10661532626 30425 0ustar 0 0 /* * $HeadURL:https://svn.apache.org/repos/asf/jakarta/commons/proper/httpclient/trunk/src/java/org/apache/commons/httpclient/cookie/CookieAttributeHandler.java $ * $Revision:400312 $ * $Date:2006-05-06 14:49:41 +0200 (Sat, 06 May 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import org.apache.commons.httpclient.Cookie; /** * Ths interface represents a cookie attribute handler responsible * for parsing, validating, and matching a specific cookie attribute, * such as path, domain, port, etc. * * Different cookie specifications can provide a specific * implementation for this class based on their cookie handling * rules. * * @author jain.samit@gmail.com (Samit Jain) * * @since 3.1 */ public interface CookieAttributeHandler { /** * Parse the given cookie attribute value and update the corresponding * {@link org.apache.commons.httpclient.Cookie} property. * * @param cookie {@link org.apache.commons.httpclient.Cookie} to be updated * @param value cookie attribute value from the cookie response header */ void parse(Cookie cookie, String value) throws MalformedCookieException; /** * Peforms cookie validation for the given attribute value. * * @param cookie {@link org.apache.commons.httpclient.Cookie} to validate * @param origin the cookie source to validate against * @throws MalformedCookieException if cookie validation fails for this attribute */ void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException; /** * Matches the given value (property of the destination host where request is being * submitted) with the corresponding cookie attribute. * * @param cookie {@link org.apache.commons.httpclient.Cookie} to match * @param origin the cookie source to match against * @return true if the match is successful; false otherwise */ boolean match(Cookie cookie, CookieOrigin origin); } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/CookieOrigin.java100644 0 0 5513 10661532627 26415 0ustar 0 0 /* * $HeadURL:https://svn.apache.org/repos/asf/jakarta/commons/proper/httpclient/trunk/src/java/org/apache/commons/httpclient/cookie/CookieOrigin.java $ * $Revision:400312 $ * $Date:2006-05-06 14:49:41 +0200 (Sat, 06 May 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; /** * CookieOrigin class incapsulates details of an origin server that * are relevant when parsing, validating or matching HTTP cookies. * * @author Oleg Kalnichevski * * @since 3.1 */ public final class CookieOrigin { private final String host; private final int port; private final String path; private final boolean secure; public CookieOrigin(final String host, int port, final String path, boolean secure) { super(); if (host == null) { throw new IllegalArgumentException( "Host of origin may not be null"); } if (host.trim().equals("")) { throw new IllegalArgumentException( "Host of origin may not be blank"); } if (port < 0) { throw new IllegalArgumentException("Invalid port: " + port); } if (path == null) { throw new IllegalArgumentException( "Path of origin may not be null."); } this.host = host; this.port = port; this.path = path; this.secure = secure; } public String getHost() { return this.host; } public String getPath() { return this.path; } public int getPort() { return this.port; } public boolean isSecure() { return this.secure; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/CookiePathComparator.java100644 0 0 5252 10661532626 30111 0ustar 0 0 /* * $Header$ * $Revision:400312 $ * $Date:2006-05-06 14:49:41 +0200 (Sat, 06 May 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.Comparator; import org.apache.commons.httpclient.Cookie; /** * This cookie comparator ensures that multiple cookies satisfying * a common criteria are ordered in the Cookie header such * that those with more specific Path attributes precede those with * less specific. * *

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

* * @author Oleg Kalnichevski * * @since 3.1 */ public class CookiePathComparator implements Comparator { private String normalizePath(final Cookie cookie) { String path = cookie.getPath(); if (path == null) { path = "/"; } if (!path.endsWith("/")) { path = path + "/"; } return path; } public int compare(final Object o1, final Object o2) { Cookie c1 = (Cookie) o1; Cookie c2 = (Cookie) o2; String path1 = normalizePath(c1); String path2 = normalizePath(c2); if (path1.equals(path2)) { return 0; } else if (path1.startsWith(path2)) { return -1; } else if (path2.startsWith(path1)) { return 1; } else { // Does not really matter return 0; } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/CookiePolicy.java100644 0 0 25437 10661532626 26453 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/CookiePolicy.java,v 1.15 2004/09/14 20:11:31 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Cookie management policy class. The cookie policy provides corresponding * cookie management interfrace for a given type or version of cookie. *

RFC 2109 specification is used per default. Other supported specification * can be chosen when appropriate or set default when desired *

The following specifications are provided: *

    *
  • BROWSER_COMPATIBILITY: compatible with the common cookie * management practices (even if they are not 100% standards compliant) *
  • NETSCAPE: Netscape cookie draft compliant *
  • RFC_2109: RFC2109 compliant (default) *
  • IGNORE_COOKIES: do not automcatically process cookies *
* * @author Oleg Kalnichevski * @author Mike Bowler * * @since 2.0 */ public abstract class CookiePolicy { private static Map SPECS = Collections.synchronizedMap(new HashMap()); /** * The policy that provides high degree of compatibilty * with common cookie management of popular HTTP agents. * * @since 3.0 */ public static final String BROWSER_COMPATIBILITY = "compatibility"; /** * The Netscape cookie draft compliant policy. * * @since 3.0 */ public static final String NETSCAPE = "netscape"; /** * The RFC 2109 compliant policy. * * @since 3.0 */ public static final String RFC_2109 = "rfc2109"; /** * The RFC 2965 compliant policy. * * @since 3.0 */ public static final String RFC_2965 = "rfc2965"; /** * The policy that ignores cookies. * * @since 3.0 */ public static final String IGNORE_COOKIES = "ignoreCookies"; /** * The default cookie policy. * * @since 3.0 */ public static final String DEFAULT = "default"; static { CookiePolicy.registerCookieSpec(DEFAULT, RFC2109Spec.class); CookiePolicy.registerCookieSpec(RFC_2109, RFC2109Spec.class); CookiePolicy.registerCookieSpec(RFC_2965, RFC2965Spec.class); CookiePolicy.registerCookieSpec(BROWSER_COMPATIBILITY, CookieSpecBase.class); CookiePolicy.registerCookieSpec(NETSCAPE, NetscapeDraftSpec.class); CookiePolicy.registerCookieSpec(IGNORE_COOKIES, IgnoreCookiesSpec.class); } /** * The COMPATIBILITY policy provides high compatibilty * with common cookie management of popular HTTP agents. * * @deprecated Use {@link #BROWSER_COMPATIBILITY} */ public static final int COMPATIBILITY = 0; /** * The NETSCAPE_DRAFT Netscape draft compliant policy. * * @deprecated Use {@link #NETSCAPE} */ public static final int NETSCAPE_DRAFT = 1; /** * The RFC2109 RFC 2109 compliant policy. * * @deprecated Use {@link #RFC_2109} */ public static final int RFC2109 = 2; /** * The RFC2965 RFC 2965 compliant policy. * * @deprecated Use {@link #RFC_2965} */ public static final int RFC2965 = 3; /** * The default cookie policy. * * @deprecated Use {@link #DEFAULT} */ private static int defaultPolicy = RFC2109; /** Log object. */ protected static final Log LOG = LogFactory.getLog(CookiePolicy.class); /** * Registers a new {@link CookieSpec cookie specification} with the given identifier. * If a specification with the given ID already exists it will be overridden. * This ID is the same one used to retrieve the {@link CookieSpec cookie specification} * from {@link #getCookieSpec(String)}. * * @param id the identifier for this specification * @param clazz the {@link CookieSpec cookie specification} class to register * * @see #getCookieSpec(String) * * @since 3.0 */ public static void registerCookieSpec(final String id, final Class clazz) { if (id == null) { throw new IllegalArgumentException("Id may not be null"); } if (clazz == null) { throw new IllegalArgumentException("Cookie spec class may not be null"); } SPECS.put(id.toLowerCase(), clazz); } /** * Unregisters the {@link CookieSpec cookie specification} with the given ID. * * @param id the ID of the {@link CookieSpec cookie specification} to unregister * * @since 3.0 */ public static void unregisterCookieSpec(final String id) { if (id == null) { throw new IllegalArgumentException("Id may not be null"); } SPECS.remove(id.toLowerCase()); } /** * Gets the {@link CookieSpec cookie specification} with the given ID. * * @param id the {@link CookieSpec cookie specification} ID * * @return {@link CookieSpec cookie specification} * * @throws IllegalStateException if a policy with the ID cannot be found * * @since 3.0 */ public static CookieSpec getCookieSpec(final String id) throws IllegalStateException { if (id == null) { throw new IllegalArgumentException("Id may not be null"); } Class clazz = (Class)SPECS.get(id.toLowerCase()); if (clazz != null) { try { return (CookieSpec)clazz.newInstance(); } catch (Exception e) { LOG.error("Error initializing cookie spec: " + id, e); throw new IllegalStateException(id + " cookie spec implemented by " + clazz.getName() + " could not be initialized"); } } else { throw new IllegalStateException("Unsupported cookie spec " + id); } } /** * @return default cookie policy * * @deprecated Use {@link #getDefaultSpec()} * * @see #getDefaultSpec() */ public static int getDefaultPolicy() { return defaultPolicy; } /** * @param policy new default cookie policy * * @deprecated Use {@link CookiePolicy#registerCookieSpec(String, Class)} * @see #DEFAULT */ public static void setDefaultPolicy(int policy) { defaultPolicy = policy; } /** * @param policy cookie policy to get the CookieSpec for * @return cookie specification interface for the given policy * * @deprecated Use {@link CookiePolicy#getCookieSpec(String)} */ public static CookieSpec getSpecByPolicy(int policy) { switch(policy) { case COMPATIBILITY: return new CookieSpecBase(); case NETSCAPE_DRAFT: return new NetscapeDraftSpec(); case RFC2109: return new RFC2109Spec(); case RFC2965: return new RFC2965Spec(); default: return getDefaultSpec(); } } /** * Returns {@link CookieSpec cookie specification} registered as {@link #DEFAULT}. * If no default {@link CookieSpec cookie specification} has been registered, * {@link RFC2109Spec RFC2109 specification} is returned. * * @return default {@link CookieSpec cookie specification} * * @see #DEFAULT */ public static CookieSpec getDefaultSpec() { try { return getCookieSpec(DEFAULT); } catch (IllegalStateException e) { LOG.warn("Default cookie policy is not registered"); return new RFC2109Spec(); } } /** * Gets the CookieSpec for a particular cookie version. * *

Supported versions: *

    *
  • version 0 corresponds to the Netscape draft *
  • version 1 corresponds to the RFC 2109 *
  • Any other cookie value coresponds to the default spec *
      * * @param ver the cookie version to get the spec for * @return cookie specification interface intended for processing * cookies with the given version * * @deprecated Use {@link CookiePolicy#getCookieSpec(String)} */ public static CookieSpec getSpecByVersion(int ver) { switch(ver) { case 0: return new NetscapeDraftSpec(); case 1: return new RFC2109Spec(); default: return getDefaultSpec(); } } /** * @return cookie specification interface that provides high compatibilty * with common cookie management of popular HTTP agents * * @deprecated Use {@link CookiePolicy#getCookieSpec(String)} */ public static CookieSpec getCompatibilitySpec() { return getSpecByPolicy(COMPATIBILITY); } /** * Obtains the currently registered cookie policy names. * * Note that the DEFAULT policy (if present) is likely to be the same * as one of the other policies, but does not have to be. * * @return array of registered cookie policy names * * @since 3.1 */ public static String[] getRegisteredCookieSpecs(){ return (String[]) SPECS.keySet().toArray(new String [SPECS.size()]); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/CookieSpec.java100644 0 0 22714 10661532626 26101 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/CookieSpec.java,v 1.11 2004/09/14 20:11:31 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.Collection; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.Cookie; /** * Defines the cookie management specification. *

      Cookie management specification must define *

        *
      • rules of parsing "Set-Cookie" header *
      • rules of validation of parsed cookies *
      • formatting of "Cookie" header *
      * for a given host, port and path of origin * * @author Oleg Kalnichevski * @author Jeff Dever * * @since 2.0 */ public interface CookieSpec { /** Path delimiter */ static final String PATH_DELIM = "/"; /** Path delimiting charachter */ static final char PATH_DELIM_CHAR = PATH_DELIM.charAt(0); /** * Parse the "Set-Cookie" header value into Cookie array. * *

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

      * * @see #validate(String, int, String, boolean, Cookie) * * @param host the host which sent the Set-Cookie header * @param port the port which sent the Set-Cookie header * @param path the path which sent the Set-Cookie header * @param secure true when the Set-Cookie header * was received over secure conection * @param header the Set-Cookie received from the server * @return an array of Cookies parsed from the Set-Cookie value * @throws MalformedCookieException if an exception occurs during parsing * @throws IllegalArgumentException if an input parameter is illegal */ Cookie[] parse(String host, int port, String path, boolean secure, final String header) throws MalformedCookieException, IllegalArgumentException; /** * Parse the "Set-Cookie" Header into an array of Cookies. * *

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

      * * @see #validate(String, int, String, boolean, Cookie) * * @param host the host which sent the Set-Cookie header * @param port the port which sent the Set-Cookie header * @param path the path which sent the Set-Cookie header * @param secure true when the Set-Cookie header * was received over secure conection * @param header the Set-Cookie received from the server * @return an array of Cookies parsed from the header * @throws MalformedCookieException if an exception occurs during parsing * @throws IllegalArgumentException if an input parameter is illegal */ Cookie[] parse(String host, int port, String path, boolean secure, final Header header) throws MalformedCookieException, IllegalArgumentException; /** * Parse the cookie attribute and update the corresponsing Cookie * properties. * * @param attribute cookie attribute from the Set-Cookie * @param cookie the to be updated * @throws MalformedCookieException if an exception occurs during parsing * @throws IllegalArgumentException if an input parameter is illegal */ void parseAttribute(NameValuePair attribute, Cookie cookie) throws MalformedCookieException, IllegalArgumentException; /** * Validate the cookie according to validation rules defined by the * cookie specification. * * @param host the host from which the {@link Cookie} was received * @param port the port from which the {@link Cookie} was received * @param path the path from which the {@link Cookie} was received * @param secure true when the {@link Cookie} was received * using a secure connection * @param cookie the Cookie to validate * @throws MalformedCookieException if the cookie is invalid * @throws IllegalArgumentException if an input parameter is illegal */ void validate(String host, int port, String path, boolean secure, final Cookie cookie) throws MalformedCookieException, IllegalArgumentException; /** * Sets the {@link Collection} of date patterns used for parsing. The String patterns must be * compatible with {@link java.text.SimpleDateFormat}. * * @param datepatterns collection of date patterns */ void setValidDateFormats(Collection datepatterns); /** * Returns the {@link Collection} of date patterns used for parsing. The String patterns are compatible * with the {@link java.text.SimpleDateFormat}. * * @return collection of date patterns */ Collection getValidDateFormats(); /** * Determines if a Cookie matches a location. * * @param host the host to which the request is being submitted * @param port the port to which the request is being submitted * @param path the path to which the request is being submitted * @param secure true if the request is using a secure connection * @param cookie the Cookie to be matched * * @return true if the cookie should be submitted with a request * with given attributes, false otherwise. */ boolean match(String host, int port, String path, boolean secure, final Cookie cookie); /** * Determines which of an array of Cookies matches a location. * * @param host the host to which the request is being submitted * @param port the port to which the request is being submitted * (currenlty ignored) * @param path the path to which the request is being submitted * @param secure true if the request is using a secure protocol * @param cookies an array of Cookies to be matched * * @return true if the cookie should be submitted with a request * with given attributes, false otherwise. */ Cookie[] match(String host, int port, String path, boolean secure, final Cookie cookies[]); /** * Performs domain-match as defined by the cookie specification. * @param host The target host. * @param domain The cookie domain attribute. * @return true if the specified host matches the given domain. * * @since 3.0 */ boolean domainMatch(String host, String domain); /** * Performs path-match as defined by the cookie specification. * @param path The target path. * @param topmostPath The cookie path attribute. * @return true if the paths match * * @since 3.0 */ boolean pathMatch(String path, String topmostPath); /** * Create a "Cookie" header value for an array of cookies. * * @param cookie the cookie to be formatted as string * @return a string suitable for sending in a "Cookie" header. */ String formatCookie(Cookie cookie); /** * Create a "Cookie" header value for an array of cookies. * * @param cookies the Cookies to be formatted * @return a string suitable for sending in a Cookie header. * @throws IllegalArgumentException if an input parameter is illegal */ String formatCookies(Cookie[] cookies) throws IllegalArgumentException; /** * Create a "Cookie" Header for an array of Cookies. * * @param cookies the Cookies format into a Cookie header * @return a Header for the given Cookies. * @throws IllegalArgumentException if an input parameter is illegal */ Header formatCookieHeader(Cookie[] cookies) throws IllegalArgumentException; /** * Create a "Cookie" Header for single Cookie. * * @param cookie the Cookie format as a Cookie header * @return a Cookie header. * @throws IllegalArgumentException if an input parameter is illegal */ Header formatCookieHeader(Cookie cookie) throws IllegalArgumentException; } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java100644 0 0 57663 10661532627 26710 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java,v 1.28 2004/11/06 19:15:42 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HeaderElement; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.util.DateParseException; import org.apache.commons.httpclient.util.DateUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * Cookie management functions shared by all specification. * * @author B.C. Holmes * @author Park, Sung-Gu * @author Doug Sale * @author Rod Waldhoff * @author dIon Gillard * @author Sean C. Sullivan * @author John Evans * @author Marc A. Saegesser * @author Oleg Kalnichevski * @author Mike Bowler * * @since 2.0 */ public class CookieSpecBase implements CookieSpec { /** Log object */ protected static final Log LOG = LogFactory.getLog(CookieSpec.class); /** Valid date patterns */ private Collection datepatterns = null; /** Default constructor */ public CookieSpecBase() { super(); } /** * Parses the Set-Cookie value into an array of Cookies. * *

      The syntax for the Set-Cookie response header is: * *

            * set-cookie      =    "Set-Cookie:" cookies
            * cookies         =    1#cookie
            * cookie          =    NAME "=" VALUE * (";" cookie-av)
            * NAME            =    attr
            * VALUE           =    value
            * cookie-av       =    "Comment" "=" value
            *                 |    "Domain" "=" value
            *                 |    "Max-Age" "=" value
            *                 |    "Path" "=" value
            *                 |    "Secure"
            *                 |    "Version" "=" 1*DIGIT
            * 
      * * @param host the host from which the Set-Cookie value was * received * @param port the port from which the Set-Cookie value was * received * @param path the path from which the Set-Cookie value was * received * @param secure true when the Set-Cookie value was * received over secure conection * @param header the Set-Cookie received from the server * @return an array of Cookies parsed from the Set-Cookie value * @throws MalformedCookieException if an exception occurs during parsing */ public Cookie[] parse(String host, int port, String path, boolean secure, final String header) throws MalformedCookieException { LOG.trace("enter CookieSpecBase.parse(" + "String, port, path, boolean, Header)"); if (host == null) { throw new IllegalArgumentException( "Host of origin may not be null"); } if (host.trim().equals("")) { throw new IllegalArgumentException( "Host of origin may not be blank"); } if (port < 0) { throw new IllegalArgumentException("Invalid port: " + port); } if (path == null) { throw new IllegalArgumentException( "Path of origin may not be null."); } if (header == null) { throw new IllegalArgumentException("Header may not be null."); } if (path.trim().equals("")) { path = PATH_DELIM; } host = host.toLowerCase(); String defaultPath = path; int lastSlashIndex = defaultPath.lastIndexOf(PATH_DELIM); if (lastSlashIndex >= 0) { if (lastSlashIndex == 0) { //Do not remove the very first slash lastSlashIndex = 1; } defaultPath = defaultPath.substring(0, lastSlashIndex); } HeaderElement[] headerElements = null; boolean isNetscapeCookie = false; int i1 = header.toLowerCase().indexOf("expires="); if (i1 != -1) { i1 += "expires=".length(); int i2 = header.indexOf(";", i1); if (i2 == -1) { i2 = header.length(); } try { DateUtil.parseDate(header.substring(i1, i2), this.datepatterns); isNetscapeCookie = true; } catch (DateParseException e) { // Does not look like a valid expiry date } } if (isNetscapeCookie) { headerElements = new HeaderElement[] { new HeaderElement(header.toCharArray()) }; } else { headerElements = HeaderElement.parseElements(header.toCharArray()); } Cookie[] cookies = new Cookie[headerElements.length]; for (int i = 0; i < headerElements.length; i++) { HeaderElement headerelement = headerElements[i]; Cookie cookie = null; try { cookie = new Cookie(host, headerelement.getName(), headerelement.getValue(), defaultPath, null, false); } catch (IllegalArgumentException e) { throw new MalformedCookieException(e.getMessage()); } // cycle through the parameters NameValuePair[] parameters = headerelement.getParameters(); // could be null. In case only a header element and no parameters. if (parameters != null) { for (int j = 0; j < parameters.length; j++) { parseAttribute(parameters[j], cookie); } } cookies[i] = cookie; } return cookies; } /** * Parse the "Set-Cookie" {@link Header} into an array of {@link * Cookie}s. * *

      The syntax for the Set-Cookie response header is: * *

            * set-cookie      =    "Set-Cookie:" cookies
            * cookies         =    1#cookie
            * cookie          =    NAME "=" VALUE * (";" cookie-av)
            * NAME            =    attr
            * VALUE           =    value
            * cookie-av       =    "Comment" "=" value
            *                 |    "Domain" "=" value
            *                 |    "Max-Age" "=" value
            *                 |    "Path" "=" value
            *                 |    "Secure"
            *                 |    "Version" "=" 1*DIGIT
            * 
      * * @param host the host from which the Set-Cookie header was * received * @param port the port from which the Set-Cookie header was * received * @param path the path from which the Set-Cookie header was * received * @param secure true when the Set-Cookie header was * received over secure conection * @param header the Set-Cookie received from the server * @return an array of Cookies parsed from the "Set-Cookie" * header * @throws MalformedCookieException if an exception occurs during parsing */ public Cookie[] parse( String host, int port, String path, boolean secure, final Header header) throws MalformedCookieException { LOG.trace("enter CookieSpecBase.parse(" + "String, port, path, boolean, String)"); if (header == null) { throw new IllegalArgumentException("Header may not be null."); } return parse(host, port, path, secure, header.getValue()); } /** * Parse the cookie attribute and update the corresponsing {@link Cookie} * properties. * * @param attribute {@link HeaderElement} cookie attribute from the * Set- Cookie * @param cookie {@link Cookie} to be updated * @throws MalformedCookieException if an exception occurs during parsing */ public void parseAttribute( final NameValuePair attribute, final Cookie cookie) throws MalformedCookieException { if (attribute == null) { throw new IllegalArgumentException("Attribute may not be null."); } if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null."); } final String paramName = attribute.getName().toLowerCase(); String paramValue = attribute.getValue(); if (paramName.equals("path")) { if ((paramValue == null) || (paramValue.trim().equals(""))) { paramValue = "/"; } cookie.setPath(paramValue); cookie.setPathAttributeSpecified(true); } else if (paramName.equals("domain")) { if (paramValue == null) { throw new MalformedCookieException( "Missing value for domain attribute"); } if (paramValue.trim().equals("")) { throw new MalformedCookieException( "Blank value for domain attribute"); } cookie.setDomain(paramValue); cookie.setDomainAttributeSpecified(true); } else if (paramName.equals("max-age")) { if (paramValue == null) { throw new MalformedCookieException( "Missing value for max-age attribute"); } int age; try { age = Integer.parseInt(paramValue); } catch (NumberFormatException e) { throw new MalformedCookieException ("Invalid max-age " + "attribute: " + e.getMessage()); } cookie.setExpiryDate( new Date(System.currentTimeMillis() + age * 1000L)); } else if (paramName.equals("secure")) { cookie.setSecure(true); } else if (paramName.equals("comment")) { cookie.setComment(paramValue); } else if (paramName.equals("expires")) { if (paramValue == null) { throw new MalformedCookieException( "Missing value for expires attribute"); } try { cookie.setExpiryDate(DateUtil.parseDate(paramValue, this.datepatterns)); } catch (DateParseException dpe) { LOG.debug("Error parsing cookie date", dpe); throw new MalformedCookieException( "Unable to parse expiration date parameter: " + paramValue); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Unrecognized cookie attribute: " + attribute.toString()); } } } public Collection getValidDateFormats() { return this.datepatterns; } public void setValidDateFormats(final Collection datepatterns) { this.datepatterns = datepatterns; } /** * Performs most common {@link Cookie} validation * * @param host the host from which the {@link Cookie} was received * @param port the port from which the {@link Cookie} was received * @param path the path from which the {@link Cookie} was received * @param secure true when the {@link Cookie} was received using a * secure connection * @param cookie The cookie to validate. * @throws MalformedCookieException if an exception occurs during * validation */ public void validate(String host, int port, String path, boolean secure, final Cookie cookie) throws MalformedCookieException { LOG.trace("enter CookieSpecBase.validate(" + "String, port, path, boolean, Cookie)"); if (host == null) { throw new IllegalArgumentException( "Host of origin may not be null"); } if (host.trim().equals("")) { throw new IllegalArgumentException( "Host of origin may not be blank"); } if (port < 0) { throw new IllegalArgumentException("Invalid port: " + port); } if (path == null) { throw new IllegalArgumentException( "Path of origin may not be null."); } if (path.trim().equals("")) { path = PATH_DELIM; } host = host.toLowerCase(); // check version if (cookie.getVersion() < 0) { throw new MalformedCookieException ("Illegal version number " + cookie.getValue()); } // security check... we musn't allow the server to give us an // invalid domain scope // Validate the cookies domain attribute. NOTE: Domains without // any dots are allowed to support hosts on private LANs that don't // have DNS names. Since they have no dots, to domain-match the // request-host and domain must be identical for the cookie to sent // back to the origin-server. if (host.indexOf(".") >= 0) { // Not required to have at least two dots. RFC 2965. // A Set-Cookie2 with Domain=ajax.com will be accepted. // domain must match host if (!host.endsWith(cookie.getDomain())) { String s = cookie.getDomain(); if (s.startsWith(".")) { s = s.substring(1, s.length()); } if (!host.equals(s)) { throw new MalformedCookieException( "Illegal domain attribute \"" + cookie.getDomain() + "\". Domain of origin: \"" + host + "\""); } } } else { if (!host.equals(cookie.getDomain())) { throw new MalformedCookieException( "Illegal domain attribute \"" + cookie.getDomain() + "\". Domain of origin: \"" + host + "\""); } } // another security check... we musn't allow the server to give us a // cookie that doesn't match this path if (!path.startsWith(cookie.getPath())) { throw new MalformedCookieException( "Illegal path attribute \"" + cookie.getPath() + "\". Path of origin: \"" + path + "\""); } } /** * Return true if the cookie should be submitted with a request * with given attributes, false otherwise. * @param host the host to which the request is being submitted * @param port the port to which the request is being submitted (ignored) * @param path the path to which the request is being submitted * @param secure true if the request is using a secure connection * @param cookie {@link Cookie} to be matched * @return true if the cookie matches the criterium */ public boolean match(String host, int port, String path, boolean secure, final Cookie cookie) { LOG.trace("enter CookieSpecBase.match(" + "String, int, String, boolean, Cookie"); if (host == null) { throw new IllegalArgumentException( "Host of origin may not be null"); } if (host.trim().equals("")) { throw new IllegalArgumentException( "Host of origin may not be blank"); } if (port < 0) { throw new IllegalArgumentException("Invalid port: " + port); } if (path == null) { throw new IllegalArgumentException( "Path of origin may not be null."); } if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (path.trim().equals("")) { path = PATH_DELIM; } host = host.toLowerCase(); if (cookie.getDomain() == null) { LOG.warn("Invalid cookie state: domain not specified"); return false; } if (cookie.getPath() == null) { LOG.warn("Invalid cookie state: path not specified"); return false; } return // only add the cookie if it hasn't yet expired (cookie.getExpiryDate() == null || cookie.getExpiryDate().after(new Date())) // and the domain pattern matches && (domainMatch(host, cookie.getDomain())) // and the path is null or matching && (pathMatch(path, cookie.getPath())) // and if the secure flag is set, only if the request is // actually secure && (cookie.getSecure() ? secure : true); } /** * Performs domain-match as implemented in common browsers. * @param host The target host. * @param domain The cookie domain attribute. * @return true if the specified host matches the given domain. */ public boolean domainMatch(final String host, String domain) { if (host.equals(domain)) { return true; } if (!domain.startsWith(".")) { domain = "." + domain; } return host.endsWith(domain) || host.equals(domain.substring(1)); } /** * Performs path-match as implemented in common browsers. * @param path The target path. * @param topmostPath The cookie path attribute. * @return true if the paths match */ public boolean pathMatch(final String path, final String topmostPath) { boolean match = path.startsWith (topmostPath); // if there is a match and these values are not exactly the same we have // to make sure we're not matcing "/foobar" and "/foo" if (match && path.length() != topmostPath.length()) { if (!topmostPath.endsWith(PATH_DELIM)) { match = (path.charAt(topmostPath.length()) == PATH_DELIM_CHAR); } } return match; } /** * Return an array of {@link Cookie}s that should be submitted with a * request with given attributes, false otherwise. * @param host the host to which the request is being submitted * @param port the port to which the request is being submitted (currently * ignored) * @param path the path to which the request is being submitted * @param secure true if the request is using a secure protocol * @param cookies an array of Cookies to be matched * @return an array of Cookies matching the criterium */ public Cookie[] match(String host, int port, String path, boolean secure, final Cookie cookies[]) { LOG.trace("enter CookieSpecBase.match(" + "String, int, String, boolean, Cookie[])"); if (cookies == null) { return null; } List matching = new LinkedList(); for (int i = 0; i < cookies.length; i++) { if (match(host, port, path, secure, cookies[i])) { addInPathOrder(matching, cookies[i]); } } return (Cookie[]) matching.toArray(new Cookie[matching.size()]); } /** * Adds the given cookie into the given list in descending path order. That * is, more specific path to least specific paths. This may not be the * fastest algorythm, but it'll work OK for the small number of cookies * we're generally dealing with. * * @param list - the list to add the cookie to * @param addCookie - the Cookie to add to list */ private static void addInPathOrder(List list, Cookie addCookie) { int i = 0; for (i = 0; i < list.size(); i++) { Cookie c = (Cookie) list.get(i); if (addCookie.compare(addCookie, c) > 0) { break; } } list.add(i, addCookie); } /** * Return a string suitable for sending in a "Cookie" header * @param cookie a {@link Cookie} to be formatted as string * @return a string suitable for sending in a "Cookie" header. */ public String formatCookie(Cookie cookie) { LOG.trace("enter CookieSpecBase.formatCookie(Cookie)"); if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } StringBuffer buf = new StringBuffer(); buf.append(cookie.getName()); buf.append("="); String s = cookie.getValue(); if (s != null) { buf.append(s); } return buf.toString(); } /** * Create a "Cookie" header value containing all {@link Cookie}s in * cookies suitable for sending in a "Cookie" header * @param cookies an array of {@link Cookie}s to be formatted * @return a string suitable for sending in a Cookie header. * @throws IllegalArgumentException if an input parameter is illegal */ public String formatCookies(Cookie[] cookies) throws IllegalArgumentException { LOG.trace("enter CookieSpecBase.formatCookies(Cookie[])"); if (cookies == null) { throw new IllegalArgumentException("Cookie array may not be null"); } if (cookies.length == 0) { throw new IllegalArgumentException("Cookie array may not be empty"); } StringBuffer buffer = new StringBuffer(); for (int i = 0; i < cookies.length; i++) { if (i > 0) { buffer.append("; "); } buffer.append(formatCookie(cookies[i])); } return buffer.toString(); } /** * Create a "Cookie" {@link Header} containing all {@link Cookie}s * in cookies. * @param cookies an array of {@link Cookie}s to be formatted as a " * Cookie" header * @return a "Cookie" {@link Header}. */ public Header formatCookieHeader(Cookie[] cookies) { LOG.trace("enter CookieSpecBase.formatCookieHeader(Cookie[])"); return new Header("Cookie", formatCookies(cookies)); } /** * Create a "Cookie" {@link Header} containing the {@link Cookie}. * @param cookie Cookies to be formatted as a Cookie * header * @return a Cookie header. */ public Header formatCookieHeader(Cookie cookie) { LOG.trace("enter CookieSpecBase.formatCookieHeader(Cookie)"); return new Header("Cookie", formatCookie(cookie)); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/CookieVersionSupport.java100644 0 0 3147 10661532626 30210 0ustar 0 0 /* * $Header: $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import org.apache.commons.httpclient.Header; /** * Defines cookie specification specific capabilities * * @author Oleg Kalnichevski * * @since 3.1 */ public interface CookieVersionSupport { int getVersion(); Header getVersionHeader(); } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.java100644 0 0 10672 10661532627 27431 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.java,v 1.6 2004/09/14 20:11:31 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.Collection; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.NameValuePair; /** * A cookie spec that does nothing. Cookies are neither parsed, formatted nor matched. * It can be used to effectively disable cookies altogether. * * @since 3.0 */ public class IgnoreCookiesSpec implements CookieSpec { /** * */ public IgnoreCookiesSpec() { super(); } /** * Returns an empty {@link Cookie cookie} array. All parameters are ignored. */ public Cookie[] parse(String host, int port, String path, boolean secure, String header) throws MalformedCookieException { return new Cookie[0]; } /** * @return null */ public Collection getValidDateFormats() { return null; } /** * Does nothing. */ public void setValidDateFormats(Collection datepatterns) { } /** * @return null */ public String formatCookie(Cookie cookie) { return null; } /** * @return null */ public Header formatCookieHeader(Cookie cookie) throws IllegalArgumentException { return null; } /** * @return null */ public Header formatCookieHeader(Cookie[] cookies) throws IllegalArgumentException { return null; } /** * @return null */ public String formatCookies(Cookie[] cookies) throws IllegalArgumentException { return null; } /** * @return false */ public boolean match(String host, int port, String path, boolean secure, Cookie cookie) { return false; } /** * Returns an empty {@link Cookie cookie} array. All parameters are ignored. */ public Cookie[] match(String host, int port, String path, boolean secure, Cookie[] cookies) { return new Cookie[0]; } /** * Returns an empty {@link Cookie cookie} array. All parameters are ignored. */ public Cookie[] parse(String host, int port, String path, boolean secure, Header header) throws MalformedCookieException, IllegalArgumentException { return new Cookie[0]; } /** * Does nothing. */ public void parseAttribute(NameValuePair attribute, Cookie cookie) throws MalformedCookieException, IllegalArgumentException { } /** * Does nothing. */ public void validate(String host, int port, String path, boolean secure, Cookie cookie) throws MalformedCookieException, IllegalArgumentException { } /** * @return false */ public boolean domainMatch(final String host, final String domain) { return false; } /** * @return false */ public boolean pathMatch(final String path, final String topmostPath) { return false; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/MalformedCookieException.java100644 0 0 5222 10661532626 30747 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/MalformedCookieException.java,v 1.8 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import org.apache.commons.httpclient.ProtocolException; /** * Signals that a cookie is in some way invalid or illegal in a given * context * * @author Oleg Kalnichevski * * @since 2.0 */ public class MalformedCookieException extends ProtocolException { /** * Creates a new MalformedCookieException with a null detail message. */ public MalformedCookieException() { super(); } /** * Creates a new MalformedCookieException with a specified message string. * * @param message The exception detail message */ public MalformedCookieException(String message) { super(message); } /** * Creates a new MalformedCookieException with the specified detail message and cause. * * @param message the exception detail message * @param cause the Throwable that caused this exception, or null * if the cause is unavailable, unknown, or not a Throwable * * @since 3.0 */ public MalformedCookieException(String message, Throwable cause) { super(message, cause); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/NetscapeDraftSpec.java100644 0 0 24635 10661532626 27417 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/NetscapeDraftSpec.java,v 1.11 2004/05/13 04:02:00 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.StringTokenizer; import java.util.Date; import java.util.Locale; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import org.apache.commons.httpclient.HeaderElement; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.Cookie; /** *

      Netscape cookie draft specific cookie management functions * * @author B.C. Holmes * @author Park, Sung-Gu * @author Doug Sale * @author Rod Waldhoff * @author dIon Gillard * @author Sean C. Sullivan * @author John Evans * @author Marc A. Saegesser * @author Oleg Kalnichevski * @author Mike Bowler * * @since 2.0 */ public class NetscapeDraftSpec extends CookieSpecBase { /** Default constructor */ public NetscapeDraftSpec() { super(); } /** * Parses the Set-Cookie value into an array of Cookies. * *

      Syntax of the Set-Cookie HTTP Response Header:

      * *

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

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

      Please note that Netscape draft specification does not fully * conform to the HTTP header format. Netscape draft does not specify * whether multiple cookies may be sent in one header. Hence, comma * character may be present in unquoted cookie value or unquoted * parameter value.

      * * @link http://wp.netscape.com/newsref/std/cookie_spec.html * * @param host the host from which the Set-Cookie value was * received * @param port the port from which the Set-Cookie value was * received * @param path the path from which the Set-Cookie value was * received * @param secure true when the Set-Cookie value was * received over secure conection * @param header the Set-Cookie received from the server * @return an array of Cookies parsed from the Set-Cookie value * @throws MalformedCookieException if an exception occurs during parsing * * @since 3.0 */ public Cookie[] parse(String host, int port, String path, boolean secure, final String header) throws MalformedCookieException { LOG.trace("enter NetscapeDraftSpec.parse(String, port, path, boolean, Header)"); if (host == null) { throw new IllegalArgumentException("Host of origin may not be null"); } if (host.trim().equals("")) { throw new IllegalArgumentException("Host of origin may not be blank"); } if (port < 0) { throw new IllegalArgumentException("Invalid port: " + port); } if (path == null) { throw new IllegalArgumentException("Path of origin may not be null."); } if (header == null) { throw new IllegalArgumentException("Header may not be null."); } if (path.trim().equals("")) { path = PATH_DELIM; } host = host.toLowerCase(); String defaultPath = path; int lastSlashIndex = defaultPath.lastIndexOf(PATH_DELIM); if (lastSlashIndex >= 0) { if (lastSlashIndex == 0) { //Do not remove the very first slash lastSlashIndex = 1; } defaultPath = defaultPath.substring(0, lastSlashIndex); } HeaderElement headerelement = new HeaderElement(header.toCharArray()); Cookie cookie = new Cookie(host, headerelement.getName(), headerelement.getValue(), defaultPath, null, false); // cycle through the parameters NameValuePair[] parameters = headerelement.getParameters(); // could be null. In case only a header element and no parameters. if (parameters != null) { for (int j = 0; j < parameters.length; j++) { parseAttribute(parameters[j], cookie); } } return new Cookie[] {cookie}; } /** * Parse the cookie attribute and update the corresponsing {@link Cookie} * properties as defined by the Netscape draft specification * * @param attribute {@link NameValuePair} cookie attribute from the * Set- Cookie * @param cookie {@link Cookie} to be updated * @throws MalformedCookieException if an exception occurs during parsing */ public void parseAttribute( final NameValuePair attribute, final Cookie cookie) throws MalformedCookieException { if (attribute == null) { throw new IllegalArgumentException("Attribute may not be null."); } if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null."); } final String paramName = attribute.getName().toLowerCase(); final String paramValue = attribute.getValue(); if (paramName.equals("expires")) { if (paramValue == null) { throw new MalformedCookieException( "Missing value for expires attribute"); } try { DateFormat expiryFormat = new SimpleDateFormat( "EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US); Date date = expiryFormat.parse(paramValue); cookie.setExpiryDate(date); } catch (ParseException e) { throw new MalformedCookieException("Invalid expires " + "attribute: " + e.getMessage()); } } else { super.parseAttribute(attribute, cookie); } } /** * Performs domain-match as described in the Netscape draft. * @param host The target host. * @param domain The cookie domain attribute. * @return true if the specified host matches the given domain. */ public boolean domainMatch(final String host, final String domain) { return host.endsWith(domain); } /** * Performs Netscape draft compliant {@link Cookie} validation * * @param host the host from which the {@link Cookie} was received * @param port the port from which the {@link Cookie} was received * @param path the path from which the {@link Cookie} was received * @param secure true when the {@link Cookie} was received * using a secure connection * @param cookie The cookie to validate. * @throws MalformedCookieException if an exception occurs during * validation */ public void validate(String host, int port, String path, boolean secure, final Cookie cookie) throws MalformedCookieException { LOG.trace("enterNetscapeDraftCookieProcessor " + "RCF2109CookieProcessor.validate(Cookie)"); // Perform generic validation super.validate(host, port, path, secure, cookie); // Perform Netscape Cookie draft specific validation if (host.indexOf(".") >= 0) { int domainParts = new StringTokenizer(cookie.getDomain(), ".") .countTokens(); if (isSpecialDomain(cookie.getDomain())) { if (domainParts < 2) { throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates the Netscape cookie specification for " + "special domains"); } } else { if (domainParts < 3) { throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates the Netscape cookie specification"); } } } } /** * Checks if the given domain is in one of the seven special * top level domains defined by the Netscape cookie specification. * @param domain The domain. * @return True if the specified domain is "special" */ private static boolean isSpecialDomain(final String domain) { final String ucDomain = domain.toUpperCase(); if (ucDomain.endsWith(".COM") || ucDomain.endsWith(".EDU") || ucDomain.endsWith(".NET") || ucDomain.endsWith(".GOV") || ucDomain.endsWith(".MIL") || ucDomain.endsWith(".ORG") || ucDomain.endsWith(".INT")) { return true; } return false; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/RFC2109Spec.java100644 0 0 26564 10661532627 25626 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/RFC2109Spec.java,v 1.21 2004/06/05 16:49:20 olegk Exp $ * $Revision: 507134 $ * $Date: 2007-02-13 19:18:05 +0100 (Tue, 13 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.util.ParameterFormatter; /** *

      RFC 2109 specific cookie management functions * * @author B.C. Holmes * @author Park, Sung-Gu * @author Doug Sale * @author Rod Waldhoff * @author dIon Gillard * @author Sean C. Sullivan * @author John Evans * @author Marc A. Saegesser * @author Oleg Kalnichevski * @author Mike Bowler * * @since 2.0 */ public class RFC2109Spec extends CookieSpecBase { private final ParameterFormatter formatter; /** * Cookie Response Header name for cookies processed * by this spec. */ public final static String SET_COOKIE_KEY = "set-cookie"; /** Default constructor */ public RFC2109Spec() { super(); this.formatter = new ParameterFormatter(); this.formatter.setAlwaysUseQuotes(true); } /** * Parse RFC 2109 specific cookie attribute and update the corresponsing * {@link Cookie} properties. * * @param attribute {@link NameValuePair} cookie attribute from the * Set- Cookie * @param cookie {@link Cookie} to be updated * @throws MalformedCookieException if an exception occurs during parsing */ public void parseAttribute( final NameValuePair attribute, final Cookie cookie) throws MalformedCookieException { if (attribute == null) { throw new IllegalArgumentException("Attribute may not be null."); } if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null."); } final String paramName = attribute.getName().toLowerCase(); final String paramValue = attribute.getValue(); if (paramName.equals("path")) { if (paramValue == null) { throw new MalformedCookieException( "Missing value for path attribute"); } if (paramValue.trim().equals("")) { throw new MalformedCookieException( "Blank value for path attribute"); } cookie.setPath(paramValue); cookie.setPathAttributeSpecified(true); } else if (paramName.equals("version")) { if (paramValue == null) { throw new MalformedCookieException( "Missing value for version attribute"); } try { cookie.setVersion(Integer.parseInt(paramValue)); } catch (NumberFormatException e) { throw new MalformedCookieException("Invalid version: " + e.getMessage()); } } else { super.parseAttribute(attribute, cookie); } } /** * Performs RFC 2109 compliant {@link Cookie} validation * * @param host the host from which the {@link Cookie} was received * @param port the port from which the {@link Cookie} was received * @param path the path from which the {@link Cookie} was received * @param secure true when the {@link Cookie} was received using a * secure connection * @param cookie The cookie to validate * @throws MalformedCookieException if an exception occurs during * validation */ public void validate(String host, int port, String path, boolean secure, final Cookie cookie) throws MalformedCookieException { LOG.trace("enter RFC2109Spec.validate(String, int, String, " + "boolean, Cookie)"); // Perform generic validation super.validate(host, port, path, secure, cookie); // Perform RFC 2109 specific validation if (cookie.getName().indexOf(' ') != -1) { throw new MalformedCookieException("Cookie name may not contain blanks"); } if (cookie.getName().startsWith("$")) { throw new MalformedCookieException("Cookie name may not start with $"); } if (cookie.isDomainAttributeSpecified() && (!cookie.getDomain().equals(host))) { // domain must start with dot if (!cookie.getDomain().startsWith(".")) { throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot"); } // domain must have at least one embedded dot int dotIndex = cookie.getDomain().indexOf('.', 1); if (dotIndex < 0 || dotIndex == cookie.getDomain().length() - 1) { throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2109: domain must contain an embedded dot"); } host = host.toLowerCase(); if (!host.endsWith(cookie.getDomain())) { throw new MalformedCookieException( "Illegal domain attribute \"" + cookie.getDomain() + "\". Domain of origin: \"" + host + "\""); } // host minus domain may not contain any dots String hostWithoutDomain = host.substring(0, host.length() - cookie.getDomain().length()); if (hostWithoutDomain.indexOf('.') != -1) { throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2109: host minus domain may not contain any dots"); } } } /** * Performs domain-match as defined by the RFC2109. * @param host The target host. * @param domain The cookie domain attribute. * @return true if the specified host matches the given domain. * * @since 3.0 */ public boolean domainMatch(String host, String domain) { boolean match = host.equals(domain) || (domain.startsWith(".") && host.endsWith(domain)); return match; } /** * Return a name/value string suitable for sending in a "Cookie" * header as defined in RFC 2109 for backward compatibility with cookie * version 0 * @param buffer The string buffer to use for output * @param param The parameter. * @param version The cookie version */ private void formatParam(final StringBuffer buffer, final NameValuePair param, int version) { if (version < 1) { buffer.append(param.getName()); buffer.append("="); if (param.getValue() != null) { buffer.append(param.getValue()); } } else { this.formatter.format(buffer, param); } } /** * Return a string suitable for sending in a "Cookie" header * as defined in RFC 2109 for backward compatibility with cookie version 0 * @param buffer The string buffer to use for output * @param cookie The {@link Cookie} to be formatted as string * @param version The version to use. */ private void formatCookieAsVer(final StringBuffer buffer, final Cookie cookie, int version) { String value = cookie.getValue(); if (value == null) { value = ""; } formatParam(buffer, new NameValuePair(cookie.getName(), value), version); if ((cookie.getPath() != null) && cookie.isPathAttributeSpecified()) { buffer.append("; "); formatParam(buffer, new NameValuePair("$Path", cookie.getPath()), version); } if ((cookie.getDomain() != null) && cookie.isDomainAttributeSpecified()) { buffer.append("; "); formatParam(buffer, new NameValuePair("$Domain", cookie.getDomain()), version); } } /** * Return a string suitable for sending in a "Cookie" header as * defined in RFC 2109 * @param cookie a {@link Cookie} to be formatted as string * @return a string suitable for sending in a "Cookie" header. */ public String formatCookie(Cookie cookie) { LOG.trace("enter RFC2109Spec.formatCookie(Cookie)"); if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } int version = cookie.getVersion(); StringBuffer buffer = new StringBuffer(); formatParam(buffer, new NameValuePair("$Version", Integer.toString(version)), version); buffer.append("; "); formatCookieAsVer(buffer, cookie, version); return buffer.toString(); } /** * Create a RFC 2109 compliant "Cookie" header value containing all * {@link Cookie}s in cookies suitable for sending in a "Cookie" * header * @param cookies an array of {@link Cookie}s to be formatted * @return a string suitable for sending in a Cookie header. */ public String formatCookies(Cookie[] cookies) { LOG.trace("enter RFC2109Spec.formatCookieHeader(Cookie[])"); int version = Integer.MAX_VALUE; // Pick the lowerest common denominator for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getVersion() < version) { version = cookie.getVersion(); } } final StringBuffer buffer = new StringBuffer(); formatParam(buffer, new NameValuePair("$Version", Integer.toString(version)), version); for (int i = 0; i < cookies.length; i++) { buffer.append("; "); formatCookieAsVer(buffer, cookies[i], version); } return buffer.toString(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/RFC2965Spec.java100644 0 0 125437 10661532626 25656 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/cookie/RFC2965Spec.java $ * $Revision: 507134 $ * $Date: 2007-02-13 19:18:05 +0100 (Tue, 13 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HeaderElement; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.util.ParameterFormatter; /** *

      RFC 2965 specific cookie management functions.

      * * @author jain.samit@gmail.com (Samit Jain) * * @since 3.1 */ public class RFC2965Spec extends CookieSpecBase implements CookieVersionSupport { private static final Comparator PATH_COMPOARATOR = new CookiePathComparator(); /** * Cookie Response Header name for cookies processed * by this spec. */ public final static String SET_COOKIE2_KEY = "set-cookie2"; /** * used for formatting RFC 2956 style cookies */ private final ParameterFormatter formatter; /** * Stores the list of attribute handlers */ private final List attribHandlerList; /** * Stores attribute name -> attribute handler mappings */ private final Map attribHandlerMap; /** * Fallback cookie spec (RFC 2109) */ private final CookieSpec rfc2109; /** * Default constructor * */ public RFC2965Spec() { super(); this.formatter = new ParameterFormatter(); this.formatter.setAlwaysUseQuotes(true); this.attribHandlerMap = new HashMap(10); this.attribHandlerList = new ArrayList(10); this.rfc2109 = new RFC2109Spec(); registerAttribHandler(Cookie2.PATH, new Cookie2PathAttributeHandler()); registerAttribHandler(Cookie2.DOMAIN, new Cookie2DomainAttributeHandler()); registerAttribHandler(Cookie2.PORT, new Cookie2PortAttributeHandler()); registerAttribHandler(Cookie2.MAXAGE, new Cookie2MaxageAttributeHandler()); registerAttribHandler(Cookie2.SECURE, new CookieSecureAttributeHandler()); registerAttribHandler(Cookie2.COMMENT, new CookieCommentAttributeHandler()); registerAttribHandler(Cookie2.COMMENTURL, new CookieCommentUrlAttributeHandler()); registerAttribHandler(Cookie2.DISCARD, new CookieDiscardAttributeHandler()); registerAttribHandler(Cookie2.VERSION, new Cookie2VersionAttributeHandler()); } protected void registerAttribHandler( final String name, final CookieAttributeHandler handler) { if (name == null) { throw new IllegalArgumentException("Attribute name may not be null"); } if (handler == null) { throw new IllegalArgumentException("Attribute handler may not be null"); } if (!this.attribHandlerList.contains(handler)) { this.attribHandlerList.add(handler); } this.attribHandlerMap.put(name, handler); } /** * Finds an attribute handler {@link CookieAttributeHandler} for the * given attribute. Returns null if no attribute handler is * found for the specified attribute. * * @param name attribute name. e.g. Domain, Path, etc. * @return an attribute handler or null */ protected CookieAttributeHandler findAttribHandler(final String name) { return (CookieAttributeHandler) this.attribHandlerMap.get(name); } /** * Gets attribute handler {@link CookieAttributeHandler} for the * given attribute. * * @param name attribute name. e.g. Domain, Path, etc. * @throws IllegalStateException if handler not found for the * specified attribute. */ protected CookieAttributeHandler getAttribHandler(final String name) { CookieAttributeHandler handler = findAttribHandler(name); if (handler == null) { throw new IllegalStateException("Handler not registered for " + name + " attribute."); } else { return handler; } } protected Iterator getAttribHandlerIterator() { return this.attribHandlerList.iterator(); } /** * Parses the Set-Cookie2 value into an array of Cookies. * *

      The syntax for the Set-Cookie2 response header is: * *

           * set-cookie      =    "Set-Cookie2:" cookies
           * cookies         =    1#cookie
           * cookie          =    NAME "=" VALUE * (";" cookie-av)
           * NAME            =    attr
           * VALUE           =    value
           * cookie-av       =    "Comment" "=" value
           *                 |    "CommentURL" "=" <"> http_URL <">
           *                 |    "Discard"
           *                 |    "Domain" "=" value
           *                 |    "Max-Age" "=" value
           *                 |    "Path" "=" value
           *                 |    "Port" [ "=" <"> portlist <"> ]
           *                 |    "Secure"
           *                 |    "Version" "=" 1*DIGIT
           * portlist        =       1#portnum
           * portnum         =       1*DIGIT
           * 
      * * @param host the host from which the Set-Cookie2 value was * received * @param port the port from which the Set-Cookie2 value was * received * @param path the path from which the Set-Cookie2 value was * received * @param secure true when the Set-Cookie2 value was * received over secure conection * @param header the Set-Cookie2 Header received from the server * @return an array of Cookies parsed from the Set-Cookie2 value * @throws MalformedCookieException if an exception occurs during parsing */ public Cookie[] parse( String host, int port, String path, boolean secure, final Header header) throws MalformedCookieException { LOG.trace("enter RFC2965.parse(" + "String, int, String, boolean, Header)"); if (header == null) { throw new IllegalArgumentException("Header may not be null."); } if (header.getName() == null) { throw new IllegalArgumentException("Header name may not be null."); } if (header.getName().equalsIgnoreCase(SET_COOKIE2_KEY)) { // parse cookie2 cookies return parse(host, port, path, secure, header.getValue()); } else if (header.getName().equalsIgnoreCase(RFC2109Spec.SET_COOKIE_KEY)) { // delegate parsing of old-style cookies to rfc2109Spec return this.rfc2109.parse(host, port, path, secure, header.getValue()); } else { throw new MalformedCookieException("Header name is not valid. " + "RFC 2965 supports \"set-cookie\" " + "and \"set-cookie2\" headers."); } } /** * @see #parse(String, int, String, boolean, org.apache.commons.httpclient.Header) */ public Cookie[] parse(String host, int port, String path, boolean secure, final String header) throws MalformedCookieException { LOG.trace("enter RFC2965Spec.parse(" + "String, int, String, boolean, String)"); // before we do anything, lets check validity of arguments if (host == null) { throw new IllegalArgumentException( "Host of origin may not be null"); } if (host.trim().equals("")) { throw new IllegalArgumentException( "Host of origin may not be blank"); } if (port < 0) { throw new IllegalArgumentException("Invalid port: " + port); } if (path == null) { throw new IllegalArgumentException( "Path of origin may not be null."); } if (header == null) { throw new IllegalArgumentException("Header may not be null."); } if (path.trim().equals("")) { path = PATH_DELIM; } host = getEffectiveHost(host); HeaderElement[] headerElements = HeaderElement.parseElements(header.toCharArray()); List cookies = new LinkedList(); for (int i = 0; i < headerElements.length; i++) { HeaderElement headerelement = headerElements[i]; Cookie2 cookie = null; try { cookie = new Cookie2(host, headerelement.getName(), headerelement.getValue(), path, null, false, new int[] {port}); } catch (IllegalArgumentException ex) { throw new MalformedCookieException(ex.getMessage()); } NameValuePair[] parameters = headerelement.getParameters(); // could be null. In case only a header element and no parameters. if (parameters != null) { // Eliminate duplicate attribues. The first occurence takes precedence Map attribmap = new HashMap(parameters.length); for (int j = parameters.length - 1; j >= 0; j--) { NameValuePair param = parameters[j]; attribmap.put(param.getName().toLowerCase(), param); } for (Iterator it = attribmap.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); parseAttribute((NameValuePair) entry.getValue(), cookie); } } cookies.add(cookie); // cycle through the parameters } return (Cookie[]) cookies.toArray(new Cookie[cookies.size()]); } /** * Parse RFC 2965 specific cookie attribute and update the corresponsing * {@link org.apache.commons.httpclient.Cookie} properties. * * @param attribute {@link org.apache.commons.httpclient.NameValuePair} cookie attribute from the * Set-Cookie2 header. * @param cookie {@link org.apache.commons.httpclient.Cookie} to be updated * @throws MalformedCookieException if an exception occurs during parsing */ public void parseAttribute( final NameValuePair attribute, final Cookie cookie) throws MalformedCookieException { if (attribute == null) { throw new IllegalArgumentException("Attribute may not be null."); } if (attribute.getName() == null) { throw new IllegalArgumentException("Attribute Name may not be null."); } if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null."); } final String paramName = attribute.getName().toLowerCase(); final String paramValue = attribute.getValue(); CookieAttributeHandler handler = findAttribHandler(paramName); if (handler == null) { // ignore unknown attribute-value pairs if (LOG.isDebugEnabled()) LOG.debug("Unrecognized cookie attribute: " + attribute.toString()); } else { handler.parse(cookie, paramValue); } } /** * Performs RFC 2965 compliant {@link org.apache.commons.httpclient.Cookie} validation * * @param host the host from which the {@link org.apache.commons.httpclient.Cookie} was received * @param port the port from which the {@link org.apache.commons.httpclient.Cookie} was received * @param path the path from which the {@link org.apache.commons.httpclient.Cookie} was received * @param secure true when the {@link org.apache.commons.httpclient.Cookie} was received using a * secure connection * @param cookie The cookie to validate * @throws MalformedCookieException if an exception occurs during * validation */ public void validate(final String host, int port, final String path, boolean secure, final Cookie cookie) throws MalformedCookieException { LOG.trace("enter RFC2965Spec.validate(String, int, String, " + "boolean, Cookie)"); if (cookie instanceof Cookie2) { if (cookie.getName().indexOf(' ') != -1) { throw new MalformedCookieException("Cookie name may not contain blanks"); } if (cookie.getName().startsWith("$")) { throw new MalformedCookieException("Cookie name may not start with $"); } CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure); for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) { CookieAttributeHandler handler = (CookieAttributeHandler) i.next(); handler.validate(cookie, origin); } } else { // old-style cookies are validated according to the old rules this.rfc2109.validate(host, port, path, secure, cookie); } } /** * Return true if the cookie should be submitted with a request * with given attributes, false otherwise. * @param host the host to which the request is being submitted * @param port the port to which the request is being submitted (ignored) * @param path the path to which the request is being submitted * @param secure true if the request is using a secure connection * @return true if the cookie matches the criterium */ public boolean match(String host, int port, String path, boolean secure, final Cookie cookie) { LOG.trace("enter RFC2965.match(" + "String, int, String, boolean, Cookie"); if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (cookie instanceof Cookie2) { // check if cookie has expired if (cookie.isPersistent() && cookie.isExpired()) { return false; } CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure); for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) { CookieAttributeHandler handler = (CookieAttributeHandler) i.next(); if (!handler.match(cookie, origin)) { return false; } } return true; } else { // old-style cookies are matched according to the old rules return this.rfc2109.match(host, port, path, secure, cookie); } } private void doFormatCookie2(final Cookie2 cookie, final StringBuffer buffer) { String name = cookie.getName(); String value = cookie.getValue(); if (value == null) { value = ""; } this.formatter.format(buffer, new NameValuePair(name, value)); // format domain attribute if (cookie.getDomain() != null && cookie.isDomainAttributeSpecified()) { buffer.append("; "); this.formatter.format(buffer, new NameValuePair("$Domain", cookie.getDomain())); } // format path attribute if ((cookie.getPath() != null) && (cookie.isPathAttributeSpecified())) { buffer.append("; "); this.formatter.format(buffer, new NameValuePair("$Path", cookie.getPath())); } // format port attribute if (cookie.isPortAttributeSpecified()) { String portValue = ""; if (!cookie.isPortAttributeBlank()) { portValue = createPortAttribute(cookie.getPorts()); } buffer.append("; "); this.formatter.format(buffer, new NameValuePair("$Port", portValue)); } } /** * Return a string suitable for sending in a "Cookie" header as * defined in RFC 2965 * @param cookie a {@link org.apache.commons.httpclient.Cookie} to be formatted as string * @return a string suitable for sending in a "Cookie" header. */ public String formatCookie(final Cookie cookie) { LOG.trace("enter RFC2965Spec.formatCookie(Cookie)"); if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; int version = cookie2.getVersion(); final StringBuffer buffer = new StringBuffer(); this.formatter.format(buffer, new NameValuePair("$Version", Integer.toString(version))); buffer.append("; "); doFormatCookie2(cookie2, buffer); return buffer.toString(); } else { // old-style cookies are formatted according to the old rules return this.rfc2109.formatCookie(cookie); } } /** * Create a RFC 2965 compliant "Cookie" header value containing all * {@link org.apache.commons.httpclient.Cookie}s suitable for * sending in a "Cookie" header * @param cookies an array of {@link org.apache.commons.httpclient.Cookie}s to be formatted * @return a string suitable for sending in a Cookie header. */ public String formatCookies(final Cookie[] cookies) { LOG.trace("enter RFC2965Spec.formatCookieHeader(Cookie[])"); if (cookies == null) { throw new IllegalArgumentException("Cookies may not be null"); } // check if cookies array contains a set-cookie (old style) cookie boolean hasOldStyleCookie = false; int version = -1; for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (!(cookie instanceof Cookie2)) { hasOldStyleCookie = true; break; } if (cookie.getVersion() > version) { version = cookie.getVersion(); } } if (version < 0) { version = 0; } if (hasOldStyleCookie || version < 1) { // delegate old-style cookie formatting to rfc2109Spec return this.rfc2109.formatCookies(cookies); } // Arrange cookies by path Arrays.sort(cookies, PATH_COMPOARATOR); final StringBuffer buffer = new StringBuffer(); // format cookie version this.formatter.format(buffer, new NameValuePair("$Version", Integer.toString(version))); for (int i = 0; i < cookies.length; i++) { buffer.append("; "); Cookie2 cookie = (Cookie2) cookies[i]; // format cookie attributes doFormatCookie2(cookie, buffer); } return buffer.toString(); } /** * Retrieves valid Port attribute value for the given ports array. * e.g. "8000,8001,8002" * * @param ports int array of ports */ private String createPortAttribute(int[] ports) { StringBuffer portValue = new StringBuffer(); for (int i = 0, len = ports.length; i < len; i++) { if (i > 0) { portValue.append(","); } portValue.append(ports[i]); } return portValue.toString(); } /** * Parses the given Port attribute value (e.g. "8000,8001,8002") * into an array of ports. * * @param portValue port attribute value * @return parsed array of ports * @throws MalformedCookieException if there is a problem in * parsing due to invalid portValue. */ private int[] parsePortAttribute(final String portValue) throws MalformedCookieException { StringTokenizer st = new StringTokenizer(portValue, ","); int[] ports = new int[st.countTokens()]; try { int i = 0; while(st.hasMoreTokens()) { ports[i] = Integer.parseInt(st.nextToken().trim()); if (ports[i] < 0) { throw new MalformedCookieException ("Invalid Port attribute."); } ++i; } } catch (NumberFormatException e) { throw new MalformedCookieException ("Invalid Port " + "attribute: " + e.getMessage()); } return ports; } /** * Gets 'effective host name' as defined in RFC 2965. *

      * If a host name contains no dots, the effective host name is * that name with the string .local appended to it. Otherwise * the effective host name is the same as the host name. Note * that all effective host names contain at least one dot. * * @param host host name where cookie is received from or being sent to. * @return */ private static String getEffectiveHost(final String host) { String effectiveHost = host.toLowerCase(); if (host.indexOf('.') < 0) { effectiveHost += ".local"; } return effectiveHost; } /** * Performs domain-match as defined by the RFC2965. *

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

        *
          their host name strings string-compare equal; or
        *
          A is a HDN string and has the form NB, where N is a non-empty * name string, B has the form .B', and B' is a HDN string. (So, * x.y.com domain-matches .Y.com but not Y.com.)
        *
      * * @param host host name where cookie is received from or being sent to. * @param domain The cookie domain attribute. * @return true if the specified host matches the given domain. */ public boolean domainMatch(String host, String domain) { boolean match = host.equals(domain) || (domain.startsWith(".") && host.endsWith(domain)); return match; } /** * Returns true if the given port exists in the given * ports list. * * @param port port of host where cookie was received from or being sent to. * @param ports port list * @return true returns true if the given port exists in * the given ports list; false otherwise. */ private boolean portMatch(int port, int[] ports) { boolean portInList = false; for (int i = 0, len = ports.length; i < len; i++) { if (port == ports[i]) { portInList = true; break; } } return portInList; } /** * "Path" attribute handler for RFC 2965 cookie spec. */ private class Cookie2PathAttributeHandler implements CookieAttributeHandler { /** * Parse cookie path attribute. */ public void parse(final Cookie cookie, final String path) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (path == null) { throw new MalformedCookieException( "Missing value for path attribute"); } if (path.trim().equals("")) { throw new MalformedCookieException( "Blank value for path attribute"); } cookie.setPath(path); cookie.setPathAttributeSpecified(true); } /** * Validate cookie path attribute. The value for the Path attribute must be a * prefix of the request-URI (case-sensitive matching). */ public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } String path = origin.getPath(); if (path == null) { throw new IllegalArgumentException( "Path of origin host may not be null."); } if (cookie.getPath() == null) { throw new MalformedCookieException("Invalid cookie state: " + "path attribute is null."); } if (path.trim().equals("")) { path = PATH_DELIM; } if (!pathMatch(path, cookie.getPath())) { throw new MalformedCookieException( "Illegal path attribute \"" + cookie.getPath() + "\". Path of origin: \"" + path + "\""); } } /** * Match cookie path attribute. The value for the Path attribute must be a * prefix of the request-URI (case-sensitive matching). */ public boolean match(final Cookie cookie, final CookieOrigin origin) { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } String path = origin.getPath(); if (cookie.getPath() == null) { LOG.warn("Invalid cookie state: path attribute is null."); return false; } if (path.trim().equals("")) { path = PATH_DELIM; } if (!pathMatch(path, cookie.getPath())) { return false; } return true; } } /** * "Domain" cookie attribute handler for RFC 2965 cookie spec. */ private class Cookie2DomainAttributeHandler implements CookieAttributeHandler { /** * Parse cookie domain attribute. */ public void parse(final Cookie cookie, String domain) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (domain == null) { throw new MalformedCookieException( "Missing value for domain attribute"); } if (domain.trim().equals("")) { throw new MalformedCookieException( "Blank value for domain attribute"); } domain = domain.toLowerCase(); if (!domain.startsWith(".")) { // Per RFC 2965 section 3.2.2 // "... If an explicitly specified value does not start with // a dot, the user agent supplies a leading dot ..." // That effectively implies that the domain attribute // MAY NOT be an IP address of a host name domain = "." + domain; } cookie.setDomain(domain); cookie.setDomainAttributeSpecified(true); } /** * Validate cookie domain attribute. */ public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } String host = origin.getHost().toLowerCase(); if (cookie.getDomain() == null) { throw new MalformedCookieException("Invalid cookie state: " + "domain not specified"); } String cookieDomain = cookie.getDomain().toLowerCase(); if (cookie.isDomainAttributeSpecified()) { // Domain attribute must start with a dot if (!cookieDomain.startsWith(".")) { throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot"); } // Domain attribute must contain atleast one embedded dot, // or the value must be equal to .local. int dotIndex = cookieDomain.indexOf('.', 1); if (((dotIndex < 0) || (dotIndex == cookieDomain.length() - 1)) && (!cookieDomain.equals(".local"))) { throw new MalformedCookieException( "Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2965: the value contains no embedded dots " + "and the value is not .local"); } // The effective host name must domain-match domain attribute. if (!domainMatch(host, cookieDomain)) { throw new MalformedCookieException( "Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2965: effective host name does not " + "domain-match domain attribute."); } // effective host name minus domain must not contain any dots String effectiveHostWithoutDomain = host.substring( 0, host.length() - cookieDomain.length()); if (effectiveHostWithoutDomain.indexOf('.') != -1) { throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2965: " + "effective host minus domain may not contain any dots"); } } else { // Domain was not specified in header. In this case, domain must // string match request host (case-insensitive). if (!cookie.getDomain().equals(host)) { throw new MalformedCookieException("Illegal domain attribute: \"" + cookie.getDomain() + "\"." + "Domain of origin: \"" + host + "\""); } } } /** * Match cookie domain attribute. */ public boolean match(final Cookie cookie, final CookieOrigin origin) { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } String host = origin.getHost().toLowerCase(); String cookieDomain = cookie.getDomain(); // The effective host name MUST domain-match the Domain // attribute of the cookie. if (!domainMatch(host, cookieDomain)) { return false; } // effective host name minus domain must not contain any dots String effectiveHostWithoutDomain = host.substring( 0, host.length() - cookieDomain.length()); if (effectiveHostWithoutDomain.indexOf('.') != -1) { return false; } return true; } } /** * "Port" cookie attribute handler for RFC 2965 cookie spec. */ private class Cookie2PortAttributeHandler implements CookieAttributeHandler { /** * Parse cookie port attribute. */ public void parse(final Cookie cookie, final String portValue) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; if ((portValue == null) || (portValue.trim().equals(""))) { // If the Port attribute is present but has no value, the // cookie can only be sent to the request-port. // Since the default port list contains only request-port, we don't // need to do anything here. cookie2.setPortAttributeBlank(true); } else { int[] ports = parsePortAttribute(portValue); cookie2.setPorts(ports); } cookie2.setPortAttributeSpecified(true); } } /** * Validate cookie port attribute. If the Port attribute was specified * in header, the request port must be in cookie's port list. */ public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; int port = origin.getPort(); if (cookie2.isPortAttributeSpecified()) { if (!portMatch(port, cookie2.getPorts())) { throw new MalformedCookieException( "Port attribute violates RFC 2965: " + "Request port not found in cookie's port list."); } } } } /** * Match cookie port attribute. If the Port attribute is not specified * in header, the cookie can be sent to any port. Otherwise, the request port * must be in the cookie's port list. */ public boolean match(final Cookie cookie, final CookieOrigin origin) { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; int port = origin.getPort(); if (cookie2.isPortAttributeSpecified()) { if (cookie2.getPorts() == null) { LOG.warn("Invalid cookie state: port not specified"); return false; } if (!portMatch(port, cookie2.getPorts())) { return false; } } return true; } else { return false; } } } /** * "Max-age" cookie attribute handler for RFC 2965 cookie spec. */ private class Cookie2MaxageAttributeHandler implements CookieAttributeHandler { /** * Parse cookie max-age attribute. */ public void parse(final Cookie cookie, final String value) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (value == null) { throw new MalformedCookieException( "Missing value for max-age attribute"); } int age = -1; try { age = Integer.parseInt(value); } catch (NumberFormatException e) { age = -1; } if (age < 0) { throw new MalformedCookieException ("Invalid max-age attribute."); } cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L)); } /** * validate cookie max-age attribute. */ public void validate(final Cookie cookie, final CookieOrigin origin) { } /** * @see CookieAttributeHandler#match(org.apache.commons.httpclient.Cookie, String) */ public boolean match(final Cookie cookie, final CookieOrigin origin) { return true; } } /** * "Secure" cookie attribute handler for RFC 2965 cookie spec. */ private class CookieSecureAttributeHandler implements CookieAttributeHandler { public void parse(final Cookie cookie, final String secure) throws MalformedCookieException { cookie.setSecure(true); } public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { } public boolean match(final Cookie cookie, final CookieOrigin origin) { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } return cookie.getSecure() == origin.isSecure(); } } /** * "Commant" cookie attribute handler for RFC 2965 cookie spec. */ private class CookieCommentAttributeHandler implements CookieAttributeHandler { public void parse(final Cookie cookie, final String comment) throws MalformedCookieException { cookie.setComment(comment); } public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { } public boolean match(final Cookie cookie, final CookieOrigin origin) { return true; } } /** * "CommantURL" cookie attribute handler for RFC 2965 cookie spec. */ private class CookieCommentUrlAttributeHandler implements CookieAttributeHandler { public void parse(final Cookie cookie, final String commenturl) throws MalformedCookieException { if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; cookie2.setCommentURL(commenturl); } } public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { } public boolean match(final Cookie cookie, final CookieOrigin origin) { return true; } } /** * "Discard" cookie attribute handler for RFC 2965 cookie spec. */ private class CookieDiscardAttributeHandler implements CookieAttributeHandler { public void parse(final Cookie cookie, final String commenturl) throws MalformedCookieException { if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; cookie2.setDiscard(true); } } public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { } public boolean match(final Cookie cookie, final CookieOrigin origin) { return true; } } /** * "Version" cookie attribute handler for RFC 2965 cookie spec. */ private class Cookie2VersionAttributeHandler implements CookieAttributeHandler { /** * Parse cookie version attribute. */ public void parse(final Cookie cookie, final String value) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; if (value == null) { throw new MalformedCookieException( "Missing value for version attribute"); } int version = -1; try { version = Integer.parseInt(value); } catch (NumberFormatException e) { version = -1; } if (version < 0) { throw new MalformedCookieException("Invalid cookie version."); } cookie2.setVersion(version); cookie2.setVersionAttributeSpecified(true); } } /** * validate cookie version attribute. Version attribute is REQUIRED. */ public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; if (!cookie2.isVersionAttributeSpecified()) { throw new MalformedCookieException( "Violates RFC 2965. Version attribute is required."); } } } public boolean match(final Cookie cookie, final CookieOrigin origin) { return true; } } public int getVersion() { return 1; } public Header getVersionHeader() { ParameterFormatter formatter = new ParameterFormatter(); StringBuffer buffer = new StringBuffer(); formatter.format(buffer, new NameValuePair("$Version", Integer.toString(getVersion()))); return new Header("Cookie2", buffer.toString(), true); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/cookie/package.html100644 0 0 477 10661532626 25435 0ustar 0 0 Package Documentation for org.apache.commons.httpclient.cookie Provides cookie handling in conjunction with {@link org.apache.commons.httpclient.Cookie}. @since 2.0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/ByteArrayRequestEntity.java100644 0 0 6471 10661532626 30701 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/ByteArrayRequestEntity.java,v 1.3 2004/05/13 02:26:08 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.methods; import java.io.IOException; import java.io.OutputStream; /** * A RequestEntity that contains an array of bytes. * * @since 3.0 */ public class ByteArrayRequestEntity implements RequestEntity { /** The content */ private byte[] content; /** The content type */ private String contentType; /** * Creates a new entity with the given content. * @param content The content to set. */ public ByteArrayRequestEntity(byte[] content) { this(content, null); } /** * Creates a new entity with the given content and content type. * @param content The content to set. * @param contentType The content type to set or null. */ public ByteArrayRequestEntity(byte[] content, String contentType) { super(); if (content == null) { throw new IllegalArgumentException("The content cannot be null"); } this.content = content; this.contentType = contentType; } /** * @return true */ public boolean isRepeatable() { return true; } /* (non-Javadoc) * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType() */ public String getContentType() { return contentType; } /* (non-Javadoc) * @see org.apache.commons.httpclient.RequestEntity#writeRequest(java.io.OutputStream) */ public void writeRequest(OutputStream out) throws IOException { out.write(content); } /** * @return The length of the content. */ public long getContentLength() { return content.length; } /** * @return Returns the content. */ public byte[] getContent() { return content; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/DeleteMethod.java100644 0 0 5574 10661532626 26577 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/DeleteMethod.java,v 1.14 2004/04/18 23:51:37 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; import org.apache.commons.httpclient.HttpMethodBase; /** * Implements the HTTP DELETE method. *

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

      * The DELETE method requests that the origin server delete the resource * identified by the Request-URI. This method MAY be overridden by human * intervention (or other means) on the origin server. *
      *

      * * @author Remy Maucherat * @author B.C. Holmes * @author Jeff Dever * * @version $Revision: 480424 $ * @since 1.0 */ public class DeleteMethod extends HttpMethodBase { // ----------------------------------------------------------- Constructors /** * No-arg constructor. * * @since 1.0 */ public DeleteMethod() { } /** * Constructor specifying a URI. * * @param uri either an absolute or relative URI * * @since 1.0 */ public DeleteMethod(String uri) { super(uri); } // ----------------------------------------------------- HttpMethod Methods /** * Returns "DELETE". * @return "DELETE" * * @since 2.0 */ public String getName() { return "DELETE"; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/EntityEnclosingMethod.java100644 0 0 46722 10661532626 30533 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/EntityEnclosingMethod.java,v 1.39 2004/07/03 14:27:03 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import org.apache.commons.httpclient.ChunkedOutputStream; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpConnection; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.ProtocolException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This abstract class serves as a foundation for all HTTP methods * that can enclose an entity within requests * * @author Oleg Kalnichevski * @author Jeff Dever * * @since 2.0beta1 * @version $Revision: 480424 $ */ public abstract class EntityEnclosingMethod extends ExpectContinueMethod { // ----------------------------------------- Static variables/initializers /** * The content length will be calculated automatically. This implies * buffering of the content. * @deprecated Use {@link InputStreamRequestEntity#CONTENT_LENGTH_AUTO}. */ public static final long CONTENT_LENGTH_AUTO = InputStreamRequestEntity.CONTENT_LENGTH_AUTO; /** * The request will use chunked transfer encoding. Content length is not * calculated and the content is not buffered.
      * @deprecated Use {@link #setContentChunked(boolean)}. */ public static final long CONTENT_LENGTH_CHUNKED = -1; /** LOG object for this class. */ private static final Log LOG = LogFactory.getLog(EntityEnclosingMethod.class); /** The unbuffered request body, if any. */ private InputStream requestStream = null; /** The request body as string, if any. */ private String requestString = null; private RequestEntity requestEntity; /** Counts how often the request was sent to the server. */ private int repeatCount = 0; /** The content length of the requestBodyStream or one of * CONTENT_LENGTH_AUTO and CONTENT_LENGTH_CHUNKED. * * @deprecated */ private long requestContentLength = InputStreamRequestEntity.CONTENT_LENGTH_AUTO; private boolean chunked = false; // ----------------------------------------------------------- Constructors /** * No-arg constructor. * * @since 2.0 */ public EntityEnclosingMethod() { super(); setFollowRedirects(false); } /** * Constructor specifying a URI. * * @param uri either an absolute or relative URI * * @since 2.0 */ public EntityEnclosingMethod(String uri) { super(uri); setFollowRedirects(false); } /** * Returns true if there is a request body to be sent. * *

      This method must be overridden by sub-classes that implement * alternative request content input methods *

      * * @return boolean * * @since 2.0beta1 */ protected boolean hasRequestContent() { LOG.trace("enter EntityEnclosingMethod.hasRequestContent()"); return (this.requestEntity != null) || (this.requestStream != null) || (this.requestString != null); } /** * Clears the request body. * *

      This method must be overridden by sub-classes that implement * alternative request content input methods.

      * * @since 2.0beta1 */ protected void clearRequestBody() { LOG.trace("enter EntityEnclosingMethod.clearRequestBody()"); this.requestStream = null; this.requestString = null; this.requestEntity = null; } /** * Generates the request body. * *

      This method must be overridden by sub-classes that implement * alternative request content input methods.

      * * @return request body as an array of bytes. If the request content * has not been set, returns null. * * @since 2.0beta1 */ protected byte[] generateRequestBody() { LOG.trace("enter EntityEnclosingMethod.renerateRequestBody()"); return null; } protected RequestEntity generateRequestEntity() { byte[] requestBody = generateRequestBody(); if (requestBody != null) { // use the request body, if it exists. // this is just for backwards compatability this.requestEntity = new ByteArrayRequestEntity(requestBody); } else if (this.requestStream != null) { this.requestEntity = new InputStreamRequestEntity( requestStream, requestContentLength); this.requestStream = null; } else if (this.requestString != null) { String charset = getRequestCharSet(); try { this.requestEntity = new StringRequestEntity( requestString, null, charset); } catch (UnsupportedEncodingException e) { if (LOG.isWarnEnabled()) { LOG.warn(charset + " not supported"); } try { this.requestEntity = new StringRequestEntity( requestString, null, null); } catch (UnsupportedEncodingException ignore) { } } } return this.requestEntity; } /** * Entity enclosing requests cannot be redirected without user intervention * according to RFC 2616. * * @return false. * * @since 2.0 */ public boolean getFollowRedirects() { return false; } /** * Entity enclosing requests cannot be redirected without user intervention * according to RFC 2616. * * @param followRedirects must always be false */ public void setFollowRedirects(boolean followRedirects) { if (followRedirects == true) { throw new IllegalArgumentException("Entity enclosing requests cannot be redirected without user intervention"); } super.setFollowRedirects(false); } /** * Sets length information about the request body. * *

      * Note: If you specify a content length the request is unbuffered. This * prevents redirection and automatic retry if a request fails the first * time. This means that the HttpClient can not perform authorization * automatically but will throw an Exception. You will have to set the * necessary 'Authorization' or 'Proxy-Authorization' headers manually. *

      * * @param length size in bytes or any of CONTENT_LENGTH_AUTO, * CONTENT_LENGTH_CHUNKED. If number of bytes or CONTENT_LENGTH_CHUNKED * is specified the content will not be buffered internally and the * Content-Length header of the request will be used. In this case * the user is responsible to supply the correct content length. * If CONTENT_LENGTH_AUTO is specified the request will be buffered * before it is sent over the network. * * @deprecated Use {@link #setContentChunked(boolean)} or * {@link #setRequestEntity(RequestEntity)} */ public void setRequestContentLength(int length) { LOG.trace("enter EntityEnclosingMethod.setRequestContentLength(int)"); this.requestContentLength = length; } /** * Returns the request's charset. The charset is parsed from the request entity's * content type, unless the content type header has been set manually. * * @see RequestEntity#getContentType() * * @since 3.0 */ public String getRequestCharSet() { if (getRequestHeader("Content-Type") == null) { // check the content type from request entity // We can't call getRequestEntity() since it will probably call // this method. if (this.requestEntity != null) { return getContentCharSet( new Header("Content-Type", requestEntity.getContentType())); } else { return super.getRequestCharSet(); } } else { return super.getRequestCharSet(); } } /** * Sets length information about the request body. * *

      * Note: If you specify a content length the request is unbuffered. This * prevents redirection and automatic retry if a request fails the first * time. This means that the HttpClient can not perform authorization * automatically but will throw an Exception. You will have to set the * necessary 'Authorization' or 'Proxy-Authorization' headers manually. *

      * * @param length size in bytes or any of CONTENT_LENGTH_AUTO, * CONTENT_LENGTH_CHUNKED. If number of bytes or CONTENT_LENGTH_CHUNKED * is specified the content will not be buffered internally and the * Content-Length header of the request will be used. In this case * the user is responsible to supply the correct content length. * If CONTENT_LENGTH_AUTO is specified the request will be buffered * before it is sent over the network. * * @deprecated Use {@link #setContentChunked(boolean)} or * {@link #setRequestEntity(RequestEntity)} */ public void setRequestContentLength(long length) { LOG.trace("enter EntityEnclosingMethod.setRequestContentLength(int)"); this.requestContentLength = length; } /** * Sets whether or not the content should be chunked. * * @param chunked true if the content should be chunked * * @since 3.0 */ public void setContentChunked(boolean chunked) { this.chunked = chunked; } /** * Returns the length of the request body. * * @return number of bytes in the request body */ protected long getRequestContentLength() { LOG.trace("enter EntityEnclosingMethod.getRequestContentLength()"); if (!hasRequestContent()) { return 0; } if (this.chunked) { return -1; } if (this.requestEntity == null) { this.requestEntity = generateRequestEntity(); } return (this.requestEntity == null) ? 0 : this.requestEntity.getContentLength(); } /** * Populates the request headers map to with additional * {@link org.apache.commons.httpclient.Header headers} to be submitted to * the given {@link HttpConnection}. * *

      * This implementation adds tt>Content-Length or Transfer-Encoding * headers. *

      * *

      * Subclasses may want to override this method to to add additional * headers, and may choose to invoke this implementation (via * super) to add the "standard" headers. *

      * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @see #writeRequestHeaders * * @since 3.0 */ protected void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter EntityEnclosingMethod.addRequestHeaders(HttpState, " + "HttpConnection)"); super.addRequestHeaders(state, conn); addContentLengthRequestHeader(state, conn); // only use the content type of the request entity if it has not already been // set manually if (getRequestHeader("Content-Type") == null) { RequestEntity requestEntity = getRequestEntity(); if (requestEntity != null && requestEntity.getContentType() != null) { setRequestHeader("Content-Type", requestEntity.getContentType()); } } } /** * Generates Content-Length or Transfer-Encoding: Chunked * request header, as long as no Content-Length request header * already exists. * * @param state current state of http requests * @param conn the connection to use for I/O * * @throws IOException when errors occur reading or writing to/from the * connection * @throws HttpException when a recoverable error occurs */ protected void addContentLengthRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter EntityEnclosingMethod.addContentLengthRequestHeader(" + "HttpState, HttpConnection)"); if ((getRequestHeader("content-length") == null) && (getRequestHeader("Transfer-Encoding") == null)) { long len = getRequestContentLength(); if (len < 0) { if (getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1)) { addRequestHeader("Transfer-Encoding", "chunked"); } else { throw new ProtocolException(getEffectiveVersion() + " does not support chunk encoding"); } } else { addRequestHeader("Content-Length", String.valueOf(len)); } } } /** * Sets the request body to be the specified inputstream. * * @param body Request body content as {@link java.io.InputStream} * * @deprecated use {@link #setRequestEntity(RequestEntity)} */ public void setRequestBody(InputStream body) { LOG.trace("enter EntityEnclosingMethod.setRequestBody(InputStream)"); clearRequestBody(); this.requestStream = body; } /** * Sets the request body to be the specified string. * The string will be submitted, using the encoding * specified in the Content-Type request header.
      * Example: setRequestHeader("Content-type", "text/xml; charset=UTF-8");
      * Would use the UTF-8 encoding. * If no charset is specified, the * {@link org.apache.commons.httpclient.HttpConstants#DEFAULT_CONTENT_CHARSET default} * content encoding is used (ISO-8859-1). * * @param body Request body content as a string * * @deprecated use {@link #setRequestEntity(RequestEntity)} */ public void setRequestBody(String body) { LOG.trace("enter EntityEnclosingMethod.setRequestBody(String)"); clearRequestBody(); this.requestString = body; } /** * Writes the request body to the given {@link HttpConnection connection}. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @return true * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected boolean writeRequestBody(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace( "enter EntityEnclosingMethod.writeRequestBody(HttpState, HttpConnection)"); if (!hasRequestContent()) { LOG.debug("Request body has not been specified"); return true; } if (this.requestEntity == null) { this.requestEntity = generateRequestEntity(); } if (requestEntity == null) { LOG.debug("Request body is empty"); return true; } long contentLength = getRequestContentLength(); if ((this.repeatCount > 0) && !requestEntity.isRepeatable()) { throw new ProtocolException( "Unbuffered entity enclosing request can not be repeated."); } this.repeatCount++; OutputStream outstream = conn.getRequestOutputStream(); if (contentLength < 0) { outstream = new ChunkedOutputStream(outstream); } requestEntity.writeRequest(outstream); // This is hardly the most elegant solution to closing chunked stream if (outstream instanceof ChunkedOutputStream) { ((ChunkedOutputStream) outstream).finish(); } outstream.flush(); LOG.debug("Request body sent"); return true; } /** * Recycles the HTTP method so that it can be used again. * Note that all of the instance variables will be reset * once this method has been called. This method will also * release the connection being used by this HTTP method. * * @see #releaseConnection() * * @deprecated no longer supported and will be removed in the future * version of HttpClient */ public void recycle() { LOG.trace("enter EntityEnclosingMethod.recycle()"); clearRequestBody(); this.requestContentLength = InputStreamRequestEntity.CONTENT_LENGTH_AUTO; this.repeatCount = 0; this.chunked = false; super.recycle(); } /** * @return Returns the requestEntity. * * @since 3.0 */ public RequestEntity getRequestEntity() { return generateRequestEntity(); } /** * @param requestEntity The requestEntity to set. * * @since 3.0 */ public void setRequestEntity(RequestEntity requestEntity) { clearRequestBody(); this.requestEntity = requestEntity; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/ExpectContinueMethod.java100644 0 0 16436 10661532626 30351 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/ExpectContinueMethod.java,v 1.13 2004/05/08 10:12:08 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; import java.io.IOException; import org.apache.commons.httpclient.HttpConnection; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** *

      * This abstract class serves as a foundation for all HTTP methods * that support 'Expect: 100-continue' handshake. *

      * *

      * The purpose of the 100 (Continue) status (refer to section 10.1.1 * of the RFC 2616 for more details) 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. In some cases, * it might either be inappropriate or highly inefficient for the * client to send the body if the server will reject the message * without looking at the body. *

      * *

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

      * * @author Oleg Kalnichevski * * @since 2.0beta1 */ public abstract class ExpectContinueMethod extends HttpMethodBase { /** LOG object for this class. */ private static final Log LOG = LogFactory.getLog(ExpectContinueMethod.class); /** * No-arg constructor. * * @since 2.0 */ public ExpectContinueMethod() { super(); } /** * Constructor specifying a URI. * * @param uri either an absolute or relative URI * * @since 2.0 */ public ExpectContinueMethod(String uri) { super(uri); } /** *

      * Returns true if the 'Expect: 100-Continue' handshake * is activated. The purpose of the 'Expect: 100-Continue' * handshake 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. *

      * * @return true if 'Expect: 100-Continue' handshake is to * be used, false otherwise. * * @since 2.0beta1 * * @deprecated Use {@link HttpMethodParams} * * @see #getParams() * @see HttpMethodParams * @see HttpMethodParams#USE_EXPECT_CONTINUE */ public boolean getUseExpectHeader() { return getParams().getBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); } /** *

      * Activates 'Expect: 100-Continue' handshake. The purpose of * the 'Expect: 100-Continue' handshake 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 * noticable peformance 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. *

      * * @param value boolean value * * @since 2.0beta1 * * @deprecated Use {@link HttpMethodParams} * * @see #getParams() * @see HttpMethodParams * @see HttpMethodParams#USE_EXPECT_CONTINUE */ public void setUseExpectHeader(boolean value) { getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, value); } /** * Returns true if there is a request body to be sent. * 'Expect: 100-continue' handshake may not be used if request * body is not present * * @return boolean * * @since 2.0beta1 */ protected abstract boolean hasRequestContent(); /** * Sets the Expect header if it has not already been set, * in addition to the "standard" set of headers. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter ExpectContinueMethod.addRequestHeaders(HttpState, HttpConnection)"); super.addRequestHeaders(state, conn); // If the request is being retried, the header may already be present boolean headerPresent = (getRequestHeader("Expect") != null); // See if the expect header should be sent // = HTTP/1.1 or higher // = request body present if (getParams().isParameterTrue(HttpMethodParams.USE_EXPECT_CONTINUE) && getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1) && hasRequestContent()) { if (!headerPresent) { setRequestHeader("Expect", "100-continue"); } } else { if (headerPresent) { removeRequestHeader("Expect"); } } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/FileRequestEntity.java100644 0 0 5317 10661532626 27654 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/methods/FileRequestEntity.java $ * $Revision: 486665 $ * $Date: 2006-12-13 15:19:07 +0100 (Wed, 13 Dec 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.httpclient.methods.RequestEntity; /** * A RequestEntity that represents a File. * * @since 3.1 */ public class FileRequestEntity implements RequestEntity { final File file; final String contentType; public FileRequestEntity(final File file, final String contentType) { super(); if (file == null) { throw new IllegalArgumentException("File may not be null"); } this.file = file; this.contentType = contentType; } public long getContentLength() { return this.file.length(); } public String getContentType() { return this.contentType; } public boolean isRepeatable() { return true; } public void writeRequest(final OutputStream out) throws IOException { byte[] tmp = new byte[4096]; int i = 0; InputStream instream = new FileInputStream(this.file); try { while ((i = instream.read(tmp)) >= 0) { out.write(tmp, 0, i); } } finally { instream.close(); } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/GetMethod.java100644 0 0 10404 10661532626 26120 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/GetMethod.java,v 1.29 2004/06/13 20:22:19 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the HTTP GET method. *

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

      * The GET method means retrieve whatever information (in the form of an * entity) is identified by the Request-URI. If the Request-URI refers * to a data-producing process, it is the produced data which shall be * returned as the entity in the response and not the source text of the * process, unless that text happens to be the output of the process. *
      *

      *

      * GetMethods will follow redirect requests from the http server by default. * This behavour can be disabled by calling setFollowRedirects(false).

      * * @author Remy Maucherat * @author Sung-Gu Park * @author Sean C. Sullivan * @author Mike Bowler * @author Jeff Dever * * @version $Revision: 480424 $ * @since 1.0 */ public class GetMethod extends HttpMethodBase { // -------------------------------------------------------------- Constants /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(GetMethod.class); // ----------------------------------------------------------- Constructors /** * No-arg constructor. * * @since 1.0 */ public GetMethod() { setFollowRedirects(true); } /** * Constructor specifying a URI. * * @param uri either an absolute or relative URI * * @since 1.0 */ public GetMethod(String uri) { super(uri); LOG.trace("enter GetMethod(String)"); setFollowRedirects(true); } // --------------------------------------------------------- Public Methods /** * Returns "GET". * * @return "GET" * * @since 2.0 */ public String getName() { return "GET"; } // ------------------------------------------------------------- Properties /** * Recycles the HTTP method so that it can be used again. * Note that all of the instance variables will be reset * once this method has been called. This method will also * release the connection being used by this HTTP method. * * @see #releaseConnection() * * @since 1.0 * * @deprecated no longer supported and will be removed in the future * version of HttpClient */ public void recycle() { LOG.trace("enter GetMethod.recycle()"); super.recycle(); setFollowRedirects(true); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/HeadMethod.java100644 0 0 17250 10661532626 26250 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/HeadMethod.java,v 1.29 2004/06/13 20:22:19 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; import java.io.IOException; import org.apache.commons.httpclient.HttpConnection; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.ProtocolException; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the HTTP HEAD method. *

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

      * The HEAD method is identical to GET except that the server MUST NOT * return a message-body in the response. The metainformation contained * in the HTTP headers in response to a HEAD request SHOULD be identical * to the information sent in response to a GET request. This method can * be used for obtaining metainformation about the entity implied by the * request without transferring the entity-body itself. This method is * often used for testing hypertext links for validity, accessibility, * and recent modification. *
      *

      * * @author Remy Maucherat * @author Mike Bowler * @author Jeff Dever * @author oleg Kalnichevski * * @version $Revision: 480424 $ * @since 1.0 */ public class HeadMethod extends HttpMethodBase { //~ Static variables/initializers /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HeadMethod.class); //~ Constructors /** * No-arg constructor. * * @since 1.0 */ public HeadMethod() { setFollowRedirects(true); } /** * Constructor specifying a URI. * * @param uri either an absolute or relative URI * * @since 1.0 */ public HeadMethod(String uri) { super(uri); setFollowRedirects(true); } //~ Methods /** * Returns "HEAD". * * @return "HEAD" * * @since 2.0 */ public String getName() { return "HEAD"; } /** * Recycles the HTTP method so that it can be used again. * Note that all of the instance variables will be reset * once this method has been called. This method will also * release the connection being used by this HTTP method. * * @see #releaseConnection() * * @since 1.0 * * @deprecated no longer supported and will be removed in the future * version of HttpClient */ public void recycle() { super.recycle(); setFollowRedirects(true); } /** * Overrides {@link HttpMethodBase} method to not read a response * body, despite the presence of a Content-Length or * Transfer-Encoding header. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @see #readResponse * @see #processResponseBody * * @since 2.0 */ protected void readResponseBody(HttpState state, HttpConnection conn) throws HttpException, IOException { LOG.trace( "enter HeadMethod.readResponseBody(HttpState, HttpConnection)"); int bodyCheckTimeout = getParams().getIntParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, -1); if (bodyCheckTimeout < 0) { responseBodyConsumed(); } else { if (LOG.isDebugEnabled()) { LOG.debug("Check for non-compliant response body. Timeout in " + bodyCheckTimeout + " ms"); } boolean responseAvailable = false; try { responseAvailable = conn.isResponseAvailable(bodyCheckTimeout); } catch (IOException e) { LOG.debug("An IOException occurred while testing if a response was available," + " we will assume one is not.", e); responseAvailable = false; } if (responseAvailable) { if (getParams().isParameterTrue(HttpMethodParams.REJECT_HEAD_BODY)) { throw new ProtocolException( "Body content may not be sent in response to HTTP HEAD request"); } else { LOG.warn("Body content returned in response to HTTP HEAD"); } super.readResponseBody(state, conn); } } } /** * Returns non-compliant response body check timeout. * * @return The period of time in milliseconds to wait for a response * body from a non-compliant server. -1 returned when * non-compliant response body check is disabled * * @deprecated Use {@link HttpMethodParams} * * @see #getParams() * @see HttpMethodParams * @see HttpMethodParams#HEAD_BODY_CHECK_TIMEOUT */ public int getBodyCheckTimeout() { return getParams().getIntParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, -1); } /** * Sets non-compliant response body check timeout. * * @param timeout The period of time in milliseconds to wait for a response * body from a non-compliant server. -1 can be used to * disable non-compliant response body check * * @deprecated Use {@link HttpMethodParams} * * @see #getParams() * @see HttpMethodParams * @see HttpMethodParams#HEAD_BODY_CHECK_TIMEOUT */ public void setBodyCheckTimeout(int timeout) { getParams().setIntParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, timeout); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/InputStreamRequestEntity.java100644 0 0 15454 10661532626 31273 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/InputStreamRequestEntity.java,v 1.4 2004/05/17 21:46:03 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.methods; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A RequestEntity that contains an InputStream. * * @since 3.0 */ public class InputStreamRequestEntity implements RequestEntity { /** * The content length will be calculated automatically. This implies * buffering of the content. */ public static final int CONTENT_LENGTH_AUTO = -2; private static final Log LOG = LogFactory.getLog(InputStreamRequestEntity.class); private long contentLength; private InputStream content; /** The buffered request body, if any. */ private byte[] buffer = null; /** The content type */ private String contentType; /** * Creates a new InputStreamRequestEntity with the given content and a content type of * {@link #CONTENT_LENGTH_AUTO}. * @param content The content to set. */ public InputStreamRequestEntity(InputStream content) { this(content, null); } /** * Creates a new InputStreamRequestEntity with the given content, content type, and a * content length of {@link #CONTENT_LENGTH_AUTO}. * @param content The content to set. * @param contentType The type of the content, or null. */ public InputStreamRequestEntity(InputStream content, String contentType) { this(content, CONTENT_LENGTH_AUTO, contentType); } /** * Creates a new InputStreamRequestEntity with the given content and content length. * @param content The content to set. * @param contentLength The content size in bytes or a negative number if not known. * If {@link #CONTENT_LENGTH_AUTO} is given the content will be buffered in order to * determine its size when {@link #getContentLength()} is called. */ public InputStreamRequestEntity(InputStream content, long contentLength) { this(content, contentLength, null); } /** * Creates a new InputStreamRequestEntity with the given content, content length, and * content type. * @param content The content to set. * @param contentLength The content size in bytes or a negative number if not known. * If {@link #CONTENT_LENGTH_AUTO} is given the content will be buffered in order to * determine its size when {@link #getContentLength()} is called. * @param contentType The type of the content, or null. */ public InputStreamRequestEntity(InputStream content, long contentLength, String contentType) { if (content == null) { throw new IllegalArgumentException("The content cannot be null"); } this.content = content; this.contentLength = contentLength; this.contentType = contentType; } /* (non-Javadoc) * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType() */ public String getContentType() { return contentType; } /** * Buffers request body input stream. */ private void bufferContent() { if (this.buffer != null) { // Already been buffered return; } if (this.content != null) { try { ByteArrayOutputStream tmp = new ByteArrayOutputStream(); byte[] data = new byte[4096]; int l = 0; while ((l = this.content.read(data)) >= 0) { tmp.write(data, 0, l); } this.buffer = tmp.toByteArray(); this.content = null; this.contentLength = buffer.length; } catch (IOException e) { LOG.error(e.getMessage(), e); this.buffer = null; this.content = null; this.contentLength = 0; } } } /** * Tests if this method is repeatable. Only true if the content has been * buffered. * * @see #getContentLength() */ public boolean isRepeatable() { return buffer != null; } /* (non-Javadoc) * @see org.apache.commons.httpclient.RequestEntity#writeRequest(java.io.OutputStream) */ public void writeRequest(OutputStream out) throws IOException { if (content != null) { byte[] tmp = new byte[4096]; int total = 0; int i = 0; while ((i = content.read(tmp)) >= 0) { out.write(tmp, 0, i); total += i; } } else if (buffer != null) { out.write(buffer); } else { throw new IllegalStateException("Content must be set before entity is written"); } } /** * Gets the content length. If the content length has not been set, the content will be * buffered to determine the actual content length. */ public long getContentLength() { if (contentLength == CONTENT_LENGTH_AUTO && buffer == null) { bufferContent(); } return contentLength; } /** * @return Returns the content. */ public InputStream getContent() { return content; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/MultipartPostMethod.java100644 0 0 30227 10661532626 30235 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/MultipartPostMethod.java,v 1.27 2004/10/06 03:39:59 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.HttpConnection; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the HTTP multipart POST method. *

      * The HTTP multipart POST method is defined in section 3.3 of * RFC1867: *

      * The media-type multipart/form-data follows the rules of all multipart * MIME data streams as outlined in RFC 1521. The multipart/form-data contains * a series of parts. Each part is expected to contain a content-disposition * header where the value is "form-data" and a name attribute specifies * the field name within the form, e.g., 'content-disposition: form-data; * name="xxxxx"', where xxxxx is the field name corresponding to that field. * Field names originally in non-ASCII character sets may be encoded using * the method outlined in RFC 1522. *
      *

      *

      * * @author Matthew Albright * @author Jeff Dever * @author Adrian Sutton * @author Mark Diggory * @author Mike Bowler * @author Oleg Kalnichevski * * @since 2.0 * * @deprecated Use {@link org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity} * in conjunction with {@link org.apache.commons.httpclient.methods.PostMethod} instead. */ public class MultipartPostMethod extends ExpectContinueMethod { /** The Content-Type for multipart/form-data. */ public static final String MULTIPART_FORM_CONTENT_TYPE = "multipart/form-data"; /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(MultipartPostMethod.class); /** The parameters for this method */ private final List parameters = new ArrayList(); /** * No-arg constructor. */ public MultipartPostMethod() { super(); } /** * Constructor specifying a URI. * * @param uri either an absolute or relative URI */ public MultipartPostMethod(String uri) { super(uri); } /** * Returns true * * @return true * * @since 2.0beta1 */ protected boolean hasRequestContent() { return true; } /** * Returns "POST". * @return "POST" */ public String getName() { return "POST"; } /** * Adds a text field part * * @param parameterName The name of the parameter. * @param parameterValue The value of the parameter. */ public void addParameter(String parameterName, String parameterValue) { LOG.trace("enter addParameter(String parameterName, String parameterValue)"); Part param = new StringPart(parameterName, parameterValue); parameters.add(param); } /** * Adds a binary file part * * @param parameterName The name of the parameter * @param parameterFile The name of the file. * @throws FileNotFoundException If the file cannot be found. */ public void addParameter(String parameterName, File parameterFile) throws FileNotFoundException { LOG.trace("enter MultipartPostMethod.addParameter(String parameterName, " + "File parameterFile)"); Part param = new FilePart(parameterName, parameterFile); parameters.add(param); } /** * Adds a binary file part with the given file name * * @param parameterName The name of the parameter * @param fileName The file name * @param parameterFile The file * @throws FileNotFoundException If the file cannot be found. */ public void addParameter(String parameterName, String fileName, File parameterFile) throws FileNotFoundException { LOG.trace("enter MultipartPostMethod.addParameter(String parameterName, " + "String fileName, File parameterFile)"); Part param = new FilePart(parameterName, fileName, parameterFile); parameters.add(param); } /** * Adds a part. * * @param part The part to add. */ public void addPart (final Part part) { LOG.trace("enter addPart(Part part)"); parameters.add(part); } /** * Returns all parts. * * @return an array of containing all parts */ public Part[] getParts() { return (Part[]) parameters.toArray(new Part[parameters.size()]); } /** * Adds a Content-Length request header, as long as no * Content-Length request header already exists. * * @param state current state of http requests * @param conn the connection to use for I/O * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @since 3.0 */ protected void addContentLengthRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter EntityEnclosingMethod.addContentLengthRequestHeader(" + "HttpState, HttpConnection)"); if (getRequestHeader("Content-Length") == null) { long len = getRequestContentLength(); addRequestHeader("Content-Length", String.valueOf(len)); } removeRequestHeader("Transfer-Encoding"); } /** * Adds a Content-Type request header. * * @param state current state of http requests * @param conn the connection to use for I/O * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @since 3.0 */ protected void addContentTypeRequestHeader(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter EntityEnclosingMethod.addContentTypeRequestHeader(" + "HttpState, HttpConnection)"); if (!parameters.isEmpty()) { StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE); if (Part.getBoundary() != null) { buffer.append("; boundary="); buffer.append(Part.getBoundary()); } setRequestHeader("Content-Type", buffer.toString()); } } /** * Populates the request headers map to with additional * {@link org.apache.commons.httpclient.Header headers} to be submitted to * the given {@link HttpConnection}. * *

      * This implementation adds tt>Content-Length and Content-Type * headers, when appropriate. *

      * *

      * Subclasses may want to override this method to to add additional * headers, and may choose to invoke this implementation (via * super) to add the "standard" headers. *

      * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. * * @see #writeRequestHeaders */ protected void addRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter MultipartPostMethod.addRequestHeaders(HttpState state, " + "HttpConnection conn)"); super.addRequestHeaders(state, conn); addContentLengthRequestHeader(state, conn); addContentTypeRequestHeader(state, conn); } /** * Writes the request body to the given {@link HttpConnection connection}. * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @return true * * @throws IOException if an I/O (transport) error occurs. Some transport exceptions * can be recovered from. * @throws HttpException if a protocol exception occurs. Usually protocol exceptions * cannot be recovered from. */ protected boolean writeRequestBody(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter MultipartPostMethod.writeRequestBody(HttpState state, " + "HttpConnection conn)"); OutputStream out = conn.getRequestOutputStream(); Part.sendParts(out, getParts()); return true; } /** *

      Return the length of the request body.

      * *

      Once this method has been invoked, the request parameters cannot be * altered until the method is {@link #recycle recycled}.

      * * @return The request content length. */ protected long getRequestContentLength() throws IOException { LOG.trace("enter MultipartPostMethod.getRequestContentLength()"); return Part.getLengthOfParts(getParts()); } /** * Recycles the HTTP method so that it can be used again. * Note that all of the instance variables will be reset * once this method has been called. This method will also * release the connection being used by this HTTP method. * * @see #releaseConnection() * * @deprecated no longer supported and will be removed in the future * version of HttpClient */ public void recycle() { LOG.trace("enter MultipartPostMethod.recycle()"); super.recycle(); parameters.clear(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/OptionsMethod.java100644 0 0 13504 10661532626 27040 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/OptionsMethod.java,v 1.15 2004/04/18 23:51:37 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpConnection; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpState; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.util.Enumeration; import java.util.StringTokenizer; import java.util.Vector; /** * Implements the HTTP OPTIONS method. *

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

      * The OPTIONS method represents a request for information about the * communication options available on the request/response chain * identified by the Request-URI. This method allows the client to * determine the options and/or requirements associated with a resource, * or the capabilities of a server, without implying a resource action * or initiating a resource retrieval. *
      *

      * * @author Remy Maucherat * @author Mike Bowler * @author Jeff Dever * * @version $Revision: 480424 $ * @since 1.0 */ public class OptionsMethod extends HttpMethodBase { // --------------------------------------------------------- Class Variables /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(OptionsMethod.class); // ----------------------------------------------------------- Constructors /** * Method constructor. * * @since 1.0 */ public OptionsMethod() { } /** * Constructor specifying a URI. * * @param uri either an absolute or relative URI * * @since 1.0 */ public OptionsMethod(String uri) { super(uri); } // ----------------------------------------------------- Instance Variables /** * Methods allowed. */ private Vector methodsAllowed = new Vector(); // --------------------------------------------------------- Public Methods /** * Get the name. * @return "OPTIONS" * @since 2.0 */ public String getName() { return "OPTIONS"; } /** * Is the specified method allowed ? * * @param method The method to check. * @return true if the specified method is allowed. * @since 1.0 */ public boolean isAllowed(String method) { checkUsed(); return methodsAllowed.contains(method); } /** * Get a list of allowed methods. * @return An enumeration of all the allowed methods. * * @since 1.0 */ public Enumeration getAllowedMethods() { checkUsed(); return methodsAllowed.elements(); } // ----------------------------------------------------- HttpMethod Methods /** *

      * This implementation will parse the Allow header to obtain * the set of methods supported by the resource identified by the Request-URI. *

      * * @param state the {@link HttpState state} information associated with this method * @param conn the {@link HttpConnection connection} used to execute * this HTTP method * * @see #readResponse * @see #readResponseHeaders * @since 2.0 */ protected void processResponseHeaders(HttpState state, HttpConnection conn) { LOG.trace("enter OptionsMethod.processResponseHeaders(HttpState, HttpConnection)"); Header allowHeader = getResponseHeader("allow"); if (allowHeader != null) { String allowHeaderValue = allowHeader.getValue(); StringTokenizer tokenizer = new StringTokenizer(allowHeaderValue, ","); while (tokenizer.hasMoreElements()) { String methodAllowed = tokenizer.nextToken().trim().toUpperCase(); methodsAllowed.addElement(methodAllowed); } } } /** * Return true if the method needs a content-length header in the request. * * @return true if a content-length header will be expected by the server * * @since 1.0 * * @deprecated only entity enclosing methods set content length header */ public boolean needContentLength() { return false; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/PostMethod.java100644 0 0 32442 10661532626 26334 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/PostMethod.java,v 1.58 2004/08/08 12:50:09 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; import java.util.Iterator; import java.util.Vector; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.util.EncodingUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the HTTP POST method. *

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

      * The POST method is used to request that the origin server accept the entity * enclosed in the request as a new subordinate of the resource identified by * the Request-URI in the Request-Line. POST is designed to allow a uniform * method to cover the following functions: *
        *
      • Annotation of existing resources
      • *
      • Posting a message to a bulletin board, newsgroup, mailing list, or * similar group of articles
      • *
      • Providing a block of data, such as the result of submitting a form, * to a data-handling process
      • *
      • Extending a database through an append operation
      • *
      *
      *

      * * @author Remy Maucherat * @author Doug Sale * @author Jeff Dever * @author Ortwin Gl???ck * @author Mike Bowler * @author Oleg Kalnichevski * * @version $Revision: 480424 $ * @since 1.0 */ public class PostMethod extends EntityEnclosingMethod { // -------------------------------------------------------------- Constants /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(PostMethod.class); /** The Content-Type for www-form-urlencoded. */ public static final String FORM_URL_ENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded"; /** * The buffered request body consisting of NameValuePairs. */ private Vector params = new Vector(); // ----------------------------------------------------------- Constructors /** * No-arg constructor. * * @since 1.0 */ public PostMethod() { super(); } /** * Constructor specifying a URI. * * @param uri either an absolute or relative URI * * @since 1.0 */ public PostMethod(String uri) { super(uri); } // ----------------------------------------------------- Instance Methods /** * Returns "POST". * * @return "POST" * * @since 2.0 */ public String getName() { return "POST"; } /** * Returns true if there is a request body to be sent. * *

      This method must be overwritten by sub-classes that implement * alternative request content input methods *

      * * @return boolean * * @since 2.0beta1 */ protected boolean hasRequestContent() { LOG.trace("enter PostMethod.hasRequestContent()"); if (!this.params.isEmpty()) { return true; } else { return super.hasRequestContent(); } } /** * Clears request body. * *

      This method must be overwritten by sub-classes that implement * alternative request content input methods

      * * @since 2.0beta1 */ protected void clearRequestBody() { LOG.trace("enter PostMethod.clearRequestBody()"); this.params.clear(); super.clearRequestBody(); } /** * Generates a request entity from the post parameters, if present. Calls * {@link EntityEnclosingMethod#generateRequestBody()} if parameters have not been set. * * @since 3.0 */ protected RequestEntity generateRequestEntity() { if (!this.params.isEmpty()) { // Use a ByteArrayRequestEntity instead of a StringRequestEntity. // This is to avoid potential encoding issues. Form url encoded strings // are ASCII by definition but the content type may not be. Treating the content // as bytes allows us to keep the current charset without worrying about how // this charset will effect the encoding of the form url encoded string. String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet()); ByteArrayRequestEntity entity = new ByteArrayRequestEntity( EncodingUtil.getAsciiBytes(content), FORM_URL_ENCODED_CONTENT_TYPE ); return entity; } else { return super.generateRequestEntity(); } } /** * Sets the value of parameter with parameterName to parameterValue. This method * does not preserve the initial insertion order. * * @param parameterName name of the parameter * @param parameterValue value of the parameter * * @since 2.0 */ public void setParameter(String parameterName, String parameterValue) { LOG.trace("enter PostMethod.setParameter(String, String)"); removeParameter(parameterName); addParameter(parameterName, parameterValue); } /** * Gets the parameter of the specified name. If there exists more than one * parameter with the name paramName, then only the first one is returned. * * @param paramName name of the parameter * * @return If a parameter exists with the name argument, the coresponding * NameValuePair is returned. Otherwise null. * * @since 2.0 * */ public NameValuePair getParameter(String paramName) { LOG.trace("enter PostMethod.getParameter(String)"); if (paramName == null) { return null; } Iterator iter = this.params.iterator(); while (iter.hasNext()) { NameValuePair parameter = (NameValuePair) iter.next(); if (paramName.equals(parameter.getName())) { return parameter; } } return null; } /** * Gets the parameters currently added to the PostMethod. If there are no * parameters, a valid array is returned with zero elements. The returned * array object contains an array of pointers to the internal data * members. * * @return An array of the current parameters * * @since 2.0 * */ public NameValuePair[] getParameters() { LOG.trace("enter PostMethod.getParameters()"); int numPairs = this.params.size(); Object[] objectArr = this.params.toArray(); NameValuePair[] nvPairArr = new NameValuePair[numPairs]; for (int i = 0; i < numPairs; i++) { nvPairArr[i] = (NameValuePair) objectArr[i]; } return nvPairArr; } /** * Adds a new parameter to be used in the POST request body. * * @param paramName The parameter name to add. * @param paramValue The parameter value to add. * * @throws IllegalArgumentException if either argument is null * * @since 1.0 */ public void addParameter(String paramName, String paramValue) throws IllegalArgumentException { LOG.trace("enter PostMethod.addParameter(String, String)"); if ((paramName == null) || (paramValue == null)) { throw new IllegalArgumentException( "Arguments to addParameter(String, String) cannot be null"); } super.clearRequestBody(); this.params.add(new NameValuePair(paramName, paramValue)); } /** * Adds a new parameter to be used in the POST request body. * * @param param The parameter to add. * * @throws IllegalArgumentException if the argument is null or contains * null values * * @since 2.0 */ public void addParameter(NameValuePair param) throws IllegalArgumentException { LOG.trace("enter PostMethod.addParameter(NameValuePair)"); if (param == null) { throw new IllegalArgumentException("NameValuePair may not be null"); } addParameter(param.getName(), param.getValue()); } /** * Adds an array of parameters to be used in the POST request body. Logs a * warning if the parameters argument is null. * * @param parameters The array of parameters to add. * * @since 2.0 */ public void addParameters(NameValuePair[] parameters) { LOG.trace("enter PostMethod.addParameters(NameValuePair[])"); if (parameters == null) { LOG.warn("Attempt to addParameters(null) ignored"); } else { super.clearRequestBody(); for (int i = 0; i < parameters.length; i++) { this.params.add(parameters[i]); } } } /** * Removes all parameters with the given paramName. If there is more than * one parameter with the given paramName, all of them are removed. If * there is just one, it is removed. If there are none, then the request * is ignored. * * @param paramName The parameter name to remove. * * @return true if at least one parameter was removed * * @throws IllegalArgumentException When the parameter name passed is null * * @since 2.0 */ public boolean removeParameter(String paramName) throws IllegalArgumentException { LOG.trace("enter PostMethod.removeParameter(String)"); if (paramName == null) { throw new IllegalArgumentException( "Argument passed to removeParameter(String) cannot be null"); } boolean removed = false; Iterator iter = this.params.iterator(); while (iter.hasNext()) { NameValuePair pair = (NameValuePair) iter.next(); if (paramName.equals(pair.getName())) { iter.remove(); removed = true; } } return removed; } /** * Removes all parameter with the given paramName and paramValue. If there * is more than one parameter with the given paramName, only one is * removed. If there are none, then the request is ignored. * * @param paramName The parameter name to remove. * @param paramValue The parameter value to remove. * * @return true if a parameter was removed. * * @throws IllegalArgumentException when param name or value are null * * @since 2.0 */ public boolean removeParameter(String paramName, String paramValue) throws IllegalArgumentException { LOG.trace("enter PostMethod.removeParameter(String, String)"); if (paramName == null) { throw new IllegalArgumentException("Parameter name may not be null"); } if (paramValue == null) { throw new IllegalArgumentException("Parameter value may not be null"); } Iterator iter = this.params.iterator(); while (iter.hasNext()) { NameValuePair pair = (NameValuePair) iter.next(); if (paramName.equals(pair.getName()) && paramValue.equals(pair.getValue())) { iter.remove(); return true; } } return false; } /** * Sets an array of parameters to be used in the POST request body * * @param parametersBody The array of parameters to add. * * @throws IllegalArgumentException when param parameters are null * * @since 2.0beta1 */ public void setRequestBody(NameValuePair[] parametersBody) throws IllegalArgumentException { LOG.trace("enter PostMethod.setRequestBody(NameValuePair[])"); if (parametersBody == null) { throw new IllegalArgumentException("Array of parameters may not be null"); } clearRequestBody(); addParameters(parametersBody); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/PutMethod.java100644 0 0 5704 10661532626 26140 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/PutMethod.java,v 1.26 2004/04/18 23:51:37 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; /** * Implements the HTTP PUT method. *

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

      * The PUT method requests that the enclosed entity be stored under the * supplied Request-URI. If the Request-URI refers to an already * existing resource, the enclosed entity SHOULD be considered as a * modified version of the one residing on the origin server. *
      *

      * * @author Remy Maucherat * @author Mike Bowler * @author Oleg Kalnichevski * @author Jeff Dever * * @version $Revision: 480424 $ * @since 1.0 */ public class PutMethod extends EntityEnclosingMethod { // ----------------------------------------------------------- Constructors /** * No-arg constructor. * * @since 1.0 */ public PutMethod() { super(); } /** * Constructor specifying a URI. * * @param uri either an absolute or relative URI * * @since 1.0 */ public PutMethod(String uri) { super(uri); } // --------------------------------------------------------- Public Methods /** * Return "PUT". * @return "PUT" * * @since 2.0 */ public String getName() { return "PUT"; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/RequestEntity.java100644 0 0 5523 10661532626 27053 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/RequestEntity.java,v 1.4 2004/05/17 21:46:03 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; import java.io.IOException; import java.io.OutputStream; /** * @since 3.0 */ public interface RequestEntity { /** * Tests if {@link #writeRequest(OutputStream)} can be called more than once. * * @return true if the entity can be written to {@link OutputStream} more than once, * false otherwise. */ boolean isRepeatable(); /** * Writes the request entity to the given stream. * @param out * @throws IOException */ void writeRequest(OutputStream out) throws IOException; /** * Gets the request entity's length. This method should return a non-negative value if the content * length is known or a negative value if it is not. In the latter case the * {@link org.apache.commons.httpclient.methods.EntityEnclosingMethod} will use chunk encoding to * transmit the request entity. * * @return a non-negative value when content length is known or a negative value when content length * is not known */ long getContentLength(); /** * Gets the entity's content type. This content type will be used as the value for the * "Content-Type" header. * @return the entity's content type * @see org.apache.commons.httpclient.HttpMethod#setRequestHeader(String, String) */ String getContentType(); } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/StringRequestEntity.java100644 0 0 14177 10661532627 30270 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/methods/StringRequestEntity.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.methods; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import org.apache.commons.httpclient.HeaderElement; import org.apache.commons.httpclient.NameValuePair; /** * A RequestEntity that contains a String. * * @since 3.0 */ public class StringRequestEntity implements RequestEntity { /** The content */ private byte[] content; /** The charset */ private String charset; /** The content type (i.e. text/html; charset=EUC-JP). */ private String contentType; /** *

      Creates a new entity with the given content. This constructor * will use the default platform charset to convert the content string * and will provide no content type.

      * * @see #StringRequestEntity(String, String, String) * * @param content The content to set. * * @deprecated use {@link #StringRequestEntity(String, String, String)} instead */ public StringRequestEntity(String content) { super(); if (content == null) { throw new IllegalArgumentException("The content cannot be null"); } this.contentType = null; this.charset = null; this.content = content.getBytes(); } /** * Creates a new entity with the given content, content type, and charset. * * @param content The content to set. * @param contentType The type of the content, or null. The value retured * by {@link #getContentType()}. If this content type contains a charset and the charset * parameter is null, the content's type charset will be used. * @param charset The charset of the content, or null. Used to convert the * content to bytes. If the content type does not contain a charset and charset is not null, * then the charset will be appended to the content type. */ public StringRequestEntity(String content, String contentType, String charset) throws UnsupportedEncodingException { super(); if (content == null) { throw new IllegalArgumentException("The content cannot be null"); } this.contentType = contentType; this.charset = charset; // resolve the content type and the charset if (contentType != null) { HeaderElement[] values = HeaderElement.parseElements(contentType); NameValuePair charsetPair = null; for (int i = 0; i < values.length; i++) { if ((charsetPair = values[i].getParameterByName("charset")) != null) { // charset found break; } } if (charset == null && charsetPair != null) { // use the charset from the content type this.charset = charsetPair.getValue(); } else if (charset != null && charsetPair == null) { // append the charset to the content type this.contentType = contentType + "; charset=" + charset; } } if (this.charset != null) { this.content = content.getBytes(this.charset); } else { this.content = content.getBytes(); } } /* (non-Javadoc) * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType() */ public String getContentType() { return contentType; } /** * @return true */ public boolean isRepeatable() { return true; } /* (non-Javadoc) * @see org.apache.commons.httpclient.RequestEntity#writeRequest(java.io.OutputStream) */ public void writeRequest(OutputStream out) throws IOException { if (out == null) { throw new IllegalArgumentException("Output stream may not be null"); } out.write(this.content); out.flush(); } /** * @return The length of the content. */ public long getContentLength() { return this.content.length; } /** * @return Returns the content. */ public String getContent() { if (this.charset != null) { try { return new String(this.content, this.charset); } catch (UnsupportedEncodingException e) { return new String(this.content); } } else { return new String(this.content); } } /** * @return Returns the charset used to convert the content to bytes. null if * no charset as been specified. */ public String getCharset() { return charset; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/TraceMethod.java100644 0 0 6432 10661532626 26425 0ustar 0 0 /* * $Header: $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods; import org.apache.commons.httpclient.HttpMethodBase; /** * Implements the HTTP TRACE method. *

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

      * The TRACE method is used to invoke a remote, application-layer loop- * back of the request message. The final recipient of the request * SHOULD reflect the message received back to the client as the * entity-body of a 200 (OK) response. The final recipient is either the * origin server or the first proxy or gateway to receive a Max-Forwards * value of zero (0) in the request (see section 14.31). A TRACE request * MUST NOT include an entity. *
      *

      * * @author Sean C. Sullivan * @author Mike Bowler * @author Jeff Dever * * @version $Revision: 480424 $ * @since 2.0 * */ public class TraceMethod extends HttpMethodBase { //~ Constructors /** * Constructor specifying a URI. * * @param uri either an absolute or relative URI * * @since 2.0 * */ public TraceMethod(String uri) { super(uri); setFollowRedirects(false); } //~ Methods /** * Returns "TRACE". * * @return "TRACE" * * @since 2.0 * */ public String getName() { return "TRACE"; } /** * Recycles the HTTP method so that it can be used again. * Note that all of the instance variables will be reset * once this method has been called. This method will also * release the connection being used by this HTTP method. * * @see #releaseConnection() * * @since 2.0 * * @deprecated no longer supported and will be removed in the future * version of HttpClient */ public void recycle() { super.recycle(); setFollowRedirects(false); } } ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/ByteArrayPartSource.javacommons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/ByteArrayPartSource.100644 0 0 5364 10661532626 31322 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/ByteArrayPartSource.java,v 1.7 2004/04/18 23:51:37 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods.multipart; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * A PartSource that reads from a byte array. This class should be used when * the data to post is already loaded into memory. * * @author Michael Becke * * @since 2.0 */ public class ByteArrayPartSource implements PartSource { /** Name of the source file. */ private String fileName; /** Byte array of the source file. */ private byte[] bytes; /** * Constructor for ByteArrayPartSource. * * @param fileName the name of the file these bytes represent * @param bytes the content of this part */ public ByteArrayPartSource(String fileName, byte[] bytes) { this.fileName = fileName; this.bytes = bytes; } /** * @see PartSource#getLength() */ public long getLength() { return bytes.length; } /** * @see PartSource#getFileName() */ public String getFileName() { return fileName; } /** * @see PartSource#createInputStream() */ public InputStream createInputStream() throws IOException { return new ByteArrayInputStream(bytes); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/FilePart.java100644 0 0 21601 10661532626 27770 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/FilePart.java,v 1.19 2004/04/18 23:51:37 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods.multipart; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.httpclient.util.EncodingUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class implements a part of a Multipart post object that * consists of a file. * * @author Matthew Albright * @author Jeff Dever * @author Adrian Sutton * @author Michael Becke * @author Mark Diggory * @author Mike Bowler * @author Oleg Kalnichevski * * @since 2.0 * */ public class FilePart extends PartBase { /** Default content encoding of file attachments. */ public static final String DEFAULT_CONTENT_TYPE = "application/octet-stream"; /** Default charset of file attachments. */ public static final String DEFAULT_CHARSET = "ISO-8859-1"; /** Default transfer encoding of file attachments. */ public static final String DEFAULT_TRANSFER_ENCODING = "binary"; /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(FilePart.class); /** Attachment's file name */ protected static final String FILE_NAME = "; filename="; /** Attachment's file name as a byte array */ private static final byte[] FILE_NAME_BYTES = EncodingUtil.getAsciiBytes(FILE_NAME); /** Source of the file part. */ private PartSource source; /** * FilePart Constructor. * * @param name the name for this part * @param partSource the source for this part * @param contentType the content type for this part, if null the * {@link #DEFAULT_CONTENT_TYPE default} is used * @param charset the charset encoding for this part, if null the * {@link #DEFAULT_CHARSET default} is used */ public FilePart(String name, PartSource partSource, String contentType, String charset) { super( name, contentType == null ? DEFAULT_CONTENT_TYPE : contentType, charset == null ? "ISO-8859-1" : charset, DEFAULT_TRANSFER_ENCODING ); if (partSource == null) { throw new IllegalArgumentException("Source may not be null"); } this.source = partSource; } /** * FilePart Constructor. * * @param name the name for this part * @param partSource the source for this part */ public FilePart(String name, PartSource partSource) { this(name, partSource, null, null); } /** * FilePart Constructor. * * @param name the name of the file part * @param file the file to post * * @throws FileNotFoundException if the file is not a normal * file or if it is not readable. */ public FilePart(String name, File file) throws FileNotFoundException { this(name, new FilePartSource(file), null, null); } /** * FilePart Constructor. * * @param name the name of the file part * @param file the file to post * @param contentType the content type for this part, if null the * {@link #DEFAULT_CONTENT_TYPE default} is used * @param charset the charset encoding for this part, if null the * {@link #DEFAULT_CHARSET default} is used * * @throws FileNotFoundException if the file is not a normal * file or if it is not readable. */ public FilePart(String name, File file, String contentType, String charset) throws FileNotFoundException { this(name, new FilePartSource(file), contentType, charset); } /** * FilePart Constructor. * * @param name the name of the file part * @param fileName the file name * @param file the file to post * * @throws FileNotFoundException if the file is not a normal * file or if it is not readable. */ public FilePart(String name, String fileName, File file) throws FileNotFoundException { this(name, new FilePartSource(fileName, file), null, null); } /** * FilePart Constructor. * * @param name the name of the file part * @param fileName the file name * @param file the file to post * @param contentType the content type for this part, if null the * {@link #DEFAULT_CONTENT_TYPE default} is used * @param charset the charset encoding for this part, if null the * {@link #DEFAULT_CHARSET default} is used * * @throws FileNotFoundException if the file is not a normal * file or if it is not readable. */ public FilePart(String name, String fileName, File file, String contentType, String charset) throws FileNotFoundException { this(name, new FilePartSource(fileName, file), contentType, charset); } /** * Write the disposition header to the output stream * @param out The output stream * @throws IOException If an IO problem occurs * @see Part#sendDispositionHeader(OutputStream) */ protected void sendDispositionHeader(OutputStream out) throws IOException { LOG.trace("enter sendDispositionHeader(OutputStream out)"); super.sendDispositionHeader(out); String filename = this.source.getFileName(); if (filename != null) { out.write(FILE_NAME_BYTES); out.write(QUOTE_BYTES); out.write(EncodingUtil.getAsciiBytes(filename)); out.write(QUOTE_BYTES); } } /** * Write the data in "source" to the specified stream. * @param out The output stream. * @throws IOException if an IO problem occurs. * @see org.apache.commons.httpclient.methods.multipart.Part#sendData(OutputStream) */ protected void sendData(OutputStream out) throws IOException { LOG.trace("enter sendData(OutputStream out)"); if (lengthOfData() == 0) { // this file contains no data, so there is nothing to send. // we don't want to create a zero length buffer as this will // cause an infinite loop when reading. LOG.debug("No data to send."); return; } byte[] tmp = new byte[4096]; InputStream instream = source.createInputStream(); try { int len; while ((len = instream.read(tmp)) >= 0) { out.write(tmp, 0, len); } } finally { // we're done with the stream, close it instream.close(); } } /** * Returns the source of the file part. * * @return The source. */ protected PartSource getSource() { LOG.trace("enter getSource()"); return this.source; } /** * Return the length of the data. * @return The length. * @throws IOException if an IO problem occurs * @see org.apache.commons.httpclient.methods.multipart.Part#lengthOfData() */ protected long lengthOfData() throws IOException { LOG.trace("enter lengthOfData()"); return source.getLength(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/FilePartSource.java100644 0 0 10275 10661532626 31156 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/FilePartSource.java,v 1.10 2004/04/18 23:51:37 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods.multipart; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * A PartSource that reads from a File. * * @author Michael Becke * @author Mark Diggory * @author Mike Bowler * * @since 2.0 */ public class FilePartSource implements PartSource { /** File part file. */ private File file = null; /** File part file name. */ private String fileName = null; /** * Constructor for FilePartSource. * * @param file the FilePart source File. * * @throws FileNotFoundException if the file does not exist or * cannot be read */ public FilePartSource(File file) throws FileNotFoundException { this.file = file; if (file != null) { if (!file.isFile()) { throw new FileNotFoundException("File is not a normal file."); } if (!file.canRead()) { throw new FileNotFoundException("File is not readable."); } this.fileName = file.getName(); } } /** * Constructor for FilePartSource. * * @param fileName the file name of the FilePart * @param file the source File for the FilePart * * @throws FileNotFoundException if the file does not exist or * cannot be read */ public FilePartSource(String fileName, File file) throws FileNotFoundException { this(file); if (fileName != null) { this.fileName = fileName; } } /** * Return the length of the file * @return the length of the file. * @see PartSource#getLength() */ public long getLength() { if (this.file != null) { return this.file.length(); } else { return 0; } } /** * Return the current filename * @return the filename. * @see PartSource#getFileName() */ public String getFileName() { return (fileName == null) ? "noname" : fileName; } /** * Return a new {@link FileInputStream} for the current filename. * @return the new input stream. * @throws IOException If an IO problem occurs. * @see PartSource#createInputStream() */ public InputStream createInputStream() throws IOException { if (this.file != null) { return new FileInputStream(this.file); } else { return new ByteArrayInputStream(new byte[] {}); } } } ././@LongLink100644 0 0 154 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/MultipartRequestEntity.javacommons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/MultipartRequestEnti100644 0 0 16341 10661532626 31521 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/MultipartRequestEntity.java,v 1.1 2004/10/06 03:39:59 mbecke Exp $ * $Revision: 502647 $ * $Date: 2007-02-02 17:22:54 +0100 (Fri, 02 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods.multipart; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.util.EncodingUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements a request entity suitable for an HTTP multipart POST method. *

      * The HTTP multipart POST method is defined in section 3.3 of * RFC1867: *

      * The media-type multipart/form-data follows the rules of all multipart * MIME data streams as outlined in RFC 1521. The multipart/form-data contains * a series of parts. Each part is expected to contain a content-disposition * header where the value is "form-data" and a name attribute specifies * the field name within the form, e.g., 'content-disposition: form-data; * name="xxxxx"', where xxxxx is the field name corresponding to that field. * Field names originally in non-ASCII character sets may be encoded using * the method outlined in RFC 1522. *
      *

      *

      This entity is designed to be used in conjunction with the * {@link org.apache.commons.httpclient.methods.PostMethod post method} to provide * multipart posts. Example usage:

      *
       *  File f = new File("/path/fileToUpload.txt");
       *  PostMethod filePost = new PostMethod("http://host/some_path");
       *  Part[] parts = {
       *      new StringPart("param_name", "value"),
       *      new FilePart(f.getName(), f)
       *  };
       *  filePost.setRequestEntity(
       *      new MultipartRequestEntity(parts, filePost.getParams())
       *      );
       *  HttpClient client = new HttpClient();
       *  int status = client.executeMethod(filePost);
       * 
      * * @since 3.0 */ public class MultipartRequestEntity implements RequestEntity { private static final Log log = LogFactory.getLog(MultipartRequestEntity.class); /** The Content-Type for multipart/form-data. */ private static final String MULTIPART_FORM_CONTENT_TYPE = "multipart/form-data"; /** * The pool of ASCII chars to be used for generating a multipart boundary. */ private static byte[] MULTIPART_CHARS = EncodingUtil.getAsciiBytes( "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); /** * Generates a random multipart boundary string. * @return */ private static byte[] generateMultipartBoundary() { Random rand = new Random(); byte[] bytes = new byte[rand.nextInt(11) + 30]; // a random size from 30 to 40 for (int i = 0; i < bytes.length; i++) { bytes[i] = MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]; } return bytes; } /** The MIME parts as set by the constructor */ protected Part[] parts; private byte[] multipartBoundary; private HttpMethodParams params; /** * Creates a new multipart entity containing the given parts. * @param parts The parts to include. * @param params The params of the HttpMethod using this entity. */ public MultipartRequestEntity(Part[] parts, HttpMethodParams params) { if (parts == null) { throw new IllegalArgumentException("parts cannot be null"); } if (params == null) { throw new IllegalArgumentException("params cannot be null"); } this.parts = parts; this.params = params; } /** * Returns the MIME boundary string that is used to demarcate boundaries of * this part. The first call to this method will implicitly create a new * boundary string. To create a boundary string first the * HttpMethodParams.MULTIPART_BOUNDARY parameter is considered. Otherwise * a random one is generated. * * @return The boundary string of this entity in ASCII encoding. */ protected byte[] getMultipartBoundary() { if (multipartBoundary == null) { String temp = (String) params.getParameter(HttpMethodParams.MULTIPART_BOUNDARY); if (temp != null) { multipartBoundary = EncodingUtil.getAsciiBytes(temp); } else { multipartBoundary = generateMultipartBoundary(); } } return multipartBoundary; } /** * Returns true if all parts are repeatable, false otherwise. * @see org.apache.commons.httpclient.methods.RequestEntity#isRepeatable() */ public boolean isRepeatable() { for (int i = 0; i < parts.length; i++) { if (!parts[i].isRepeatable()) { return false; } } return true; } /* (non-Javadoc) * @see org.apache.commons.httpclient.methods.RequestEntity#writeRequest(java.io.OutputStream) */ public void writeRequest(OutputStream out) throws IOException { Part.sendParts(out, parts, getMultipartBoundary()); } /* (non-Javadoc) * @see org.apache.commons.httpclient.methods.RequestEntity#getContentLength() */ public long getContentLength() { try { return Part.getLengthOfParts(parts, getMultipartBoundary()); } catch (Exception e) { log.error("An exception occurred while getting the length of the parts", e); return 0; } } /* (non-Javadoc) * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType() */ public String getContentType() { StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE); buffer.append("; boundary="); buffer.append(EncodingUtil.getAsciiString(getMultipartBoundary())); return buffer.toString(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/Part.java100644 0 0 35064 10661532626 27200 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/Part.java,v 1.16 2005/01/14 21:16:40 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods.multipart; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.httpclient.util.EncodingUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Abstract class for one Part of a multipart post object. * * @author Matthew Albright * @author Jeff Dever * @author Adrian Sutton * @author Mike Bowler * @author Oleg Kalnichevski * * @since 2.0 */ public abstract class Part { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(Part.class); /** * The boundary * @deprecated use {@link org.apache.commons.httpclient.params.HttpMethodParams#MULTIPART_BOUNDARY} */ protected static final String BOUNDARY = "----------------314159265358979323846"; /** * The boundary as a byte array. * @deprecated */ protected static final byte[] BOUNDARY_BYTES = EncodingUtil.getAsciiBytes(BOUNDARY); /** * The default boundary to be used if {@link #setBoundaryBytes(byte[])) has not * been called. */ private static final byte[] DEFAULT_BOUNDARY_BYTES = BOUNDARY_BYTES; /** Carriage return/linefeed */ protected static final String CRLF = "\r\n"; /** Carriage return/linefeed as a byte array */ protected static final byte[] CRLF_BYTES = EncodingUtil.getAsciiBytes(CRLF); /** Content dispostion characters */ protected static final String QUOTE = "\""; /** Content dispostion as a byte array */ protected static final byte[] QUOTE_BYTES = EncodingUtil.getAsciiBytes(QUOTE); /** Extra characters */ protected static final String EXTRA = "--"; /** Extra characters as a byte array */ protected static final byte[] EXTRA_BYTES = EncodingUtil.getAsciiBytes(EXTRA); /** Content dispostion characters */ protected static final String CONTENT_DISPOSITION = "Content-Disposition: form-data; name="; /** Content dispostion as a byte array */ protected static final byte[] CONTENT_DISPOSITION_BYTES = EncodingUtil.getAsciiBytes(CONTENT_DISPOSITION); /** Content type header */ protected static final String CONTENT_TYPE = "Content-Type: "; /** Content type header as a byte array */ protected static final byte[] CONTENT_TYPE_BYTES = EncodingUtil.getAsciiBytes(CONTENT_TYPE); /** Content charset */ protected static final String CHARSET = "; charset="; /** Content charset as a byte array */ protected static final byte[] CHARSET_BYTES = EncodingUtil.getAsciiBytes(CHARSET); /** Content type header */ protected static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: "; /** Content type header as a byte array */ protected static final byte[] CONTENT_TRANSFER_ENCODING_BYTES = EncodingUtil.getAsciiBytes(CONTENT_TRANSFER_ENCODING); /** * Return the boundary string. * @return the boundary string * @deprecated uses a constant string. Rather use {@link #getPartBoundary} */ public static String getBoundary() { return BOUNDARY; } /** * The ASCII bytes to use as the multipart boundary. */ private byte[] boundaryBytes; /** * Return the name of this part. * @return The name. */ public abstract String getName(); /** * Returns the content type of this part. * @return the content type, or null to exclude the content type header */ public abstract String getContentType(); /** * Return the character encoding of this part. * @return the character encoding, or null to exclude the character * encoding header */ public abstract String getCharSet(); /** * Return the transfer encoding of this part. * @return the transfer encoding, or null to exclude the transfer encoding header */ public abstract String getTransferEncoding(); /** * Gets the part boundary to be used. * @return the part boundary as an array of bytes. * * @since 3.0 */ protected byte[] getPartBoundary() { if (boundaryBytes == null) { // custom boundary bytes have not been set, use the default. return DEFAULT_BOUNDARY_BYTES; } else { return boundaryBytes; } } /** * Sets the part boundary. Only meant to be used by * {@link Part#sendParts(OutputStream, Part[], byte[])} * and {@link Part#getLengthOfParts(Part[], byte[])} * @param boundaryBytes An array of ASCII bytes. * @since 3.0 */ void setPartBoundary(byte[] boundaryBytes) { this.boundaryBytes = boundaryBytes; } /** * Tests if this part can be sent more than once. * @return true if {@link #sendData(OutputStream)} can be successfully called * more than once. * @since 3.0 */ public boolean isRepeatable() { return true; } /** * Write the start to the specified output stream * @param out The output stream * @throws IOException If an IO problem occurs. */ protected void sendStart(OutputStream out) throws IOException { LOG.trace("enter sendStart(OutputStream out)"); out.write(EXTRA_BYTES); out.write(getPartBoundary()); out.write(CRLF_BYTES); } /** * Write the content disposition header to the specified output stream * * @param out The output stream * @throws IOException If an IO problem occurs. */ protected void sendDispositionHeader(OutputStream out) throws IOException { LOG.trace("enter sendDispositionHeader(OutputStream out)"); out.write(CONTENT_DISPOSITION_BYTES); out.write(QUOTE_BYTES); out.write(EncodingUtil.getAsciiBytes(getName())); out.write(QUOTE_BYTES); } /** * Write the content type header to the specified output stream * @param out The output stream * @throws IOException If an IO problem occurs. */ protected void sendContentTypeHeader(OutputStream out) throws IOException { LOG.trace("enter sendContentTypeHeader(OutputStream out)"); String contentType = getContentType(); if (contentType != null) { out.write(CRLF_BYTES); out.write(CONTENT_TYPE_BYTES); out.write(EncodingUtil.getAsciiBytes(contentType)); String charSet = getCharSet(); if (charSet != null) { out.write(CHARSET_BYTES); out.write(EncodingUtil.getAsciiBytes(charSet)); } } } /** * Write the content transfer encoding header to the specified * output stream * * @param out The output stream * @throws IOException If an IO problem occurs. */ protected void sendTransferEncodingHeader(OutputStream out) throws IOException { LOG.trace("enter sendTransferEncodingHeader(OutputStream out)"); String transferEncoding = getTransferEncoding(); if (transferEncoding != null) { out.write(CRLF_BYTES); out.write(CONTENT_TRANSFER_ENCODING_BYTES); out.write(EncodingUtil.getAsciiBytes(transferEncoding)); } } /** * Write the end of the header to the output stream * @param out The output stream * @throws IOException If an IO problem occurs. */ protected void sendEndOfHeader(OutputStream out) throws IOException { LOG.trace("enter sendEndOfHeader(OutputStream out)"); out.write(CRLF_BYTES); out.write(CRLF_BYTES); } /** * Write the data to the specified output stream * @param out The output stream * @throws IOException If an IO problem occurs. */ protected abstract void sendData(OutputStream out) throws IOException; /** * Return the length of the main content * * @return long The length. * @throws IOException If an IO problem occurs */ protected abstract long lengthOfData() throws IOException; /** * Write the end data to the output stream. * @param out The output stream * @throws IOException If an IO problem occurs. */ protected void sendEnd(OutputStream out) throws IOException { LOG.trace("enter sendEnd(OutputStream out)"); out.write(CRLF_BYTES); } /** * Write all the data to the output stream. * If you override this method make sure to override * #length() as well * * @param out The output stream * @throws IOException If an IO problem occurs. */ public void send(OutputStream out) throws IOException { LOG.trace("enter send(OutputStream out)"); sendStart(out); sendDispositionHeader(out); sendContentTypeHeader(out); sendTransferEncodingHeader(out); sendEndOfHeader(out); sendData(out); sendEnd(out); } /** * Return the full length of all the data. * If you override this method make sure to override * #send(OutputStream) as well * * @return long The length. * @throws IOException If an IO problem occurs */ public long length() throws IOException { LOG.trace("enter length()"); if (lengthOfData() < 0) { return -1; } ByteArrayOutputStream overhead = new ByteArrayOutputStream(); sendStart(overhead); sendDispositionHeader(overhead); sendContentTypeHeader(overhead); sendTransferEncodingHeader(overhead); sendEndOfHeader(overhead); sendEnd(overhead); return overhead.size() + lengthOfData(); } /** * Return a string representation of this object. * @return A string representation of this object. * @see java.lang.Object#toString() */ public String toString() { return this.getName(); } /** * Write all parts and the last boundary to the specified output stream. * * @param out The stream to write to. * @param parts The parts to write. * * @throws IOException If an I/O error occurs while writing the parts. */ public static void sendParts(OutputStream out, final Part[] parts) throws IOException { sendParts(out, parts, DEFAULT_BOUNDARY_BYTES); } /** * Write all parts and the last boundary to the specified output stream. * * @param out The stream to write to. * @param parts The parts to write. * @param partBoundary The ASCII bytes to use as the part boundary. * * @throws IOException If an I/O error occurs while writing the parts. * * @since 3.0 */ public static void sendParts(OutputStream out, Part[] parts, byte[] partBoundary) throws IOException { if (parts == null) { throw new IllegalArgumentException("Parts may not be null"); } if (partBoundary == null || partBoundary.length == 0) { throw new IllegalArgumentException("partBoundary may not be empty"); } for (int i = 0; i < parts.length; i++) { // set the part boundary before the part is sent parts[i].setPartBoundary(partBoundary); parts[i].send(out); } out.write(EXTRA_BYTES); out.write(partBoundary); out.write(EXTRA_BYTES); out.write(CRLF_BYTES); } /** * Return the total sum of all parts and that of the last boundary * * @param parts The parts. * @return The total length * * @throws IOException If an I/O error occurs while writing the parts. */ public static long getLengthOfParts(Part[] parts) throws IOException { return getLengthOfParts(parts, DEFAULT_BOUNDARY_BYTES); } /** * Gets the length of the multipart message including the given parts. * * @param parts The parts. * @param partBoundary The ASCII bytes to use as the part boundary. * @return The total length * * @throws IOException If an I/O error occurs while writing the parts. * * @since 3.0 */ public static long getLengthOfParts(Part[] parts, byte[] partBoundary) throws IOException { LOG.trace("getLengthOfParts(Parts[])"); if (parts == null) { throw new IllegalArgumentException("Parts may not be null"); } long total = 0; for (int i = 0; i < parts.length; i++) { // set the part boundary before we calculate the part's length parts[i].setPartBoundary(partBoundary); long l = parts[i].length(); if (l < 0) { return -1; } total += l; } total += EXTRA_BYTES.length; total += partBoundary.length; total += EXTRA_BYTES.length; total += CRLF_BYTES.length; return total; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/PartBase.java100644 0 0 10530 10661532626 27762 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/PartBase.java,v 1.5 2004/04/18 23:51:37 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods.multipart; /** * Provides setters and getters for the basic Part properties. * * @author Michael Becke */ public abstract class PartBase extends Part { /** Name of the file part. */ private String name; /** Content type of the file part. */ private String contentType; /** Content encoding of the file part. */ private String charSet; /** The transfer encoding. */ private String transferEncoding; /** * Constructor. * * @param name The name of the part * @param contentType The content type, or null * @param charSet The character encoding, or null * @param transferEncoding The transfer encoding, or null */ public PartBase(String name, String contentType, String charSet, String transferEncoding) { if (name == null) { throw new IllegalArgumentException("Name must not be null"); } this.name = name; this.contentType = contentType; this.charSet = charSet; this.transferEncoding = transferEncoding; } /** * Returns the name. * @return The name. * @see org.apache.commons.httpclient.methods.multipart.Part#getName() */ public String getName() { return this.name; } /** * Returns the content type of this part. * @return String The name. */ public String getContentType() { return this.contentType; } /** * Return the character encoding of this part. * @return String The name. */ public String getCharSet() { return this.charSet; } /** * Returns the transfer encoding of this part. * @return String The name. */ public String getTransferEncoding() { return transferEncoding; } /** * Sets the character encoding. * * @param charSet the character encoding, or null to exclude the character * encoding header */ public void setCharSet(String charSet) { this.charSet = charSet; } /** * Sets the content type. * * @param contentType the content type, or null to exclude the content type header */ public void setContentType(String contentType) { this.contentType = contentType; } /** * Sets the part name. * * @param name */ public void setName(String name) { if (name == null) { throw new IllegalArgumentException("Name must not be null"); } this.name = name; } /** * Sets the transfer encoding. * * @param transferEncoding the transfer encoding, or null to exclude the * transfer encoding header */ public void setTransferEncoding(String transferEncoding) { this.transferEncoding = transferEncoding; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/PartSource.java100644 0 0 4726 10661532626 30342 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/PartSource.java,v 1.6 2004/04/18 23:51:37 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods.multipart; import java.io.IOException; import java.io.InputStream; /** * An interface for providing access to data when posting MultiPart messages. * * @see FilePart * * @author Michael Becke * * @since 2.0 */ public interface PartSource { /** * Gets the number of bytes contained in this source. * * @return a value >= 0 */ long getLength(); /** * Gets the name of the file this source represents. * * @return the fileName used for posting a MultiPart file part */ String getFileName(); /** * Gets a new InputStream for reading this source. This method can be * called more than once and should therefore return a new stream every * time. * * @return a new InputStream * * @throws IOException if an error occurs when creating the InputStream */ InputStream createInputStream() throws IOException; } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/StringPart.java100644 0 0 12000 10661532626 30350 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/StringPart.java,v 1.11 2004/04/18 23:51:37 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.methods.multipart; import java.io.OutputStream; import java.io.IOException; import org.apache.commons.httpclient.util.EncodingUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Simple string parameter for a multipart post * * @author Matthew Albright * @author Jeff Dever * @author Mike Bowler * @author Oleg Kalnichevski * * @since 2.0 */ public class StringPart extends PartBase { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(StringPart.class); /** Default content encoding of string parameters. */ public static final String DEFAULT_CONTENT_TYPE = "text/plain"; /** Default charset of string parameters*/ public static final String DEFAULT_CHARSET = "US-ASCII"; /** Default transfer encoding of string parameters*/ public static final String DEFAULT_TRANSFER_ENCODING = "8bit"; /** Contents of this StringPart. */ private byte[] content; /** The String value of this part. */ private String value; /** * Constructor. * * @param name The name of the part * @param value the string to post * @param charset the charset to be used to encode the string, if null * the {@link #DEFAULT_CHARSET default} is used */ public StringPart(String name, String value, String charset) { super( name, DEFAULT_CONTENT_TYPE, charset == null ? DEFAULT_CHARSET : charset, DEFAULT_TRANSFER_ENCODING ); if (value == null) { throw new IllegalArgumentException("Value may not be null"); } if (value.indexOf(0) != -1) { // See RFC 2048, 2.8. "8bit Data" throw new IllegalArgumentException("NULs may not be present in string parts"); } this.value = value; } /** * Constructor. * * @param name The name of the part * @param value the string to post */ public StringPart(String name, String value) { this(name, value, null); } /** * Gets the content in bytes. Bytes are lazily created to allow the charset to be changed * after the part is created. * * @return the content in bytes */ private byte[] getContent() { if (content == null) { content = EncodingUtil.getBytes(value, getCharSet()); } return content; } /** * Writes the data to the given OutputStream. * @param out the OutputStream to write to * @throws IOException if there is a write error */ protected void sendData(OutputStream out) throws IOException { LOG.trace("enter sendData(OutputStream)"); out.write(getContent()); } /** * Return the length of the data. * @return The length of the data. * @throws IOException If an IO problem occurs * @see org.apache.commons.httpclient.methods.multipart.Part#lengthOfData() */ protected long lengthOfData() throws IOException { LOG.trace("enter lengthOfData()"); return getContent().length; } /* (non-Javadoc) * @see org.apache.commons.httpclient.methods.multipart.BasePart#setCharSet(java.lang.String) */ public void setCharSet(String charSet) { super.setCharSet(charSet); this.content = null; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/multipart/package.html100644 0 0 531 10661532626 27637 0ustar 0 0 Package Documentation for org.apache.commons.httpclient.methods.multipart Provides Multipart support classes for the {@link org.apache.commons.httpclient.methods.MultipartPostMethod}. @since 2.0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/methods/package.html100644 0 0 506 10661532626 25620 0ustar 0 0 Package Documentation for org.apache.commons.httpclient.methods Classes implementing {@link org.apache.commons.httpclient.HttpMethod} for the base HTTP methods. @since 1.0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/package.html100644 0 0 11702 10661532626 24215 0ustar 0 0 Package Documentation for org.apache.commons.httpclient

      Classes and interfaces supporting the client side of the HTTP protocol.

      The HttpClient component supports the client-side of RFC 1945 (HTTP/1.0) and RFC 2616 (HTTP/1.1), several related specifications (RFC 2109 (Cookies), RFC 2617 (HTTP Authentication), etc.), and provides a framework by which new request types (methods) or HTTP extensions can can be easily created or supported.

      The basis for the abstraction is provided by three types:

        {@link org.apache.commons.httpclient.HttpConnection}
        represents a network connection to some HTTP host.
        {@link org.apache.commons.httpclient.HttpMethod}
        represents a request to be made over some {@link org.apache.commons.httpclient.HttpConnection} and contains the server's response.
        {@link org.apache.commons.httpclient.HttpState}
        contains the HTTP attributes that may persist from request to request, such as cookies and authentication credentials.

      and several simple bean-style classes:

        {@link org.apache.commons.httpclient.Cookie}
        represents HTTP cookie.
        {@link org.apache.commons.httpclient.Credentials}
        an interface representing a set of authentication credentials.
        {@link org.apache.commons.httpclient.Header}
        represents an HTTP request or response header.
        {@link org.apache.commons.httpclient.HeaderElement}
        represents a single element of a multi-part header.
        {@link org.apache.commons.httpclient.UsernamePasswordCredentials}
        a username and password pair.

      {@link org.apache.commons.httpclient.HttpClient} provides a simple "user-agent" implementation that will suffice for many applications, but whose use is not required.

      HttpClient also provides several utilities that may be useful when extending the framework:

        {@link org.apache.commons.httpclient.HttpMethodBase}
        an abstract base implementation of HttpMethod, which may be extended to create new method types or to support additional protocol HTTP features.
        {@link org.apache.commons.httpclient.HttpStatus}
        an enumeration of HttpStatus codes.
        {@link org.apache.commons.httpclient.ChunkedOutputStream}
        an {@link java.io.OutputStream} wrapper supporting the "chunked" transfer encoding.
        {@link org.apache.commons.httpclient.ChunkedInputStream}
        an {@link java.io.InputStream} wrapper supporting the "chunked" transfer encoding.
        {@link org.apache.commons.httpclient.util.URIUtil}
        provides utilities for encoding and decoding URI's in the %HH format.

      HttpClient Configuration with Java Properties

      Java properties can be set at run time with the -Dname=value command line arguments to the application that uses HttpClient. These properties can also be set programaticly by calling System.getProperties().setProperty(name, value). This is the list of properties that HttpClient recognizes:
      Name Type Effect
      httpclient.useragent String Sets the User-Agent string to be sent on every HTTP request.
      httpclient.authentication.preemptive boolean Sends authorization credentials without requiring explicit requests from the web server
      commons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/DefaultHttpParams.java100644 0 0 20672 10661532627 27461 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/DefaultHttpParams.java,v 1.9 2004/12/21 23:15:21 olegk Exp $ * $Revision: 510589 $ * $Date: 2007-02-22 18:04:52 +0100 (Thu, 22 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.params; import java.io.Serializable; import java.util.HashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class represents a collection of HTTP protocol parameters. Protocol parameters * may be linked together to form a hierarchy. If a particular parameter value has not been * explicitly defined in the collection itself, its value will be drawn from the parent * collection of parameters. * * @author Oleg Kalnichevski * * @version $Revision: 510589 $ * * @since 3.0 */ public class DefaultHttpParams implements HttpParams, Serializable, Cloneable { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(DefaultHttpParams.class); /** HttpParams class factory. */ private static HttpParamsFactory httpParamsFactory = new DefaultHttpParamsFactory(); /** * Gets the default HttpParams to be used. * * @return the value returned from HttpParamsFactory#getDefaultParams() * * @see HttpParamsFactory#getDefaultParams() */ public static HttpParams getDefaultParams() { return httpParamsFactory.getDefaultParams(); } /** * Sets the factory that will provide the default HttpParams. * * @param httpParamsFactory an instance of HttpParamsFactory * * @see #getDefaultParams() */ public static void setHttpParamsFactory(HttpParamsFactory httpParamsFactory) { if (httpParamsFactory == null) { throw new IllegalArgumentException("httpParamsFactory may not be null"); } DefaultHttpParams.httpParamsFactory = httpParamsFactory; } /** The set of default values to defer to */ private HttpParams defaults = null; /** Hash map of HTTP parameters that this collection contains */ private HashMap parameters = null; /** * Creates a new collection of parameters with the given parent. * The collection will defer to its parent for a default value * if a particular parameter is not explicitly set in the collection * itself. * * @param defaults the parent collection to defer to, if a parameter * is not explictly set in the collection itself. */ public DefaultHttpParams(final HttpParams defaults) { super(); this.defaults = defaults; } /** * Creates a new collection of parameters with the collection returned * by {@link #getDefaultParams()} as a parent. The collection will defer * to its parent for a default value if a particular parameter is not * explicitly set in the collection itself. * * @see #getDefaultParams() */ public DefaultHttpParams() { this(getDefaultParams()); } public synchronized HttpParams getDefaults() { return this.defaults; } public synchronized void setDefaults(final HttpParams params) { this.defaults = params; } public synchronized Object getParameter(final String name) { // See if the parameter has been explicitly defined Object param = null; if (this.parameters != null) { param = this.parameters.get(name); } if (param != null) { // If so, return return param; } else { // If not, see if defaults are available if (this.defaults != null) { // Return default parameter value return this.defaults.getParameter(name); } else { // Otherwise, return null return null; } } } public synchronized void setParameter(final String name, final Object value) { if (this.parameters == null) { this.parameters = new HashMap(); } this.parameters.put(name, value); if (LOG.isDebugEnabled()) { LOG.debug("Set parameter " + name + " = " + value); } } /** * Assigns the value to all the parameter with the given names * * @param names array of parameter name * @param value parameter value */ public synchronized void setParameters(final String[] names, final Object value) { for (int i = 0; i < names.length; i++) { setParameter(names[i], value); } } public long getLongParameter(final String name, long defaultValue) { Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Long)param).longValue(); } public void setLongParameter(final String name, long value) { setParameter(name, new Long(value)); } public int getIntParameter(final String name, int defaultValue) { Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Integer)param).intValue(); } public void setIntParameter(final String name, int value) { setParameter(name, new Integer(value)); } public double getDoubleParameter(final String name, double defaultValue) { Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Double)param).doubleValue(); } public void setDoubleParameter(final String name, double value) { setParameter(name, new Double(value)); } public boolean getBooleanParameter(final String name, boolean defaultValue) { Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Boolean)param).booleanValue(); } public void setBooleanParameter(final String name, boolean value) { setParameter(name, value ? Boolean.TRUE : Boolean.FALSE);// Boolean.valueOf() = Java 1.4+ } public boolean isParameterSet(final String name) { return getParameter(name) != null; } public boolean isParameterSetLocally(final String name) { return this.parameters != null && this.parameters.get(name) != null; } public boolean isParameterTrue(final String name) { return getBooleanParameter(name, false); } public boolean isParameterFalse(final String name) { return !getBooleanParameter(name, false); } /** * Removes all parameters from this collection. */ public void clear() { this.parameters = null; } /** * Clones this collection of parameters. Please note that paramter values * themselves are not cloned. * * @see java.io.Serializable * @see java.lang.Object#clone() */ public Object clone() throws CloneNotSupportedException { DefaultHttpParams clone = (DefaultHttpParams)super.clone(); if (this.parameters != null) { clone.parameters = (HashMap)this.parameters.clone(); } clone.setDefaults(this.defaults); return clone; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.java100644 0 0 13310 10661532626 30777 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.java,v 1.16 2004/11/20 21:48:47 mbecke Exp $ * $Revision: 566065 $ * $Date: 2007-08-15 10:34:30 +0200 (Wed, 15 Aug 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.params; import java.util.ArrayList; import java.util.Arrays; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.SimpleHttpConnectionManager; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.util.DateUtil; /** * @since 3.0 */ public class DefaultHttpParamsFactory implements HttpParamsFactory { private HttpParams httpParams; /** * */ public DefaultHttpParamsFactory() { super(); } /* (non-Javadoc) * @see org.apache.commons.httpclient.params.HttpParamsFactory#getDefaultParams() */ public synchronized HttpParams getDefaultParams() { if (httpParams == null) { httpParams = createParams(); } return httpParams; } protected HttpParams createParams() { HttpClientParams params = new HttpClientParams(null); params.setParameter(HttpMethodParams.USER_AGENT, "Jakarta Commons-HttpClient/3.1"); params.setVersion(HttpVersion.HTTP_1_1); params.setConnectionManagerClass(SimpleHttpConnectionManager.class); params.setCookiePolicy(CookiePolicy.DEFAULT); params.setHttpElementCharset("US-ASCII"); params.setContentCharset("ISO-8859-1"); params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); ArrayList datePatterns = new ArrayList(); datePatterns.addAll( Arrays.asList( new String[] { DateUtil.PATTERN_RFC1123, DateUtil.PATTERN_RFC1036, DateUtil.PATTERN_ASCTIME, "EEE, dd-MMM-yyyy HH:mm:ss z", "EEE, dd-MMM-yyyy HH-mm-ss z", "EEE, dd MMM yy HH:mm:ss z", "EEE dd-MMM-yyyy HH:mm:ss z", "EEE dd MMM yyyy HH:mm:ss z", "EEE dd-MMM-yyyy HH-mm-ss z", "EEE dd-MMM-yy HH:mm:ss z", "EEE dd MMM yy HH:mm:ss z", "EEE,dd-MMM-yy HH:mm:ss z", "EEE,dd-MMM-yyyy HH:mm:ss z", "EEE, dd-MM-yyyy HH:mm:ss z", } ) ); params.setParameter(HttpMethodParams.DATE_PATTERNS, datePatterns); // TODO: To be removed. Provided for backward compatibility String agent = null; try { agent = System.getProperty("httpclient.useragent"); } catch (SecurityException ignore) { } if (agent != null) { params.setParameter(HttpMethodParams.USER_AGENT, agent); } // TODO: To be removed. Provided for backward compatibility String preemptiveDefault = null; try { preemptiveDefault = System.getProperty("httpclient.authentication.preemptive"); } catch (SecurityException ignore) { } if (preemptiveDefault != null) { preemptiveDefault = preemptiveDefault.trim().toLowerCase(); if (preemptiveDefault.equals("true")) { params.setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, Boolean.TRUE); } else if (preemptiveDefault.equals("false")) { params.setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, Boolean.FALSE); } } // TODO: To be removed. Provided for backward compatibility String defaultCookiePolicy = null; try { defaultCookiePolicy = System.getProperty("apache.commons.httpclient.cookiespec"); } catch (SecurityException ignore) { } if (defaultCookiePolicy != null) { if ("COMPATIBILITY".equalsIgnoreCase(defaultCookiePolicy)) { params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } else if ("NETSCAPE_DRAFT".equalsIgnoreCase(defaultCookiePolicy)) { params.setCookiePolicy(CookiePolicy.NETSCAPE); } else if ("RFC2109".equalsIgnoreCase(defaultCookiePolicy)) { params.setCookiePolicy(CookiePolicy.RFC_2109); } } return params; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/HostParams.java100644 0 0 7320 10661532626 26124 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HostParams.java,v 1.5 2004/10/06 17:32:04 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.params; /** * This class represents a collection of HTTP protocol parameters applicable to * {@link org.apache.commons.httpclient.HostConfiguration instances of HostConfiguration}. * Protocol parameters may be linked together to form a hierarchy. If a particular * parameter value has not been explicitly defined in the collection itself, its * value will be drawn from the parent collection of parameters. * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ * * @since 3.0 */ public class HostParams extends DefaultHttpParams { /** * Defines the request headers to be sent per default with each request. *

      * This parameter expects a value of type {@link java.util.Collection}. The * collection is expected to contain {@link org.apache.commons.httpclient.Header}s. *

      */ public static final String DEFAULT_HEADERS = "http.default-headers"; /** * Creates a new collection of parameters with the collection returned * by {@link #getDefaultParams()} as a parent. The collection will defer * to its parent for a default value if a particular parameter is not * explicitly set in the collection itself. * * @see #getDefaultParams() */ public HostParams() { super(); } /** * Creates a new collection of parameters with the given parent. * The collection will defer to its parent for a default value * if a particular parameter is not explicitly set in the collection * itself. * * @param defaults the parent collection to defer to, if a parameter * is not explictly set in the collection itself. * * @see #getDefaultParams() */ public HostParams(HttpParams defaults) { super(defaults); } /** * Sets the virtual host name. * * @param hostname The host name */ public void setVirtualHost(final String hostname) { setParameter(HttpMethodParams.VIRTUAL_HOST, hostname); } /** * Returns the virtual host name. * * @return The virtual host name */ public String getVirtualHost() { return (String) getParameter(HttpMethodParams.VIRTUAL_HOST); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/HttpClientParams.java100644 0 0 17306 10661532626 27312 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpClientParams.java,v 1.7 2004/05/13 04:01:22 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.params; /** * This class represents a collection of HTTP protocol parameters applicable to * {@link org.apache.commons.httpclient.HttpClient instances of HttpClient}. * Protocol parameters may be linked together to form a hierarchy. If a particular * parameter value has not been explicitly defined in the collection itself, its * value will be drawn from the parent collection of parameters. * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ * * @since 3.0 */ public class HttpClientParams extends HttpMethodParams { /** * Sets the timeout in milliseconds used when retrieving an * {@link org.apache.commons.httpclient.HttpConnection HTTP connection} from the * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}. *

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

      */ public static final String CONNECTION_MANAGER_TIMEOUT = "http.connection-manager.timeout"; /** * Defines the default * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager} * class. *

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

      */ public static final String CONNECTION_MANAGER_CLASS = "http.connection-manager.class"; /** * Defines whether authentication should be attempted preemptively. *

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

      */ public static final String PREEMPTIVE_AUTHENTICATION = "http.authentication.preemptive"; /** * Defines whether relative redirects should be rejected. *

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

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

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

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

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

      */ public static final String ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects"; /** * Creates a new collection of parameters with the collection returned * by {@link #getDefaultParams()} as a parent. The collection will defer * to its parent for a default value if a particular parameter is not * explicitly set in the collection itself. * * @see #getDefaultParams() */ public HttpClientParams() { super(); } /** * Creates a new collection of parameters with the given parent. * The collection will defer to its parent for a default value * if a particular parameter is not explicitly set in the collection * itself. * * @param defaults the parent collection to defer to, if a parameter * is not explictly set in the collection itself. * * @see #getDefaultParams() */ public HttpClientParams(HttpParams defaults) { super(defaults); } /** * Returns the timeout in milliseconds used when retrieving an * {@link org.apache.commons.httpclient.HttpConnection HTTP connection} from the * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}. * * @return timeout in milliseconds. */ public long getConnectionManagerTimeout() { return getLongParameter(CONNECTION_MANAGER_TIMEOUT, 0); } /** * Sets the timeout in milliseconds used when retrieving an * {@link org.apache.commons.httpclient.HttpConnection HTTP connection} from the * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}. * * @param timeout the timeout in milliseconds */ public void setConnectionManagerTimeout(long timeout) { setLongParameter(CONNECTION_MANAGER_TIMEOUT, timeout); } /** * Returns the default * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager} * class. * @return {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager} * factory class. */ public Class getConnectionManagerClass() { return (Class) getParameter(CONNECTION_MANAGER_CLASS); } /** * Sets {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager} * class to be used der default. * @param clazz * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager} * factory class. */ public void setConnectionManagerClass(Class clazz) { setParameter(CONNECTION_MANAGER_CLASS, clazz); } /** * Returns true if authentication should be attempted preemptively, * false otherwise. * * @return true if authentication should be attempted preemptively, * false otherwise. */ public boolean isAuthenticationPreemptive() { return getBooleanParameter(PREEMPTIVE_AUTHENTICATION, false); } /** * Sets whether authentication should be attempted preemptively. * * @param value true if authentication should be attempted preemptively, * false otherwise. */ public void setAuthenticationPreemptive(boolean value) { setBooleanParameter(PREEMPTIVE_AUTHENTICATION, value); } private static final String[] PROTOCOL_STRICTNESS_PARAMETERS = { REJECT_RELATIVE_REDIRECT, ALLOW_CIRCULAR_REDIRECTS }; public void makeStrict() { super.makeStrict(); setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.TRUE); } public void makeLenient() { super.makeLenient(); setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.FALSE); } } ././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/HttpConnectionManagerParams.javacommons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/HttpConnectionManagerParams.jav100644 0 0 16522 10661532626 31324 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpConnectionManagerParams.java,v 1.9 2004/09/13 16:25:20 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.params; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; /** * This class represents a collection of HTTP protocol parameters applicable to * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection managers}. * Protocol parameters may be linked together to form a hierarchy. If a particular * parameter value has not been explicitly defined in the collection itself, its * value will be drawn from the parent collection of parameters. * * @author Oleg Kalnichevski * @author Michael Becke * * @version $Revision: 480424 $ * * @since 3.0 */ public class HttpConnectionManagerParams extends HttpConnectionParams { /** * Defines the maximum number of connections allowed per host configuration. * These values only apply to the number of connections from a particular instance * of HttpConnectionManager. *

      * This parameter expects a value of type {@link java.util.Map}. The value * should map instances of {@link org.apache.commons.httpclient.HostConfiguration} * to {@link Integer integers}. The default value can be specified using * {@link org.apache.commons.httpclient.HostConfiguration#ANY_HOST_CONFIGURATION}. *

      */ public static final String MAX_HOST_CONNECTIONS = "http.connection-manager.max-per-host"; /** * Defines the maximum number of connections allowed overall. This value only applies * to the number of connections from a particular instance of HttpConnectionManager. *

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

      */ public static final String MAX_TOTAL_CONNECTIONS = "http.connection-manager.max-total"; /** * Sets the default maximum number of connections allowed for a given * host config. * * @param maxHostConnections The default maximum. * * @see #MAX_HOST_CONNECTIONS */ public void setDefaultMaxConnectionsPerHost(int maxHostConnections) { setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, maxHostConnections); } /** * Sets the maximum number of connections to be used for the given host config. * * @param hostConfiguration The host config to set the maximum for. Use * {@link HostConfiguration#ANY_HOST_CONFIGURATION} to configure the default value * per host. * @param maxHostConnections The maximum number of connections, > 0 * * @see #MAX_HOST_CONNECTIONS */ public void setMaxConnectionsPerHost( HostConfiguration hostConfiguration, int maxHostConnections) { if (maxHostConnections <= 0) { throw new IllegalArgumentException("maxHostConnections must be greater than 0"); } Map currentValues = (Map) getParameter(MAX_HOST_CONNECTIONS); // param values are meant to be immutable so we'll make a copy // to modify Map newValues = null; if (currentValues == null) { newValues = new HashMap(); } else { newValues = new HashMap(currentValues); } newValues.put(hostConfiguration, new Integer(maxHostConnections)); setParameter(MAX_HOST_CONNECTIONS, newValues); } /** * Gets the default maximum number of connections allowed for a given * host config. * * @return The default maximum. * * @see #MAX_HOST_CONNECTIONS */ public int getDefaultMaxConnectionsPerHost() { return getMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION); } /** * Gets the maximum number of connections to be used for a particular host config. If * the value has not been specified for the given host the default value will be * returned. * * @param hostConfiguration The host config. * @return The maximum number of connections to be used for the given host config. * * @see #MAX_HOST_CONNECTIONS */ public int getMaxConnectionsPerHost(HostConfiguration hostConfiguration) { Map m = (Map) getParameter(MAX_HOST_CONNECTIONS); if (m == null) { // MAX_HOST_CONNECTIONS have not been configured, using the default value return MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS; } else { Integer max = (Integer) m.get(hostConfiguration); if (max == null && hostConfiguration != HostConfiguration.ANY_HOST_CONFIGURATION) { // the value has not been configured specifically for this host config, // use the default value return getMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION); } else { return ( max == null ? MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS : max.intValue() ); } } } /** * Sets the maximum number of connections allowed. * * @param maxTotalConnections The maximum number of connections allowed. * * @see #MAX_TOTAL_CONNECTIONS */ public void setMaxTotalConnections(int maxTotalConnections) { setIntParameter( HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, maxTotalConnections); } /** * Gets the maximum number of connections allowed. * * @return The maximum number of connections allowed. * * @see #MAX_TOTAL_CONNECTIONS */ public int getMaxTotalConnections() { return getIntParameter( HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, MultiThreadedHttpConnectionManager.DEFAULT_MAX_TOTAL_CONNECTIONS); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/HttpConnectionParams.java100644 0 0 27767 10661532626 30207 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpConnectionParams.java,v 1.6 2004/09/15 20:32:21 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.params; /** * This class represents a collection of HTTP protocol parameters applicable to * {@link org.apache.commons.httpclient.HttpConnection HTTP connections}. * Protocol parameters may be linked together to form a hierarchy. If a particular * parameter value has not been explicitly defined in the collection itself, its * value will be drawn from the parent collection of parameters. * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ * * @since 3.0 */ public class HttpConnectionParams extends DefaultHttpParams { /** * Defines the default socket timeout (SO_TIMEOUT) in milliseconds which is the * timeout for waiting for data. A timeout value of zero is interpreted as an infinite * timeout. This value is used when no socket timeout is set in the * {@link HttpMethodParams HTTP method parameters}. *

      * 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 a hint the size of the underlying buffers used by the platform * for outgoing network I/O. This value is a suggestion to the kernel from * the application about the size of buffers to use for the data to be sent * over the socket. *

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

      * @see java.net.SocketOptions#SO_SNDBUF */ public static final String SO_SNDBUF = "http.socket.sendbuffer"; /** * Determines a hint the size of the underlying buffers used by the platform * for incoming network I/O. This value is a suggestion to the kernel from * the application about the size of buffers to use for the data to be received * over the socket. *

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

      * @see java.net.SocketOptions#SO_RCVBUF */ public static final String SO_RCVBUF = "http.socket.receivebuffer"; /** * Sets SO_LINGER with the specified linger time in seconds. The maximum timeout * value is platform specific. Value 0 implies that the option is disabled. * Value -1 implies that the JRE default is used. The setting only affects * socket close. *

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

      * @see java.net.SocketOptions#SO_LINGER */ public static final String SO_LINGER = "http.socket.linger"; /** * Determines the timeout until a connection is etablished. A value of zero * means the timeout is not used. The default value is zero. *

      * 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. Disabling * stale connection check may result in slight performance improvement * at the risk of getting an I/O error when executing a request over a * connection that has been closed at the server side. *

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

      */ public static final String STALE_CONNECTION_CHECK = "http.connection.stalecheck"; /** * Creates a new collection of parameters with the collection returned * by {@link #getDefaultParams()} as a parent. The collection will defer * to its parent for a default value if a particular parameter is not * explicitly set in the collection itself. * * @see #getDefaultParams() */ public HttpConnectionParams() { super(); } /** * Returns the default socket timeout (SO_TIMEOUT) in milliseconds which is the * timeout for waiting for data. A timeout value of zero is interpreted as an infinite * timeout. This value is used when no socket timeout is set in the * {@link HttpMethodParams HTTP method parameters}. * * @return timeout in milliseconds */ public int getSoTimeout() { return getIntParameter(SO_TIMEOUT, 0); } /** * Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the * timeout for waiting for data. A timeout value of zero is interpreted as an infinite * timeout. This value is used when no socket timeout is set in the * {@link HttpMethodParams HTTP method parameters}. * * @param timeout Timeout in milliseconds */ public void setSoTimeout(int timeout) { setIntParameter(SO_TIMEOUT, 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. * * @param value true if the Nagle's algorithm is to NOT be used * (that is enable TCP_NODELAY), false otherwise. */ public void setTcpNoDelay(boolean value) { setBooleanParameter(TCP_NODELAY, value); } /** * Tests if Nagle's algorithm is to be used. * * @return true if the Nagle's algorithm is to NOT be used * (that is enable TCP_NODELAY), false otherwise. */ public boolean getTcpNoDelay() { return getBooleanParameter(TCP_NODELAY, true); } /** * Returns a hint the size of the underlying buffers used by the platform for * outgoing network I/O. This value is a suggestion to the kernel from the * application about the size of buffers to use for the data to be sent over * the socket. * * @return the hint size of the send buffer */ public int getSendBufferSize() { return getIntParameter(SO_SNDBUF, -1); } /** * Sets a hint the size of the underlying buffers used by the platform for * outgoing network I/O. This value is a suggestion to the kernel from the * application about the size of buffers to use for the data to be sent over * the socket. * * @param size the hint size of the send buffer */ public void setSendBufferSize(int size) { setIntParameter(SO_SNDBUF, size); } /** * Returns a hint the size of the underlying buffers used by the platform * for incoming network I/O. This value is a suggestion to the kernel from * the application about the size of buffers to use for the data to be received * over the socket. * * @return the hint size of the send buffer */ public int getReceiveBufferSize() { return getIntParameter(SO_RCVBUF, -1); } /** * Sets a hint the size of the underlying buffers used by the platform * for incoming network I/O. This value is a suggestion to the kernel from * the application about the size of buffers to use for the data to be received * over the socket. * * @param size the hint size of the send buffer */ public void setReceiveBufferSize(int size) { setIntParameter(SO_RCVBUF, size); } /** * Returns linger-on-close timeout. Value 0 implies that the option is * disabled. Value -1 implies that the JRE default is used. * * @return the linger-on-close timeout */ public int getLinger() { return getIntParameter(SO_LINGER, -1); } /** * Returns linger-on-close timeout. This option disables/enables immediate return * from a close() of a TCP Socket. Enabling this option with a non-zero Integer * timeout means that a close() will block pending the transmission and * acknowledgement of all data written to the peer, at which point the socket is * closed gracefully. Value 0 implies that the option is * disabled. Value -1 implies that the JRE default is used. * * @param value the linger-on-close timeout */ public void setLinger(int value) { setIntParameter(SO_LINGER, value); } /** * Returns the timeout until a connection is etablished. A value of zero * means the timeout is not used. The default value is zero. * * @return timeout in milliseconds. */ public int getConnectionTimeout() { return getIntParameter(CONNECTION_TIMEOUT, 0); } /** * Sets the timeout until a connection is etablished. A value of zero * means the timeout is not used. The default value is zero. * * @param timeout Timeout in milliseconds. */ public void setConnectionTimeout(int timeout) { setIntParameter(CONNECTION_TIMEOUT, timeout); } /** * Tests whether stale connection check is to be used. Disabling * stale connection check may result in slight performance improvement * at the risk of getting an I/O error when executing a request over a * connection that has been closed at the server side. * * @return true if stale connection check is to be used, * false otherwise. */ public boolean isStaleCheckingEnabled() { return getBooleanParameter(STALE_CONNECTION_CHECK, true); } /** * Defines whether stale connection check is to be used. Disabling * stale connection check may result in slight performance improvement * at the risk of getting an I/O error when executing a request over a * connection that has been closed at the server side. * * @param value true if stale connection check is to be used, * false otherwise. */ public void setStaleCheckingEnabled(boolean value) { setBooleanParameter(STALE_CONNECTION_CHECK, value); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/HttpMethodParams.java100644 0 0 45006 10661532627 27313 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpMethodParams.java,v 1.17 2004/10/06 17:32:04 olegk Exp $ * $Revision: 483949 $ * $Date: 2006-12-08 12:34:50 +0100 (Fri, 08 Dec 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.params; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class represents a collection of HTTP protocol parameters applicable to * {@link org.apache.commons.httpclient.HttpMethod HTTP methods}. Protocol * parameters may be linked together to form a hierarchy. If a particular * parameter value has not been explicitly defined in the collection itself, * its value will be drawn from the parent collection of parameters. * * @author Oleg Kalnichevski * @author Christian Kohlschuetter * * @version $Revision: 483949 $ * * @since 3.0 */ public class HttpMethodParams extends DefaultHttpParams { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HttpMethodParams.class); /** * Defines the content of the User-Agent header used by * {@link org.apache.commons.httpclient.HttpMethod HTTP methods}. *

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

      */ public static final String USER_AGENT = "http.useragent"; /** * Defines the {@link HttpVersion HTTP protocol version} used by * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} per * default. *

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

      */ public static final String PROTOCOL_VERSION = "http.protocol.version"; /** * Defines whether {@link org.apache.commons.httpclient.HttpMethod HTTP methods} should * reject ambiguous {@link org.apache.commons.httpclient.StatusLine HTTP status line}. *

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

      */ public static final String UNAMBIGUOUS_STATUS_LINE = "http.protocol.unambiguous-statusline"; /** * Defines whether {@link org.apache.commons.httpclient.Cookie cookies} should be put on * a single {@link org.apache.commons.httpclient.Header response header}. *

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

      */ public static final String SINGLE_COOKIE_HEADER = "http.protocol.single-cookie-header"; /** * Defines whether responses with an invalid Transfer-Encoding header should be * rejected. *

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

      */ public static final String STRICT_TRANSFER_ENCODING = "http.protocol.strict-transfer-encoding"; /** * Defines whether the content body sent in response to * {@link org.apache.commons.httpclient.methods.HeadMethod} should be rejected. *

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

      */ public static final String REJECT_HEAD_BODY = "http.protocol.reject-head-body"; /** * Sets period of time in milliseconds to wait for a content body sent in response to * {@link org.apache.commons.httpclient.methods.HeadMethod HEAD method} from a * non-compliant server. If the parameter is not set or set to -1 non-compliant * response body check is disabled. *

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

      */ public static final String HEAD_BODY_CHECK_TIMEOUT = "http.protocol.head-body-timeout"; /** *

      * Activates 'Expect: 100-Continue' handshake for the * {@link org.apache.commons.httpclient.methods.ExpectContinueMethod * entity enclosing methods}. The purpose of the 'Expect: 100-Continue' * handshake 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 * noticable peformance 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 charset to be used when encoding * {@link org.apache.commons.httpclient.Credentials}. If not defined then the * {@link #HTTP_ELEMENT_CHARSET} should be used. *

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

      */ public static final String CREDENTIAL_CHARSET = "http.protocol.credential-charset"; /** * 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 for parsing URIs. *

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

      */ public static final String HTTP_URI_CHARSET = "http.protocol.uri-charset"; /** * Defines the charset to be used 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 {@link CookiePolicy cookie policy} to be used for cookie management. *

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

      */ public static final String COOKIE_POLICY = "http.protocol.cookie-policy"; /** * Defines HttpClient's behavior when a response provides more bytes than * expected (specified with Content-Length, for example). *

      * Such surplus data makes the HTTP connection unreliable for keep-alive * requests, as malicious response data (faked headers etc.) can lead to undesired * results on the next request using that connection. *

      *

      * If this parameter is set to true, any detection of extra * input data will generate a warning in the log. *

      *

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

      */ public static final String WARN_EXTRA_INPUT = "http.protocol.warn-extra-input"; /** * Defines the maximum number of ignorable lines before we expect * a HTTP response's status code. *

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

      *

      * Set this to 0 to disallow any garbage/empty lines before the status line.
      * To specify no limit, use {@link java.lang.Integer#MAX_VALUE} (default in lenient mode). *

      * * This parameter expects a value of type {@link Integer}. */ public static final String STATUS_LINE_GARBAGE_LIMIT = "http.protocol.status-line-garbage-limit"; /** * Sets the socket timeout (SO_TIMEOUT) in milliseconds to be used when executing the method. * 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"; /** * The key used to look up the date patterns used for parsing. The String patterns are stored * in a {@link java.util.Collection} and must be compatible with * {@link java.text.SimpleDateFormat}. *

      * This parameter expects a value of type {@link java.util.Collection}. *

      */ public static final String DATE_PATTERNS = "http.dateparser.patterns"; /** * Sets the method retry handler parameter. *

      * This parameter expects a value of type {@link org.apache.commons.httpclient.HttpMethodRetryHandler}. *

      */ public static final String RETRY_HANDLER = "http.method.retry-handler"; /** * Sets the maximum buffered response size (in bytes) that triggers no warning. Buffered * responses exceeding this size will trigger a warning in the log. *

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

      */ public static final String BUFFER_WARN_TRIGGER_LIMIT = "http.method.response.buffer.warnlimit"; /** * Defines the virtual host name. *

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

      */ public static final String VIRTUAL_HOST = "http.virtual-host"; /** * Sets the value to use as the multipart boundary. *

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

      * @see org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity */ public static final String MULTIPART_BOUNDARY = "http.method.multipart.boundary"; /** * Creates a new collection of parameters with the collection returned * by {@link #getDefaultParams()} as a parent. The collection will defer * to its parent for a default value if a particular parameter is not * explicitly set in the collection itself. * * @see #getDefaultParams() */ public HttpMethodParams() { super(getDefaultParams()); } /** * Creates a new collection of parameters with the given parent. * The collection will defer to its parent for a default value * if a particular parameter is not explicitly set in the collection * itself. * * @param defaults the parent collection to defer to, if a parameter * is not explictly set in the collection itself. * * @see #getDefaultParams() */ public HttpMethodParams(HttpParams defaults) { super(defaults); } /** * Returns the charset to be used for writing HTTP headers. * @return The charset */ public String getHttpElementCharset() { String charset = (String) getParameter(HTTP_ELEMENT_CHARSET); if (charset == null) { LOG.warn("HTTP element charset not configured, using US-ASCII"); charset = "US-ASCII"; } return charset; } /** * Sets the charset to be used for writing HTTP headers. * @param charset The charset */ public void setHttpElementCharset(String charset) { setParameter(HTTP_ELEMENT_CHARSET, charset); } /** * Returns the default charset to be used for writing content body, * when no charset explicitly specified. * @return The charset */ public String getContentCharset() { String charset = (String) getParameter(HTTP_CONTENT_CHARSET); if (charset == null) { LOG.warn("Default content charset not configured, using ISO-8859-1"); charset = "ISO-8859-1"; } return charset; } /** * Sets the charset to be used for parsing URIs. * @param charset The charset */ public void setUriCharset(String charset) { setParameter(HTTP_URI_CHARSET, charset); } /** * Returns the charset to be used for parsing URIs. * @return The charset */ public String getUriCharset() { String charset = (String) getParameter(HTTP_URI_CHARSET); if (charset == null) { charset = "UTF-8"; } return charset; } /** * Sets the default charset to be used for writing content body, * when no charset explicitly specified. * @param charset The charset */ public void setContentCharset(String charset) { setParameter(HTTP_CONTENT_CHARSET, charset); } /** * Returns the charset to be used for {@link org.apache.commons.httpclient.Credentials}. If * not configured the {@link #HTTP_ELEMENT_CHARSET HTTP element charset} is used. * @return The charset */ public String getCredentialCharset() { String charset = (String) getParameter(CREDENTIAL_CHARSET); if (charset == null) { LOG.debug("Credential charset not configured, using HTTP element charset"); charset = getHttpElementCharset(); } return charset; } /** * Sets the charset to be used for writing HTTP headers. * @param charset The charset */ public void setCredentialCharset(String charset) { setParameter(CREDENTIAL_CHARSET, charset); } /** * Returns {@link HttpVersion HTTP protocol version} to be used by the * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} that * this collection of parameters applies to. * * @return {@link HttpVersion HTTP protocol version} */ public HttpVersion getVersion() { Object param = getParameter(PROTOCOL_VERSION); if (param == null) { return HttpVersion.HTTP_1_1; } return (HttpVersion)param; } /** * Assigns the {@link HttpVersion HTTP protocol version} to be used by the * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} that * this collection of parameters applies to. * * @param version the {@link HttpVersion HTTP protocol version} */ public void setVersion(HttpVersion version) { setParameter(PROTOCOL_VERSION, version); } /** * Returns {@link CookiePolicy cookie policy} to be used by the * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} * this collection of parameters applies to. * * @return {@link CookiePolicy cookie policy} */ public String getCookiePolicy() { Object param = getParameter(COOKIE_POLICY); if (param == null) { return CookiePolicy.DEFAULT; } return (String)param; } /** * Assigns the {@link CookiePolicy cookie policy} to be used by the * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} * this collection of parameters applies to. * * @param policy the {@link CookiePolicy cookie policy} */ public void setCookiePolicy(String policy) { setParameter(COOKIE_POLICY, policy); } /** * Returns the default socket timeout (SO_TIMEOUT) in milliseconds which is the * timeout for waiting for data. A timeout value of zero is interpreted as an infinite * timeout. * * @return timeout in milliseconds */ public int getSoTimeout() { return getIntParameter(SO_TIMEOUT, 0); } /** * Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the * timeout for waiting for data. A timeout value of zero is interpreted as an infinite * timeout. * * @param timeout Timeout in milliseconds */ public void setSoTimeout(int timeout) { setIntParameter(SO_TIMEOUT, timeout); } /** * Sets the virtual host name. * * @param hostname The host name */ public void setVirtualHost(final String hostname) { setParameter(VIRTUAL_HOST, hostname); } /** * Returns the virtual host name. * * @return The virtual host name */ public String getVirtualHost() { return (String) getParameter(VIRTUAL_HOST); } private static final String[] PROTOCOL_STRICTNESS_PARAMETERS = { UNAMBIGUOUS_STATUS_LINE, SINGLE_COOKIE_HEADER, STRICT_TRANSFER_ENCODING, REJECT_HEAD_BODY, WARN_EXTRA_INPUT }; /** * Makes the {@link org.apache.commons.httpclient.HttpMethod HTTP methods} * strictly follow the HTTP protocol specification (RFC 2616 and other relevant RFCs). * It must be noted that popular HTTP agents have different degree of HTTP protocol * compliance and some HTTP serves are programmed to expect the behaviour that does not * strictly adhere to the HTTP specification. */ public void makeStrict() { setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.TRUE); setIntParameter(STATUS_LINE_GARBAGE_LIMIT, 0); } /** * Makes the {@link org.apache.commons.httpclient.HttpMethod HTTP methods} * attempt to mimic the exact behaviour of commonly used HTTP agents, * which many HTTP servers expect, even though such behaviour may violate * the HTTP protocol specification (RFC 2616 and other relevant RFCs). */ public void makeLenient() { setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.FALSE); setIntParameter(STATUS_LINE_GARBAGE_LIMIT, Integer.MAX_VALUE); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/HttpParams.java100644 0 0 20702 10661532627 26146 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpParams.java,v 1.6 2004/05/13 04:01:22 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.params; /** * This interface represents a collection of HTTP protocol parameters. Protocol parameters * may be linked together to form a hierarchy. If a particular parameter value has not been * explicitly defined in the collection itself, its value will be drawn from the parent * collection of parameters. * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ * * @since 3.0 */ public interface HttpParams { /** * Returns the parent collection that this collection will defer to * for a default value if a particular parameter is not explicitly * set in the collection itself * * @return the parent collection to defer to, if a particular parameter * is not explictly set in the collection itself. * * @see #setDefaults(HttpParams) */ public HttpParams getDefaults(); /** * Assigns the parent collection that this collection will defer to * for a default value if a particular parameter is not explicitly * set in the collection itself * * @param params the parent collection to defer to, if a particular * parameter is not explictly set in the collection itself. * * @see #getDefaults() */ public void setDefaults(final HttpParams params); /** * Returns a parameter value with the given name. If the parameter is * not explicitly defined in this collection, its value will be drawn * from a higer level collection at which this parameter is defined. * If the parameter is not explicitly set anywhere up the hierarchy, * null value is returned. * * @param name the parent name. * * @return an object that represents the value of the parameter. * * @see #setParameter(String, Object) */ public Object getParameter(final String name); /** * Assigns the value to the parameter with the given name * * @param name parameter name * @param value parameter value */ public void setParameter(final String name, final Object value); /** * Returns a {@link Long} parameter value with the given name. * If the parameter is not explicitly defined in this collection, its * value will be drawn from a higer level collection at which this parameter * is defined. If the parameter is not explicitly set anywhere up the hierarchy, * 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) */ public long getLongParameter(final String name, long defaultValue); /** * Assigns a {@link Long} to the parameter with the given name * * @param name parameter name * @param value parameter value */ public void setLongParameter(final String name, long value); /** * Returns an {@link Integer} parameter value with the given name. * If the parameter is not explicitly defined in this collection, its * value will be drawn from a higer level collection at which this parameter * is defined. If the parameter is not explicitly set anywhere up the hierarchy, * 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) */ public int getIntParameter(final String name, int defaultValue); /** * Assigns an {@link Integer} to the parameter with the given name * * @param name parameter name * @param value parameter value */ public void setIntParameter(final String name, int value); /** * Returns a {@link Double} parameter value with the given name. * If the parameter is not explicitly defined in this collection, its * value will be drawn from a higer level collection at which this parameter * is defined. If the parameter is not explicitly set anywhere up the hierarchy, * 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) */ public double getDoubleParameter(final String name, double defaultValue); /** * Assigns a {@link Double} to the parameter with the given name * * @param name parameter name * @param value parameter value */ public void setDoubleParameter(final String name, double value); /** * Returns a {@link Boolean} parameter value with the given name. * If the parameter is not explicitly defined in this collection, its * value will be drawn from a higer level collection at which this parameter * is defined. If the parameter is not explicitly set anywhere up the hierarchy, * 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) */ public boolean getBooleanParameter(final String name, boolean defaultValue); /** * Assigns a {@link Boolean} to the parameter with the given name * * @param name parameter name * @param value parameter value */ public void setBooleanParameter(final String name, boolean value); /** * Returns true if the parameter is set at any level, false otherwise. * * @param name parameter name * * @return true if the parameter is set at any level, false * otherwise. */ public boolean isParameterSet(final String name); /** * Returns true if the parameter is set locally, false otherwise. * * @param name parameter name * * @return true if the parameter is set locally, false * otherwise. */ public boolean isParameterSetLocally(final String name); /** * Returns true if the parameter is set and is true, false * otherwise. * * @param name parameter name * * @return true if the parameter is set and is true, false * otherwise. */ public boolean isParameterTrue(final String name); /** * Returns true if the parameter is either not set or is false, * false otherwise. * * @param name parameter name * * @return true if the parameter is either not set or is false, * false otherwise. */ public boolean isParameterFalse(final String name); } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/HttpParamsFactory.java100644 0 0 4020 10661532626 27450 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpParamsFactory.java,v 1.5 2004/05/13 04:01:22 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.params; /** * A factory for getting the default set of parameters to use when creating an instance of * HttpParams. * * @see org.apache.commons.httpclient.params.DefaultHttpParams#setHttpParamsFactory(HttpParamsFactory) * * @since 3.0 */ public interface HttpParamsFactory { /** * Gets the default parameters. This method may be called more than once and is not required * to always return the same value. * * @return an instance of HttpParams */ HttpParams getDefaultParams(); } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/params/package.html100644 0 0 406 10661532626 25437 0ustar 0 0 Package Documentation for org.apache.commons.httpclient.params HttpClient preferences framework. @since 3.0 ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactory.javacommons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactory100644 0 0 14026 10661532626 31476 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactory.java,v 1.2 2004/04/18 23:51:38 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.protocol; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.util.TimeoutController; /** * This helper class is intedned to help work around the limitation of older Java versions * (older than 1.4) that prevents from specifying a connection timeout when creating a * socket. This factory executes a controller thread overssing the process of socket * initialisation. If the socket constructor cannot be created within the specified time * limit, the controller terminates and throws an {@link ConnectTimeoutException} * * @author Ortwin Glueck * @author Oleg Kalnichevski * * @since 3.0 */ public final class ControllerThreadSocketFactory { private ControllerThreadSocketFactory() { super(); } /** * This method spawns a controller thread overseeing the process of socket * initialisation. If the socket constructor cannot be created within the specified time * limit, the controller terminates and throws an {@link ConnectTimeoutException} * * @param host the host name/IP * @param port the port on the host * @param localAddress the local host name/IP to bind the socket to * @param localPort the port on the local machine * @param timeout the timeout value to be used in milliseconds. If the socket cannot be * completed within the given time limit, it will be abandoned * * @return a connected Socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined * @throws ConnectTimeoutException if socket cannot be connected within the * given time limit * */ public static Socket createSocket( final ProtocolSocketFactory socketfactory, final String host, final int port, final InetAddress localAddress, final int localPort, int timeout) throws IOException, UnknownHostException, ConnectTimeoutException { SocketTask task = new SocketTask() { public void doit() throws IOException { setSocket(socketfactory.createSocket(host, port, localAddress, localPort)); } }; try { TimeoutController.execute(task, timeout); } catch (TimeoutController.TimeoutException e) { throw new ConnectTimeoutException( "The host did not accept the connection within timeout of " + timeout + " ms"); } Socket socket = task.getSocket(); if (task.exception != null) { throw task.exception; } return socket; } public static Socket createSocket(final SocketTask task, int timeout) throws IOException, UnknownHostException, ConnectTimeoutException { try { TimeoutController.execute(task, timeout); } catch (TimeoutController.TimeoutException e) { throw new ConnectTimeoutException( "The host did not accept the connection within timeout of " + timeout + " ms"); } Socket socket = task.getSocket(); if (task.exception != null) { throw task.exception; } return socket; } /** * Helper class for wrapping socket based tasks. */ public static abstract class SocketTask implements Runnable { /** The socket */ private Socket socket; /** The exception */ private IOException exception; /** * Set the socket. * @param newSocket The new socket. */ protected void setSocket(final Socket newSocket) { socket = newSocket; } /** * Return the socket. * @return Socket The socket. */ protected Socket getSocket() { return socket; } /** * Perform the logic. * @throws IOException If an IO problem occurs */ public abstract void doit() throws IOException; /** Execute the logic in this object and keep track of any exceptions. */ public void run() { try { doit(); } catch (IOException e) { exception = e; } } } } ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFactory.javacommons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFactory.100644 0 0 13372 10661532626 31412 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFactory.java,v 1.10 2004/05/13 04:01:22 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.protocol; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.params.HttpConnectionParams; /** * The default class for creating protocol sockets. This class just uses the * {@link java.net.Socket socket} constructors. * * @author Michael Becke * * @since 2.0 */ public class DefaultProtocolSocketFactory implements ProtocolSocketFactory { /** * The factory singleton. */ private static final DefaultProtocolSocketFactory factory = new DefaultProtocolSocketFactory(); /** * Gets an singleton instance of the DefaultProtocolSocketFactory. * @return a DefaultProtocolSocketFactory */ static DefaultProtocolSocketFactory getSocketFactory() { return factory; } /** * Constructor for DefaultProtocolSocketFactory. */ public DefaultProtocolSocketFactory() { super(); } /** * @see #createSocket(java.lang.String,int,java.net.InetAddress,int) */ public Socket createSocket( String host, int port, InetAddress localAddress, int localPort ) throws IOException, UnknownHostException { return new Socket(host, port, localAddress, localPort); } /** * Attempts to get a new socket connection to the given host within the given time limit. *

      * This method employs several techniques to circumvent the limitations of older JREs that * do not support connect timeout. When running in JRE 1.4 or above reflection is used to * call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older * JREs a controller thread is executed. The controller thread attempts to create a new socket * within the given limit of time. If socket constructor does not return until the timeout * expires, the controller terminates and throws an {@link ConnectTimeoutException} *

      * * @param host the host name/IP * @param port the port on the host * @param localAddress the local host name/IP to bind the socket to * @param localPort the port on the local machine * @param params {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined * @throws ConnectTimeoutException if socket cannot be connected within the * given time limit * * @since 3.0 */ public Socket createSocket( final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params ) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); if (timeout == 0) { return createSocket(host, port, localAddress, localPort); } else { // To be eventually deprecated when migrated to Java 1.4 or above Socket socket = ReflectionSocketFactory.createSocket( "javax.net.SocketFactory", host, port, localAddress, localPort, timeout); if (socket == null) { socket = ControllerThreadSocketFactory.createSocket( this, host, port, localAddress, localPort, timeout); } return socket; } } /** * @see ProtocolSocketFactory#createSocket(java.lang.String,int) */ public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return new Socket(host, port); } /** * All instances of DefaultProtocolSocketFactory are the same. */ public boolean equals(Object obj) { return ((obj != null) && obj.getClass().equals(getClass())); } /** * All instances of DefaultProtocolSocketFactory have the same hash code. */ public int hashCode() { return getClass().hashCode(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/Protocol.java100644 0 0 22241 10661532626 26241 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/Protocol.java,v 1.10 2004/04/18 23:51:38 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.protocol; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.util.LangUtils; /** * A class to encapsulate the specifics of a protocol. This class class also * provides the ability to customize the set and characteristics of the * protocols used. * *

      One use case for modifying the default set of protocols would be to set a * custom SSL socket factory. This would look something like the following: *

       
       * Protocol myHTTPS = new Protocol( "https", new MySSLSocketFactory(), 443 );
       * 
       * Protocol.registerProtocol( "https", myHTTPS );
       * 
      * * @author Michael Becke * @author Jeff Dever * @author Mike Bowler * * @since 2.0 */ public class Protocol { /** The available protocols */ private static final Map PROTOCOLS = Collections.synchronizedMap(new HashMap()); /** * Registers a new protocol with the given identifier. If a protocol with * the given ID already exists it will be overridden. This ID is the same * one used to retrieve the protocol from getProtocol(String). * * @param id the identifier for this protocol * @param protocol the protocol to register * * @see #getProtocol(String) */ public static void registerProtocol(String id, Protocol protocol) { if (id == null) { throw new IllegalArgumentException("id is null"); } if (protocol == null) { throw new IllegalArgumentException("protocol is null"); } PROTOCOLS.put(id, protocol); } /** * Unregisters the protocol with the given ID. * * @param id the ID of the protocol to remove */ public static void unregisterProtocol(String id) { if (id == null) { throw new IllegalArgumentException("id is null"); } PROTOCOLS.remove(id); } /** * Gets the protocol with the given ID. * * @param id the protocol ID * * @return Protocol a protocol * * @throws IllegalStateException if a protocol with the ID cannot be found */ public static Protocol getProtocol(String id) throws IllegalStateException { if (id == null) { throw new IllegalArgumentException("id is null"); } Protocol protocol = (Protocol) PROTOCOLS.get(id); if (protocol == null) { protocol = lazyRegisterProtocol(id); } return protocol; } /** * Lazily registers the protocol with the given id. * * @param id the protocol ID * * @return the lazily registered protocol * * @throws IllegalStateException if the protocol with id is not recognized */ private static Protocol lazyRegisterProtocol(String id) throws IllegalStateException { if ("http".equals(id)) { final Protocol http = new Protocol("http", DefaultProtocolSocketFactory.getSocketFactory(), 80); Protocol.registerProtocol("http", http); return http; } if ("https".equals(id)) { final Protocol https = new Protocol("https", SSLProtocolSocketFactory.getSocketFactory(), 443); Protocol.registerProtocol("https", https); return https; } throw new IllegalStateException("unsupported protocol: '" + id + "'"); } /** the scheme of this protocol (e.g. http, https) */ private String scheme; /** The socket factory for this protocol */ private ProtocolSocketFactory socketFactory; /** The default port for this protocol */ private int defaultPort; /** True if this protocol is secure */ private boolean secure; /** * Constructs a new Protocol. Whether the created protocol is secure depends on * the class of factory. * * @param scheme the scheme (e.g. http, https) * @param factory the factory for creating sockets for communication using * this protocol * @param defaultPort the port this protocol defaults to */ public Protocol(String scheme, ProtocolSocketFactory factory, int defaultPort) { if (scheme == null) { throw new IllegalArgumentException("scheme is null"); } if (factory == null) { throw new IllegalArgumentException("socketFactory is null"); } if (defaultPort <= 0) { throw new IllegalArgumentException("port is invalid: " + defaultPort); } this.scheme = scheme; this.socketFactory = factory; this.defaultPort = defaultPort; this.secure = (factory instanceof SecureProtocolSocketFactory); } /** * Constructs a new Protocol. Whether the created protocol is secure depends on * the class of factory. * * @param scheme the scheme (e.g. http, https) * @param factory the factory for creating sockets for communication using * this protocol * @param defaultPort the port this protocol defaults to * @deprecated Use the constructor that uses ProtocolSocketFactory, this version of * the constructor is only kept for backwards API compatibility. */ public Protocol(String scheme, SecureProtocolSocketFactory factory, int defaultPort) { this(scheme, (ProtocolSocketFactory) factory, defaultPort); } /** * Returns the defaultPort. * @return int */ public int getDefaultPort() { return defaultPort; } /** * Returns the socketFactory. If secure the factory is a * SecureProtocolSocketFactory. * @return SocketFactory */ public ProtocolSocketFactory getSocketFactory() { return socketFactory; } /** * Returns the scheme. * @return The scheme */ public String getScheme() { return scheme; } /** * Returns true if this protocol is secure * @return true if this protocol is secure */ public boolean isSecure() { return secure; } /** * Resolves the correct port for this protocol. Returns the given port if * valid or the default port otherwise. * * @param port the port to be resolved * * @return the given port or the defaultPort */ public int resolvePort(int port) { return port <= 0 ? getDefaultPort() : port; } /** * Return a string representation of this object. * @return a string representation of this object. */ public String toString() { return scheme + ":" + defaultPort; } /** * Return true if the specified object equals this object. * @param obj The object to compare against. * @return true if the objects are equal. */ public boolean equals(Object obj) { if (obj instanceof Protocol) { Protocol p = (Protocol) obj; return ( defaultPort == p.getDefaultPort() && scheme.equalsIgnoreCase(p.getScheme()) && secure == p.isSecure() && socketFactory.equals(p.getSocketFactory())); } else { return false; } } /** * Return a hash code for this object * @return The hash code. */ public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.defaultPort); hash = LangUtils.hashCode(hash, this.scheme.toLowerCase()); hash = LangUtils.hashCode(hash, this.secure); hash = LangUtils.hashCode(hash, this.socketFactory); return hash; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/ProtocolSocketFactory.java100644 0 0 10713 10661532626 30743 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/ProtocolSocketFactory.java,v 1.10 2004/05/13 04:01:22 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.protocol; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.params.HttpConnectionParams; /** * A factory for creating Sockets. * *

      Both {@link java.lang.Object#equals(java.lang.Object) Object.equals()} and * {@link java.lang.Object#hashCode() Object.hashCode()} should be overridden appropriately. * Protocol socket factories are used to uniquely identify Protocols and * HostConfigurations, and equals() and hashCode() are * required for the correct operation of some connection managers.

      * * @see Protocol * * @author Michael Becke * @author Mike Bowler * * @since 2.0 */ public interface ProtocolSocketFactory { /** * Gets a new socket connection to the given host. * * @param host the host name/IP * @param port the port on the host * @param localAddress the local host name/IP to bind the socket to * @param localPort the port on the local machine * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined */ Socket createSocket( String host, int port, InetAddress localAddress, int localPort ) throws IOException, UnknownHostException; /** * Gets a new socket connection to the given host. * * @param host the host name/IP * @param port the port on the host * @param localAddress the local host name/IP to bind the socket to * @param localPort the port on the local machine * @param params {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined * @throws ConnectTimeoutException if socket cannot be connected within the * given time limit * * @since 3.0 */ Socket createSocket( String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params ) throws IOException, UnknownHostException, ConnectTimeoutException; /** * Gets a new socket connection to the given host. * * @param host the host name/IP * @param port the port on the host * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined */ Socket createSocket( String host, int port ) throws IOException, UnknownHostException; } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/ReflectionSocketFactory.java100644 0 0 15710 10661532626 31236 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/ReflectionSocketFactory.java,v 1.4 2004/12/21 23:15:21 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.protocol; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import org.apache.commons.httpclient.ConnectTimeoutException; /** * This helper class uses refelction in order to execute Socket methods * available in Java 1.4 and above * * @author Oleg Kalnichevski * * @since 3.0 */ public final class ReflectionSocketFactory { private static boolean REFLECTION_FAILED = false; private static Constructor INETSOCKETADDRESS_CONSTRUCTOR = null; private static Method SOCKETCONNECT_METHOD = null; private static Method SOCKETBIND_METHOD = null; private static Class SOCKETTIMEOUTEXCEPTION_CLASS = null; private ReflectionSocketFactory() { super(); } /** * This method attempts to execute Socket method available since Java 1.4 * using reflection. If the methods are not available or could not be executed * null is returned * * @param socketfactoryName name of the socket factory class * @param host the host name/IP * @param port the port on the host * @param localAddress the local host name/IP to bind the socket to * @param localPort the port on the local machine * @param timeout the timeout value to be used in milliseconds. If the socket cannot be * completed within the given time limit, it will be abandoned * * @return a connected Socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined * @throws ConnectTimeoutException if socket cannot be connected within the * given time limit * */ public static Socket createSocket( final String socketfactoryName, final String host, final int port, final InetAddress localAddress, final int localPort, int timeout) throws IOException, UnknownHostException, ConnectTimeoutException { if (REFLECTION_FAILED) { //This is known to have failed before. Do not try it again return null; } // This code uses reflection to essentially do the following: // // SocketFactory socketFactory = Class.forName(socketfactoryName).getDefault(); // Socket socket = socketFactory.createSocket(); // SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); // SocketAddress remoteaddr = new InetSocketAddress(host, port); // socket.bind(localaddr); // socket.connect(remoteaddr, timeout); // return socket; try { Class socketfactoryClass = Class.forName(socketfactoryName); Method method = socketfactoryClass.getMethod("getDefault", new Class[] {}); Object socketfactory = method.invoke(null, new Object[] {}); method = socketfactoryClass.getMethod("createSocket", new Class[] {}); Socket socket = (Socket) method.invoke(socketfactory, new Object[] {}); if (INETSOCKETADDRESS_CONSTRUCTOR == null) { Class addressClass = Class.forName("java.net.InetSocketAddress"); INETSOCKETADDRESS_CONSTRUCTOR = addressClass.getConstructor( new Class[] { InetAddress.class, Integer.TYPE }); } Object remoteaddr = INETSOCKETADDRESS_CONSTRUCTOR.newInstance( new Object[] { InetAddress.getByName(host), new Integer(port)}); Object localaddr = INETSOCKETADDRESS_CONSTRUCTOR.newInstance( new Object[] { localAddress, new Integer(localPort)}); if (SOCKETCONNECT_METHOD == null) { SOCKETCONNECT_METHOD = Socket.class.getMethod("connect", new Class[] {Class.forName("java.net.SocketAddress"), Integer.TYPE}); } if (SOCKETBIND_METHOD == null) { SOCKETBIND_METHOD = Socket.class.getMethod("bind", new Class[] {Class.forName("java.net.SocketAddress")}); } SOCKETBIND_METHOD.invoke(socket, new Object[] { localaddr}); SOCKETCONNECT_METHOD.invoke(socket, new Object[] { remoteaddr, new Integer(timeout)}); return socket; } catch (InvocationTargetException e) { Throwable cause = e.getTargetException(); if (SOCKETTIMEOUTEXCEPTION_CLASS == null) { try { SOCKETTIMEOUTEXCEPTION_CLASS = Class.forName("java.net.SocketTimeoutException"); } catch (ClassNotFoundException ex) { // At this point this should never happen. Really. REFLECTION_FAILED = true; return null; } } if (SOCKETTIMEOUTEXCEPTION_CLASS.isInstance(cause)) { throw new ConnectTimeoutException( "The host did not accept the connection within timeout of " + timeout + " ms", cause); } if (cause instanceof IOException) { throw (IOException)cause; } return null; } catch (Exception e) { REFLECTION_FAILED = true; return null; } } } ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.javacommons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.java100644 0 0 14475 10661532627 31337 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.java,v 1.10 2004/05/13 04:01:22 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.protocol; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import javax.net.ssl.SSLSocketFactory; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.params.HttpConnectionParams; /** * A SecureProtocolSocketFactory that uses JSSE to create sockets. * * @author Michael Becke * @author Mike Bowler * * @since 2.0 */ public class SSLProtocolSocketFactory implements SecureProtocolSocketFactory { /** * The factory singleton. */ private static final SSLProtocolSocketFactory factory = new SSLProtocolSocketFactory(); /** * Gets an singleton instance of the SSLProtocolSocketFactory. * @return a SSLProtocolSocketFactory */ static SSLProtocolSocketFactory getSocketFactory() { return factory; } /** * Constructor for SSLProtocolSocketFactory. */ public SSLProtocolSocketFactory() { super(); } /** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) */ public Socket createSocket( String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { return SSLSocketFactory.getDefault().createSocket( host, port, clientHost, clientPort ); } /** * Attempts to get a new socket connection to the given host within the given time limit. *

      * This method employs several techniques to circumvent the limitations of older JREs that * do not support connect timeout. When running in JRE 1.4 or above reflection is used to * call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older * JREs a controller thread is executed. The controller thread attempts to create a new socket * within the given limit of time. If socket constructor does not return until the timeout * expires, the controller terminates and throws an {@link ConnectTimeoutException} *

      * * @param host the host name/IP * @param port the port on the host * @param localAddress the local host name/IP to bind the socket to * @param localPort the port on the local machine * @param params {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined * * @since 3.0 */ public Socket createSocket( final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params ) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); if (timeout == 0) { return createSocket(host, port, localAddress, localPort); } else { // To be eventually deprecated when migrated to Java 1.4 or above Socket socket = ReflectionSocketFactory.createSocket( "javax.net.ssl.SSLSocketFactory", host, port, localAddress, localPort, timeout); if (socket == null) { socket = ControllerThreadSocketFactory.createSocket( this, host, port, localAddress, localPort, timeout); } return socket; } } /** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int) */ public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return SSLSocketFactory.getDefault().createSocket( host, port ); } /** * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean) */ public Socket createSocket( Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket( socket, host, port, autoClose ); } /** * All instances of SSLProtocolSocketFactory are the same. */ public boolean equals(Object obj) { return ((obj != null) && obj.getClass().equals(getClass())); } /** * All instances of SSLProtocolSocketFactory have the same hash code. */ public int hashCode() { return getClass().hashCode(); } } ././@LongLink100644 0 0 150 10661532634 10255 Lustar 0 0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.javacommons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.j100644 0 0 5324 10661532626 31404 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.java,v 1.6 2004/04/18 23:51:38 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.protocol; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; /** * A ProtocolSocketFactory that is secure. * * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory * * @author Michael Becke * @author Mike Bowler * @since 2.0 */ public interface SecureProtocolSocketFactory extends ProtocolSocketFactory { /** * Returns a socket connected to the given host that is layered over an * existing socket. Used primarily for creating secure sockets through * proxies. * * @param socket the existing socket * @param host the host name/IP * @param port the port on the host * @param autoClose a flag for closing the underling socket when the created * socket is closed * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined */ Socket createSocket( Socket socket, String host, int port, boolean autoClose ) throws IOException, UnknownHostException; } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/protocol/package.html100644 0 0 430 10661532626 26012 0ustar 0 0 Package Documentation for org.apache.commons.httpclient.protocol Provides protocol specific socket factory handling. @since 2.0 commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/DateParseException.java100644 0 0 3603 10661532626 27264 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/DateParseException.java,v 1.5 2004/11/06 19:15:42 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; /** * An exception to indicate an error parsing a date string. * * @see DateUtil * * @author Michael Becke */ public class DateParseException extends Exception { /** * */ public DateParseException() { super(); } /** * @param message the exception message */ public DateParseException(String message) { super(message); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/DateParser.java100644 0 0 12153 10661532627 25610 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/DateParser.java,v 1.11 2004/11/06 19:15:42 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.TimeZone; /** * A utility class for parsing HTTP dates as used in cookies and other headers. * This class handles dates as defined by RFC 2616 section 3.3.1 as well as * some other common non-standard formats. * * @author Christopher Brown * @author Michael Becke * * @deprecated Use {@link org.apache.commons.httpclient.util.DateUtil} */ public class DateParser { /** * Date format pattern used to parse HTTP date headers in RFC 1123 format. */ public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; /** * Date format pattern used to parse HTTP date headers in RFC 1036 format. */ public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz"; /** * Date format pattern used to parse HTTP date headers in ANSI C * asctime() format. */ public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy"; private static final Collection DEFAULT_PATTERNS = Arrays.asList( new String[] { PATTERN_ASCTIME, PATTERN_RFC1036, PATTERN_RFC1123 } ); /** * Parses a date value. The formats used for parsing the date value are retrieved from * the default http params. * * @param dateValue the date value to parse * * @return the parsed date * * @throws DateParseException if the value could not be parsed using any of the * supported date formats */ public static Date parseDate(String dateValue) throws DateParseException { return parseDate(dateValue, null); } /** * Parses the date value using the given date formats. * * @param dateValue the date value to parse * @param dateFormats the date formats to use * * @return the parsed date * * @throws DateParseException if none of the dataFormats could parse the dateValue */ public static Date parseDate( String dateValue, Collection dateFormats ) throws DateParseException { if (dateValue == null) { throw new IllegalArgumentException("dateValue is null"); } if (dateFormats == null) { dateFormats = DEFAULT_PATTERNS; } // trim single quotes around date if present // see issue #5279 if (dateValue.length() > 1 && dateValue.startsWith("'") && dateValue.endsWith("'") ) { dateValue = dateValue.substring (1, dateValue.length() - 1); } SimpleDateFormat dateParser = null; Iterator formatIter = dateFormats.iterator(); while (formatIter.hasNext()) { String format = (String) formatIter.next(); if (dateParser == null) { dateParser = new SimpleDateFormat(format, Locale.US); dateParser.setTimeZone(TimeZone.getTimeZone("GMT")); } else { dateParser.applyPattern(format); } try { return dateParser.parse(dateValue); } catch (ParseException pe) { // ignore this exception, we will try the next format } } // we were unable to parse the date throw new DateParseException("Unable to parse the date " + dateValue); } /** This class should not be instantiated. */ private DateParser() { } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/DateUtil.java100644 0 0 17013 10661532627 25271 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/DateUtil.java,v 1.2 2004/12/24 20:36:13 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.TimeZone; /** * A utility class for parsing and formatting HTTP dates as used in cookies and * other headers. This class handles dates as defined by RFC 2616 section * 3.3.1 as well as some other common non-standard formats. * * @author Christopher Brown * @author Michael Becke */ public class DateUtil { /** * Date format pattern used to parse HTTP date headers in RFC 1123 format. */ public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; /** * Date format pattern used to parse HTTP date headers in RFC 1036 format. */ public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz"; /** * Date format pattern used to parse HTTP date headers in ANSI C * asctime() format. */ public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy"; private static final Collection DEFAULT_PATTERNS = Arrays.asList( new String[] { PATTERN_ASCTIME, PATTERN_RFC1036, PATTERN_RFC1123 } ); private static final Date DEFAULT_TWO_DIGIT_YEAR_START; static { Calendar calendar = Calendar.getInstance(); calendar.set(2000, Calendar.JANUARY, 1, 0, 0); DEFAULT_TWO_DIGIT_YEAR_START = calendar.getTime(); } private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); /** * Parses a date value. The formats used for parsing the date value are retrieved from * the default http params. * * @param dateValue the date value to parse * * @return the parsed date * * @throws DateParseException if the value could not be parsed using any of the * supported date formats */ public static Date parseDate(String dateValue) throws DateParseException { return parseDate(dateValue, null, null); } /** * Parses the date value using the given date formats. * * @param dateValue the date value to parse * @param dateFormats the date formats to use * * @return the parsed date * * @throws DateParseException if none of the dataFormats could parse the dateValue */ public static Date parseDate(String dateValue, Collection dateFormats) throws DateParseException { return parseDate(dateValue, dateFormats, null); } /** * Parses the date value using the given date formats. * * @param dateValue the date value to parse * @param dateFormats the date formats to use * @param startDate During parsing, two digit years will be placed in the range * startDate to startDate + 100 years. This value may * be null. When null is given as a parameter, year * 2000 will be used. * * @return the parsed date * * @throws DateParseException if none of the dataFormats could parse the dateValue */ public static Date parseDate( String dateValue, Collection dateFormats, Date startDate ) throws DateParseException { if (dateValue == null) { throw new IllegalArgumentException("dateValue is null"); } if (dateFormats == null) { dateFormats = DEFAULT_PATTERNS; } if (startDate == null) { startDate = DEFAULT_TWO_DIGIT_YEAR_START; } // trim single quotes around date if present // see issue #5279 if (dateValue.length() > 1 && dateValue.startsWith("'") && dateValue.endsWith("'") ) { dateValue = dateValue.substring (1, dateValue.length() - 1); } SimpleDateFormat dateParser = null; Iterator formatIter = dateFormats.iterator(); while (formatIter.hasNext()) { String format = (String) formatIter.next(); if (dateParser == null) { dateParser = new SimpleDateFormat(format, Locale.US); dateParser.setTimeZone(TimeZone.getTimeZone("GMT")); dateParser.set2DigitYearStart(startDate); } else { dateParser.applyPattern(format); } try { return dateParser.parse(dateValue); } catch (ParseException pe) { // ignore this exception, we will try the next format } } // we were unable to parse the date throw new DateParseException("Unable to parse the date " + dateValue); } /** * Formats the given date according to the RFC 1123 pattern. * * @param date The date to format. * @return An RFC 1123 formatted date string. * * @see #PATTERN_RFC1123 */ public static String formatDate(Date date) { return formatDate(date, PATTERN_RFC1123); } /** * Formats the given date according to the specified pattern. The pattern * must conform to that used by the {@link SimpleDateFormat simple date * format} class. * * @param date The date to format. * @param pattern The pattern to use for formatting the date. * @return A formatted date string. * * @throws IllegalArgumentException If the given date pattern is invalid. * * @see SimpleDateFormat */ public static String formatDate(Date date, String pattern) { if (date == null) throw new IllegalArgumentException("date is null"); if (pattern == null) throw new IllegalArgumentException("pattern is null"); SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.US); formatter.setTimeZone(GMT); return formatter.format(date); } /** This class should not be instantiated. */ private DateUtil() { } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/EncodingUtil.java100644 0 0 23622 10661532626 26144 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/EncodingUtil.java,v 1.8 2004/05/13 04:01:22 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; import java.io.UnsupportedEncodingException; import org.apache.commons.codec.net.URLCodec; import org.apache.commons.httpclient.HttpClientError; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * The home for utility methods that handle various encoding tasks. * * @author Michael Becke * @author Oleg Kalnichevski * * @since 2.0 final */ public class EncodingUtil { /** Default content encoding chatset */ private static final String DEFAULT_CHARSET = "ISO-8859-1"; /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(EncodingUtil.class); /** * Form-urlencoding routine. * * The default encoding for all forms is `application/x-www-form-urlencoded'. * A form data set is represented in this media type as follows: * * The form field names and values are escaped: space characters are replaced * by `+', and then reserved characters are escaped as per [URL]; that is, * non-alphanumeric characters are replaced by `%HH', a percent sign and two * hexadecimal digits representing the ASCII code of the character. Line breaks, * as in multi-line text field values, are represented as CR LF pairs, i.e. `%0D%0A'. * *

      * if the given charset is not supported, ISO-8859-1 is used instead. *

      * * @param pairs the values to be encoded * @param charset the character set of pairs to be encoded * * @return the urlencoded pairs * * @since 2.0 final */ public static String formUrlEncode(NameValuePair[] pairs, String charset) { try { return doFormUrlEncode(pairs, charset); } catch (UnsupportedEncodingException e) { LOG.error("Encoding not supported: " + charset); try { return doFormUrlEncode(pairs, DEFAULT_CHARSET); } catch (UnsupportedEncodingException fatal) { // Should never happen. ISO-8859-1 must be supported on all JVMs throw new HttpClientError("Encoding not supported: " + DEFAULT_CHARSET); } } } /** * Form-urlencoding routine. * * The default encoding for all forms is `application/x-www-form-urlencoded'. * A form data set is represented in this media type as follows: * * The form field names and values are escaped: space characters are replaced * by `+', and then reserved characters are escaped as per [URL]; that is, * non-alphanumeric characters are replaced by `%HH', a percent sign and two * hexadecimal digits representing the ASCII code of the character. Line breaks, * as in multi-line text field values, are represented as CR LF pairs, i.e. `%0D%0A'. * * @param pairs the values to be encoded * @param charset the character set of pairs to be encoded * * @return the urlencoded pairs * @throws UnsupportedEncodingException if charset is not supported * * @since 2.0 final */ private static String doFormUrlEncode(NameValuePair[] pairs, String charset) throws UnsupportedEncodingException { StringBuffer buf = new StringBuffer(); for (int i = 0; i < pairs.length; i++) { URLCodec codec = new URLCodec(); NameValuePair pair = pairs[i]; if (pair.getName() != null) { if (i > 0) { buf.append("&"); } buf.append(codec.encode(pair.getName(), charset)); buf.append("="); if (pair.getValue() != null) { buf.append(codec.encode(pair.getValue(), charset)); } } } return buf.toString(); } /** * 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. * * @since 3.0 */ public static String getString( final byte[] data, int offset, int length, String charset ) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } if (charset == null || charset.length() == 0) { throw new IllegalArgumentException("charset may not be null or empty"); } try { return new String(data, offset, length, charset); } catch (UnsupportedEncodingException e) { if (LOG.isWarnEnabled()) { LOG.warn("Unsupported encoding: " + charset + ". System encoding used"); } 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. * * @since 3.0 */ public static String getString(final byte[] data, String charset) { 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. * * @since 3.0 */ public static byte[] getBytes(final String data, String charset) { if (data == null) { throw new IllegalArgumentException("data may not be null"); } if (charset == null || charset.length() == 0) { throw new IllegalArgumentException("charset may not be null or empty"); } try { return data.getBytes(charset); } catch (UnsupportedEncodingException e) { if (LOG.isWarnEnabled()) { LOG.warn("Unsupported encoding: " + charset + ". System encoding used."); } 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. * * @since 3.0 */ public static byte[] getAsciiBytes(final String data) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } try { return data.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { throw new HttpClientError("HttpClient requires ASCII support"); } } /** * 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 * * @since 3.0 */ public static String getAsciiString(final byte[] data, int offset, int length) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } try { return new String(data, offset, length, "US-ASCII"); } catch (UnsupportedEncodingException e) { throw new HttpClientError("HttpClient requires ASCII support"); } } /** * 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 * * @since 3.0 */ public static String getAsciiString(final byte[] data) { return getAsciiString(data, 0, data.length); } /** * This class should not be instantiated. */ private EncodingUtil() { } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/ExceptionUtil.java100644 0 0 11223 10661532626 26346 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/ExceptionUtil.java,v 1.5 2004/10/19 18:09:46 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; import java.io.InterruptedIOException; import java.lang.reflect.Method; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * The home for utility methods that handle various exception-related tasks. * * @author Oleg Kalnichevski * @author Laura Werner * * @since 3.0 */ public class ExceptionUtil { /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(ExceptionUtil.class); /** 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(); /** A reference to SocketTimeoutExceptionClass class, or null if it's not there in this JVM */ static private final Class SOCKET_TIMEOUT_CLASS = SocketTimeoutExceptionClass(); /** * Returns a Method allowing access to * {@link Throwable.initCause(Throwable) initCause} method of {@link Throwable}, * or null if the method * does not exist. * * @return A Method for Throwable.initCause, or * null if unavailable. */ static private Method getInitCauseMethod() { try { Class[] paramsClasses = new Class[] { Throwable.class }; return Throwable.class.getMethod("initCause", paramsClasses); } catch (NoSuchMethodException e) { return null; } } /** * Returns SocketTimeoutExceptionClass or null if the class * does not exist. * * @return SocketTimeoutExceptionClass, or null if unavailable. */ static private Class SocketTimeoutExceptionClass() { try { return Class.forName("java.net.SocketTimeoutException"); } catch (ClassNotFoundException 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(Throwable throwable, Throwable cause) { if (INIT_CAUSE_METHOD != null) { try { INIT_CAUSE_METHOD.invoke(throwable, new Object[] { cause }); } catch (Exception e) { LOG.warn("Exception invoking Throwable.initCause", e); } } } /** * If SocketTimeoutExceptionClass is defined, returns true only if the * exception is an instance of SocketTimeoutExceptionClass. If * SocketTimeoutExceptionClass is undefined, always returns true. * * @param e an instance of InterruptedIOException class. * * @return true if the exception signals socket timeout, false * otherwise. */ public static boolean isSocketTimeoutException(final InterruptedIOException e) { if (SOCKET_TIMEOUT_CLASS != null) { return SOCKET_TIMEOUT_CLASS.isInstance(e); } else { return true; } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/HttpURLConnection.java100644 0 0 42712 10661532626 27103 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/HttpURLConnection.java,v 1.15 2004/04/18 23:51:38 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.Header; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.ProtocolException; import java.security.Permission; /** * Provides a HttpURLConnection wrapper around HttpClient's * HttpMethod. This allows existing code to easily switch to * HttpClieht without breaking existing interfaces using the JDK * HttpURLConnection. * * Note 1: The current implementations wraps only a connected * HttpMethod, ie a method that has alreayd been used to connect * to an HTTP server. * * Note 2: It is a best try effort as different version of the JDK have * different behaviours for HttpURLConnection (And I'm not even * including the numerous HttpURLConnection bugs!). * * @author Vincent Massol * @author Jeff Dever * @author Mike Bowler * * @since 2.0 * * @version $Id: HttpURLConnection.java 480424 2006-11-29 05:56:49Z bayard $ */ public class HttpURLConnection extends java.net.HttpURLConnection { // -------------------------------------------------------- Class Variables /** Log object for this class. */ private static final Log LOG = LogFactory.getLog(HttpURLConnection.class); // ----------------------------------------------------- Instance Variables /** * The HttpMethod object that was used to connect to the * HTTP server. It contains all the returned data. */ private HttpMethod method; /** * The URL to which we are connected */ private URL url; // ----------------------------------------------------------- Constructors /** * Creates an HttpURLConnection from a HttpMethod. * * @param method the theMethod that was used to connect to the HTTP * server and which contains the returned data. * @param url the URL to which we are connected (includes query string) */ public HttpURLConnection(HttpMethod method, URL url) { super(url); this.method = method; this.url = url; } /** * Create an instance. * @param url The URL. * @see java.net.HttpURLConnection#HttpURLConnection(URL) */ protected HttpURLConnection(URL url) { super(url); throw new RuntimeException("An HTTP URL connection can only be " + "constructed from a HttpMethod class"); } // --------------------------------------------------------- Public Methods /** * Gets an input stream for the HttpMethod response body. * @throws IOException If an IO problem occurs. * @return The input stream. * @see java.net.HttpURLConnection#getInputStream() * @see org.apache.commons.httpclient.HttpMethod#getResponseBodyAsStream() */ public InputStream getInputStream() throws IOException { LOG.trace("enter HttpURLConnection.getInputStream()"); return this.method.getResponseBodyAsStream(); } /** * Not yet implemented. * Return the error stream. * @see java.net.HttpURLConnection#getErrorStream() */ public InputStream getErrorStream() { LOG.trace("enter HttpURLConnection.getErrorStream()"); throw new RuntimeException("Not implemented yet"); } /** * Not yet implemented. * @see java.net.HttpURLConnection#disconnect() */ public void disconnect() { LOG.trace("enter HttpURLConnection.disconnect()"); throw new RuntimeException("Not implemented yet"); } /** * Not available: the data must have already been retrieved. * @throws IOException If an IO problem occurs. * @see java.net.HttpURLConnection#connect() */ public void connect() throws IOException { LOG.trace("enter HttpURLConnection.connect()"); throw new RuntimeException("This class can only be used with already" + "retrieved data"); } /** * Not yet implemented. * @return true if we are using a proxy. * @see java.net.HttpURLConnection#usingProxy() */ public boolean usingProxy() { LOG.trace("enter HttpURLConnection.usingProxy()"); throw new RuntimeException("Not implemented yet"); } /** * Return the request method. * @return The request method. * @see java.net.HttpURLConnection#getRequestMethod() * @see org.apache.commons.httpclient.HttpMethod#getName() */ public String getRequestMethod() { LOG.trace("enter HttpURLConnection.getRequestMethod()"); return this.method.getName(); } /** * Return the response code. * @return The response code. * @throws IOException If an IO problem occurs. * @see java.net.HttpURLConnection#getResponseCode() * @see org.apache.commons.httpclient.HttpMethod#getStatusCode() */ public int getResponseCode() throws IOException { LOG.trace("enter HttpURLConnection.getResponseCode()"); return this.method.getStatusCode(); } /** * Return the response message * @return The response message * @throws IOException If an IO problem occurs. * @see java.net.HttpURLConnection#getResponseMessage() * @see org.apache.commons.httpclient.HttpMethod#getStatusText() */ public String getResponseMessage() throws IOException { LOG.trace("enter HttpURLConnection.getResponseMessage()"); return this.method.getStatusText(); } /** * Return the header field * @param name the name of the header * @return the header field. * @see java.net.HttpURLConnection#getHeaderField(String) * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders() */ public String getHeaderField(String name) { LOG.trace("enter HttpURLConnection.getHeaderField(String)"); // Note: Return the last matching header in the Header[] array, as in // the JDK implementation. Header[] headers = this.method.getResponseHeaders(); for (int i = headers.length - 1; i >= 0; i--) { if (headers[i].getName().equalsIgnoreCase(name)) { return headers[i].getValue(); } } return null; } /** * Return the header field key * @param keyPosition The key position * @return The header field key. * @see java.net.HttpURLConnection#getHeaderFieldKey(int) * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders() */ public String getHeaderFieldKey(int keyPosition) { LOG.trace("enter HttpURLConnection.getHeaderFieldKey(int)"); // Note: HttpClient does not consider the returned Status Line as // a response header. However, getHeaderFieldKey(0) is supposed to // return null. Hence the special case below ... if (keyPosition == 0) { return null; } // Note: HttpClient does not currently keep headers in the same order // that they are read from the HTTP server. Header[] headers = this.method.getResponseHeaders(); if (keyPosition < 0 || keyPosition > headers.length) { return null; } return headers[keyPosition - 1].getName(); } /** * Return the header field at the specified position * @param position The position * @return The header field. * @see java.net.HttpURLConnection#getHeaderField(int) * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders() */ public String getHeaderField(int position) { LOG.trace("enter HttpURLConnection.getHeaderField(int)"); // Note: HttpClient does not consider the returned Status Line as // a response header. However, getHeaderField(0) is supposed to // return the status line. Hence the special case below ... if (position == 0) { return this.method.getStatusLine().toString(); } // Note: HttpClient does not currently keep headers in the same order // that they are read from the HTTP server. Header[] headers = this.method.getResponseHeaders(); if (position < 0 || position > headers.length) { return null; } return headers[position - 1].getValue(); } /** * Return the URL * @return The URL. * @see java.net.HttpURLConnection#getURL() */ public URL getURL() { LOG.trace("enter HttpURLConnection.getURL()"); return this.url; } // Note: We don't implement the following methods so that they default to // the JDK implementation. They will all call // getHeaderField(String) which we have overridden. // java.net.HttpURLConnection#getHeaderFieldDate(String, long) // java.net.HttpURLConnection#getContentLength() // java.net.HttpURLConnection#getContentType() // java.net.HttpURLConnection#getContentEncoding() // java.net.HttpURLConnection#getDate() // java.net.HttpURLConnection#getHeaderFieldInt(String, int) // java.net.HttpURLConnection#getExpiration() // java.net.HttpURLConnection#getLastModified() /** * Not available: the data must have already been retrieved. */ public void setInstanceFollowRedirects(boolean isFollowingRedirects) { LOG.trace("enter HttpURLConnection.setInstanceFollowRedirects(boolean)"); throw new RuntimeException("This class can only be used with already" + "retrieved data"); } /** * Not yet implemented. */ public boolean getInstanceFollowRedirects() { LOG.trace("enter HttpURLConnection.getInstanceFollowRedirects()"); throw new RuntimeException("Not implemented yet"); } /** * Not available: the data must have already been retrieved. * @see java.net.HttpURLConnection#setRequestMethod(String) */ public void setRequestMethod(String method) throws ProtocolException { LOG.trace("enter HttpURLConnection.setRequestMethod(String)"); throw new RuntimeException("This class can only be used with already" + "retrieved data"); } /** * Not yet implemented. * @see java.net.HttpURLConnection#getPermission() */ public Permission getPermission() throws IOException { LOG.trace("enter HttpURLConnection.getPermission()"); throw new RuntimeException("Not implemented yet"); } /** * Not yet implemented. * @see java.net.HttpURLConnection#getContent() */ public Object getContent() throws IOException { LOG.trace("enter HttpURLConnection.getContent()"); throw new RuntimeException("Not implemented yet"); } /** * Not yet implemented. */ public Object getContent(Class[] classes) throws IOException { LOG.trace("enter HttpURLConnection.getContent(Class[])"); throw new RuntimeException("Not implemented yet"); } /** * @see java.net.HttpURLConnection#getOutputStream() */ public OutputStream getOutputStream() throws IOException { LOG.trace("enter HttpURLConnection.getOutputStream()"); throw new RuntimeException("This class can only be used with already" + "retrieved data"); } /** * Not available: the data must have already been retrieved. * @see java.net.HttpURLConnection#setDoInput(boolean) */ public void setDoInput(boolean isInput) { LOG.trace("enter HttpURLConnection.setDoInput()"); throw new RuntimeException("This class can only be used with already" + "retrieved data"); } /** * Not yet implemented. * @see java.net.HttpURLConnection#getDoInput() */ public boolean getDoInput() { LOG.trace("enter HttpURLConnection.getDoInput()"); throw new RuntimeException("Not implemented yet"); } /** * Not available: the data must have already been retrieved. * @see java.net.HttpURLConnection#setDoOutput(boolean) */ public void setDoOutput(boolean isOutput) { LOG.trace("enter HttpURLConnection.setDoOutput()"); throw new RuntimeException("This class can only be used with already" + "retrieved data"); } /** * Not yet implemented. * @see java.net.HttpURLConnection#getDoOutput() */ public boolean getDoOutput() { LOG.trace("enter HttpURLConnection.getDoOutput()"); throw new RuntimeException("Not implemented yet"); } /** * Not available: the data must have already been retrieved. * @see java.net.HttpURLConnection#setAllowUserInteraction(boolean) */ public void setAllowUserInteraction(boolean isAllowInteraction) { LOG.trace("enter HttpURLConnection.setAllowUserInteraction(boolean)"); throw new RuntimeException("This class can only be used with already" + "retrieved data"); } /** * Not yet implemented. * @see java.net.HttpURLConnection#getAllowUserInteraction() */ public boolean getAllowUserInteraction() { LOG.trace("enter HttpURLConnection.getAllowUserInteraction()"); throw new RuntimeException("Not implemented yet"); } /** * Not available: the data must have already been retrieved. * @see java.net.HttpURLConnection#setUseCaches(boolean) */ public void setUseCaches(boolean isUsingCaches) { LOG.trace("enter HttpURLConnection.setUseCaches(boolean)"); throw new RuntimeException("This class can only be used with already" + "retrieved data"); } /** * Not yet implemented. * @see java.net.HttpURLConnection#getUseCaches() */ public boolean getUseCaches() { LOG.trace("enter HttpURLConnection.getUseCaches()"); throw new RuntimeException("Not implemented yet"); } /** * Not available: the data must have already been retrieved. * @see java.net.HttpURLConnection#setIfModifiedSince(long) */ public void setIfModifiedSince(long modificationDate) { LOG.trace("enter HttpURLConnection.setIfModifiedSince(long)"); throw new RuntimeException("This class can only be used with already" + "retrieved data"); } /** * Not yet implemented. * @see java.net.HttpURLConnection#getIfModifiedSince() */ public long getIfModifiedSince() { LOG.trace("enter HttpURLConnection.getIfmodifiedSince()"); throw new RuntimeException("Not implemented yet"); } /** * Not available: the data must have already been retrieved. * @see java.net.HttpURLConnection#getDefaultUseCaches() */ public boolean getDefaultUseCaches() { LOG.trace("enter HttpURLConnection.getDefaultUseCaches()"); throw new RuntimeException("Not implemented yet"); } /** * Not available: the data must have already been retrieved. * @see java.net.HttpURLConnection#setDefaultUseCaches(boolean) */ public void setDefaultUseCaches(boolean isUsingCaches) { LOG.trace("enter HttpURLConnection.setDefaultUseCaches(boolean)"); throw new RuntimeException("This class can only be used with already" + "retrieved data"); } /** * Not available: the data must have already been retrieved. * @see java.net.HttpURLConnection#setRequestProperty(String,String) */ public void setRequestProperty(String key, String value) { LOG.trace("enter HttpURLConnection.setRequestProperty()"); throw new RuntimeException("This class can only be used with already" + "retrieved data"); } /** * Not yet implemented. * @see java.net.HttpURLConnection#getRequestProperty(String) */ public String getRequestProperty(String key) { LOG.trace("enter HttpURLConnection.getRequestProperty()"); throw new RuntimeException("Not implemented yet"); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/IdleConnectionHandler.java100644 0 0 10512 10661532626 27745 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/IdleConnectionHandler.java,v 1.2 2004/05/13 02:40:36 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.httpclient.HttpConnection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A helper class for connection managers to track idle connections. * *

      This class is not synchronized.

      * * @see org.apache.commons.httpclient.HttpConnectionManager#closeIdleConnections(long) * * @since 3.0 */ public class IdleConnectionHandler { private static final Log LOG = LogFactory.getLog(IdleConnectionHandler.class); /** Holds connections and the time they were added. */ private Map connectionToAdded = new HashMap(); /** * */ public IdleConnectionHandler() { super(); } /** * Registers the given connection with this handler. The connection will be held until * {@link #remove(HttpConnection)} or {@link #closeIdleConnections(long)} is called. * * @param connection the connection to add * * @see #remove(HttpConnection) */ public void add(HttpConnection connection) { Long timeAdded = new Long(System.currentTimeMillis()); if (LOG.isDebugEnabled()) { LOG.debug("Adding connection at: " + timeAdded); } connectionToAdded.put(connection, timeAdded); } /** * Removes the given connection from the list of connections to be closed when idle. * @param connection */ public void remove(HttpConnection connection) { connectionToAdded.remove(connection); } /** * Removes all connections referenced by this handler. */ public void removeAll() { this.connectionToAdded.clear(); } /** * Closes connections that have been idle for at least the given amount of time. * * @param idleTime the minimum idle time, in milliseconds, for connections to be closed */ public void closeIdleConnections(long idleTime) { // the latest time for which connections will be closed long idleTimeout = System.currentTimeMillis() - idleTime; if (LOG.isDebugEnabled()) { LOG.debug("Checking for connections, idleTimeout: " + idleTimeout); } Iterator connectionIter = connectionToAdded.keySet().iterator(); while (connectionIter.hasNext()) { HttpConnection conn = (HttpConnection) connectionIter.next(); Long connectionTime = (Long) connectionToAdded.get(conn); if (connectionTime.longValue() <= idleTimeout) { if (LOG.isDebugEnabled()) { LOG.debug("Closing connection, connection time: " + connectionTime); } connectionIter.remove(); conn.close(); } } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/IdleConnectionTimeoutThread.java100644 0 0 13116 10661532626 31151 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/IdleConnectionTimeoutThread.java,v 1.2 2004/05/13 02:40:36 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.httpclient.HttpConnectionManager; /** * A utility class for periodically closing idle connections. * * @see org.apache.commons.httpclient.HttpConnectionManager#closeIdleConnections(long) * * @since 3.0 */ public class IdleConnectionTimeoutThread extends Thread { private List connectionManagers = new ArrayList(); private boolean shutdown = false; private long timeoutInterval = 1000; private long connectionTimeout = 3000; public IdleConnectionTimeoutThread() { setDaemon(true); } /** * Adds a connection manager to be handled by this class. * {@link HttpConnectionManager#closeIdleConnections(long)} will be called on the connection * manager every {@link #setTimeoutInterval(long) timeoutInterval} milliseconds. * * @param connectionManager The connection manager to add */ public synchronized void addConnectionManager(HttpConnectionManager connectionManager) { if (shutdown) { throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown"); } this.connectionManagers.add(connectionManager); } /** * Removes the connection manager from this class. The idle connections from the connection * manager will no longer be automatically closed by this class. * * @param connectionManager The connection manager to remove */ public synchronized void removeConnectionManager(HttpConnectionManager connectionManager) { if (shutdown) { throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown"); } this.connectionManagers.remove(connectionManager); } /** * Handles calling {@link HttpConnectionManager#closeIdleConnections(long) closeIdleConnections()} * and doing any other cleanup work on the given connection mangaer. * @param connectionManager The connection manager to close idle connections for */ protected void handleCloseIdleConnections(HttpConnectionManager connectionManager) { connectionManager.closeIdleConnections(connectionTimeout); } /** * Closes idle connections. */ public synchronized void run() { while (!shutdown) { Iterator iter = connectionManagers.iterator(); while (iter.hasNext()) { HttpConnectionManager connectionManager = (HttpConnectionManager) iter.next(); handleCloseIdleConnections(connectionManager); } try { this.wait(timeoutInterval); } catch (InterruptedException e) { } } // clear out the connection managers now that we're shutdown this.connectionManagers.clear(); } /** * Stops the thread used to close idle connections. This class cannot be used once shutdown. */ public synchronized void shutdown() { this.shutdown = true; this.notifyAll(); } /** * Sets the timeout value to use when testing for idle connections. * * @param connectionTimeout The connection timeout in milliseconds * * @see HttpConnectionManager#closeIdleConnections(long) */ public synchronized void setConnectionTimeout(long connectionTimeout) { if (shutdown) { throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown"); } this.connectionTimeout = connectionTimeout; } /** * Sets the interval used by this class between closing idle connections. Idle * connections will be closed every timeoutInterval milliseconds. * * @param timeoutInterval The timeout interval in milliseconds */ public synchronized void setTimeoutInterval(long timeoutInterval) { if (shutdown) { throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown"); } this.timeoutInterval = timeoutInterval; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/LangUtils.java100644 0 0 4530 10661532626 25437 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/util/LangUtils.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; /** * A set of utility methods to help produce consistent Object#equals(Object) and * Object#hashCode methods. * * @author Oleg Kalnichevski * * @since 3.0 */ public class LangUtils { public static final int HASH_SEED = 17; public static final int HASH_OFFSET = 37; private LangUtils() { super(); } public static int hashCode(final int seed, final int hashcode) { return seed * HASH_OFFSET + hashcode; } public static int hashCode(final int seed, final Object obj) { return hashCode(seed, obj != null ? obj.hashCode() : 0); } public static int hashCode(final int seed, final boolean b) { return hashCode(seed, b ? 1 : 0); } public static boolean equals(final Object obj1, final Object obj2) { return obj1 == null ? obj2 == null : obj1.equals(obj2); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/ParameterFormatter.java100644 0 0 20277 10661532626 27367 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/util/ParameterFormatter.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; import org.apache.commons.httpclient.NameValuePair; /** *

      * This formatter produces a textual representation of attribute/value pairs. It * comforms to the generic grammar and formatting rules outlined in the * Section 2.1 * and * Section 3.6 * of RFC 2616 *

      * 2.1 Augmented BNF *

      * Many HTTP/1.1 header field values consist of words separated by LWS or special * characters. These special characters MUST be in a quoted string to be used within * a parameter value (as defined in section 3.6). *

      *

       * token          = 1*
       * separators     = "(" | ")" | "<" | ">" | "@"
       *                | "," | ";" | ":" | "\" | <">
       *                | "/" | "[" | "]" | "?" | "="
       *                | "{" | "}" | SP | HT
       * 
      *

      * A string of text is parsed as a single word if it is quoted using double-quote marks. *

      *
       * quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
       * qdtext         = >
       * 
      *

      * The backslash character ("\") MAY be used as a single-character quoting mechanism only * within quoted-string and comment constructs. *

      *
       * quoted-pair    = "\" CHAR
       * 
      * 3.6 Transfer Codings *

      * Parameters are in the form of attribute/value pairs. *

      *
       * parameter               = attribute "=" value
       * attribute               = token
       * value                   = token | quoted-string
       * 
      * * @author Oleg Kalnichevski * * @since 3.0 */ public class ParameterFormatter { /** * 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 */ private static final char[] SEPARATORS = { '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}', ' ', '\t' }; /** * Unsafe special characters that must be escaped using the backslash * character */ private static final char[] UNSAFE_CHARS = { '"', '\\' }; /** * This flag determines whether all parameter values must be enclosed in * quotation marks, even if they do not contain any special characters */ private boolean alwaysUseQuotes = true; /** Default ParameterFormatter constructor */ public ParameterFormatter() { super(); } private static boolean isOneOf(char[] chars, char ch) { for (int i = 0; i < chars.length; i++) { if (ch == chars[i]) { return true; } } return false; } private static boolean isUnsafeChar(char ch) { return isOneOf(UNSAFE_CHARS, ch); } private static boolean isSeparator(char ch) { return isOneOf(SEPARATORS, ch); } /** * Determines whether all parameter values must be enclosed in quotation * marks, even if they do not contain any special characters * * @return true if all parameter values must be enclosed in * quotation marks, false otherwise */ public boolean isAlwaysUseQuotes() { return alwaysUseQuotes; } /** * Defines whether all parameter values must be enclosed in quotation * marks, even if they do not contain any special characters * * @param alwaysUseQuotes */ public void setAlwaysUseQuotes(boolean alwaysUseQuotes) { this.alwaysUseQuotes = alwaysUseQuotes; } /** * Formats the given parameter value using formatting rules defined * in RFC 2616 * * @param buffer output buffer * @param value the parameter value to be formatted * @param alwaysUseQuotes true if the parameter value must * be enclosed in quotation marks, even if it does not contain any special * characters, false only if the parameter value contains * potentially unsafe special characters */ public static void formatValue( final StringBuffer buffer, final String value, boolean alwaysUseQuotes) { if (buffer == null) { throw new IllegalArgumentException("String buffer may not be null"); } if (value == null) { throw new IllegalArgumentException("Value buffer may not be null"); } if (alwaysUseQuotes) { buffer.append('"'); for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (isUnsafeChar(ch)) { buffer.append('\\'); } buffer.append(ch); } buffer.append('"'); } else { int offset = buffer.length(); boolean unsafe = false; for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (isSeparator(ch)) { unsafe = true; } if (isUnsafeChar(ch)) { buffer.append('\\'); } buffer.append(ch); } if (unsafe) { buffer.insert(offset, '"'); buffer.append('"'); } } } /** * Produces textual representaion of the attribute/value pair using * formatting rules defined in RFC 2616 * * @param buffer output buffer * @param param the parameter to be formatted */ public void format(final StringBuffer buffer, final NameValuePair param) { if (buffer == null) { throw new IllegalArgumentException("String buffer may not be null"); } if (param == null) { throw new IllegalArgumentException("Parameter may not be null"); } buffer.append(param.getName()); String value = param.getValue(); if (value != null) { buffer.append("="); formatValue(buffer, value, this.alwaysUseQuotes); } } /** * Produces textual representaion of the attribute/value pair using * formatting rules defined in RFC 2616 * * @param param the parameter to be formatted * * @return RFC 2616 conformant textual representaion of the * attribute/value pair */ public String format(final NameValuePair param) { StringBuffer buffer = new StringBuffer(); format(buffer, param); return buffer.toString(); } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/ParameterParser.java100644 0 0 15767 10661532626 26670 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/ParameterParser.java,v 1.5 2004/05/13 04:01:22 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.NameValuePair; /** * A simple parser intended to parse sequences of name/value pairs. * Parameter values are exptected to be enclosed in quotes if they * contain unsafe characters, such as '=' characters or separators. * Parameter values are optional and can be omitted. * *

      * param1 = value; param2 = "anything goes; really"; param3 *

      * * @author Oleg Kalnichevski * * @since 3.0 */ public class ParameterParser { /** String to be parsed */ private char[] chars = null; /** Current position in the string */ private int pos = 0; /** Maximum position in the string */ private int len = 0; /** Start of a token */ private int i1 = 0; /** End of a token */ private int i2 = 0; /** Default ParameterParser constructor */ public ParameterParser() { super(); } /** Are there any characters left to parse? */ private boolean hasChar() { return this.pos < this.len; } /** A helper method to process the parsed token. */ private String getToken(boolean quoted) { // Trim leading white spaces while ((i1 < i2) && (Character.isWhitespace(chars[i1]))) { i1++; } // Trim trailing white spaces while ((i2 > i1) && (Character.isWhitespace(chars[i2 - 1]))) { i2--; } // Strip away quotes if necessary if (quoted) { if (((i2 - i1) >= 2) && (chars[i1] == '"') && (chars[i2 - 1] == '"')) { i1++; i2--; } } String result = null; if (i2 >= i1) { result = new String(chars, i1, i2 - i1); } return result; } /** Is given character present in the array of characters? */ private boolean isOneOf(char ch, char[] charray) { boolean result = false; for (int i = 0; i < charray.length; i++) { if (ch == charray[i]) { result = true; break; } } return result; } /** Parse out a token until any of the given terminators * is encountered. */ private String parseToken(final char[] terminators) { char ch; i1 = pos; i2 = pos; while (hasChar()) { ch = chars[pos]; if (isOneOf(ch, terminators)) { break; } i2++; pos++; } return getToken(false); } /** Parse out a token until any of the given terminators * is encountered. Special characters in quoted tokens * are escaped. */ private String parseQuotedToken(final char[] terminators) { char ch; i1 = pos; i2 = pos; boolean quoted = false; boolean charEscaped = false; while (hasChar()) { ch = chars[pos]; if (!quoted && isOneOf(ch, terminators)) { break; } if (!charEscaped && ch == '"') { quoted = !quoted; } charEscaped = (!charEscaped && ch == '\\'); i2++; pos++; } return getToken(true); } /** * Extracts a list of {@link NameValuePair}s from the given string. * * @param str the string that contains a sequence of name/value pairs * @return a list of {@link NameValuePair}s * */ public List parse(final String str, char separator) { if (str == null) { return new ArrayList(); } return parse(str.toCharArray(), separator); } /** * Extracts a list of {@link NameValuePair}s from the given array of * characters. * * @param chars the array of characters that contains a sequence of * name/value pairs * * @return a list of {@link NameValuePair}s */ public List parse(final char[] chars, char separator) { if (chars == null) { return new ArrayList(); } return parse(chars, 0, chars.length, separator); } /** * Extracts a list of {@link NameValuePair}s from the given array of * characters. * * @param chars the array of characters that contains a sequence of * name/value pairs * @param offset - the initial offset. * @param length - the length. * * @return a list of {@link NameValuePair}s */ public List parse(final char[] chars, int offset, int length, char separator) { if (chars == null) { return new ArrayList(); } List params = new ArrayList(); this.chars = chars; this.pos = offset; this.len = length; String paramName = null; String paramValue = null; while (hasChar()) { paramName = parseToken(new char[] {'=', separator}); paramValue = null; if (hasChar() && (chars[pos] == '=')) { pos++; // skip '=' paramValue = parseQuotedToken(new char[] {separator}); } if (hasChar() && (chars[pos] == separator)) { pos++; // skip separator } if (paramName != null && !(paramName.equals("") && paramValue == null)) { params.add(new NameValuePair(paramName, paramValue)); } } return params; } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/TimeoutController.java100644 0 0 7012 10661532626 27225 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/TimeoutController.java,v 1.6 2004/04/18 23:51:38 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; /** *

      * Executes a task with a specified timeout. *

      * @author Ortwin Glueck * @author Mike Bowler * @version $Revision: 480424 $ * @since 2.0 */ public final class TimeoutController { /** * Do not instantiate objects of this class. Methods are static. */ private TimeoutController() { } /** * Executes task. Waits for timeout * milliseconds for the task to end and returns. If the task does not return * in time, the thread is interrupted and an Exception is thrown. * The caller should override the Thread.interrupt() method to something that * quickly makes the thread die or use Thread.isInterrupted(). * @param task The thread to execute * @param timeout The timeout in milliseconds. 0 means to wait forever. * @throws TimeoutException if the timeout passes and the thread does not return. */ public static void execute(Thread task, long timeout) throws TimeoutException { task.start(); try { task.join(timeout); } catch (InterruptedException e) { /* if somebody interrupts us he knows what he is doing */ } if (task.isAlive()) { task.interrupt(); throw new TimeoutException(); } } /** * Executes task in a new deamon Thread and waits for the timeout. * @param task The task to execute * @param timeout The timeout in milliseconds. 0 means to wait forever. * @throws TimeoutException if the timeout passes and the thread does not return. */ public static void execute(Runnable task, long timeout) throws TimeoutException { Thread t = new Thread(task, "Timeout guard"); t.setDaemon(true); execute(t, timeout); } /** * Signals that the task timed out. */ public static class TimeoutException extends Exception { /** Create an instance */ public TimeoutException() { } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/URIUtil.java100644 0 0 52351 10661532626 25056 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/URIUtil.java,v 1.27 2004/05/05 20:34:01 olegk Exp $ * $Revision: 507321 $ * $Date: 2007-02-14 01:10:51 +0100 (Wed, 14 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.util; import java.util.BitSet; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.net.URLCodec; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.URIException; /** * The URI escape and character encoding and decoding utility. * It's compatible with {@link org.apache.commons.httpclient.HttpURL} rather * than {@link org.apache.commons.httpclient.URI}. * * @author Sung-Gu * @version $Revision: 507321 $ $Date: 2002/03/14 15:14:01 */ public class URIUtil { // ----------------------------------------------------- Instance variables protected static final BitSet empty = new BitSet(1); // ---------------------------------------------------------- URI utilities /** * Get the basename of an URI. It's possibly an empty string. * * @param uri a string regarded an URI * @return the basename string; an empty string if the path ends with slash */ public static String getName(String uri) { if (uri == null || uri.length() == 0) { return uri; } String path = URIUtil.getPath(uri); int at = path.lastIndexOf("/"); int to = path.length(); return (at >= 0) ? path.substring(at + 1, to) : path; } /** * Get the query of an URI. * * @param uri a string regarded an URI * @return the query string; null if empty or undefined */ public static String getQuery(String uri) { if (uri == null || uri.length() == 0) { return null; } // consider of net_path int at = uri.indexOf("//"); int from = uri.indexOf( "/", at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0 ); // the authority part of URI ignored int to = uri.length(); // reuse the at and from variables to consider the query at = uri.indexOf("?", from); if (at >= 0) { from = at + 1; } else { return null; } // check the fragment if (uri.lastIndexOf("#") > from) { to = uri.lastIndexOf("#"); } // get the path and query. return (from < 0 || from == to) ? null : uri.substring(from, to); } /** * Get the path of an URI. * * @param uri a string regarded an URI * @return the path string */ public static String getPath(String uri) { if (uri == null) { return null; } // consider of net_path int at = uri.indexOf("//"); int from = uri.indexOf( "/", at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0 ); // the authority part of URI ignored int to = uri.length(); // check the query if (uri.indexOf('?', from) != -1) { to = uri.indexOf('?', from); } // check the fragment if (uri.lastIndexOf("#") > from && uri.lastIndexOf("#") < to) { to = uri.lastIndexOf("#"); } // get only the path. return (from < 0) ? (at >= 0 ? "/" : uri) : uri.substring(from, to); } /** * Get the path and query of an URI. * * @param uri a string regarded an URI * @return the path and query string */ public static String getPathQuery(String uri) { if (uri == null) { return null; } // consider of net_path int at = uri.indexOf("//"); int from = uri.indexOf( "/", at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0 ); // the authority part of URI ignored int to = uri.length(); // Ignore the '?' mark so to ignore the query. // check the fragment if (uri.lastIndexOf("#") > from) { to = uri.lastIndexOf("#"); } // get the path and query. return (from < 0) ? (at >= 0 ? "/" : uri) : uri.substring(from, to); } /** * Get the path of an URI and its rest part. * * @param uri a string regarded an URI * @return the string from the path part */ public static String getFromPath(String uri) { if (uri == null) { return null; } // consider of net_path int at = uri.indexOf("//"); int from = uri.indexOf( "/", at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0 ); // get the path and its rest. return (from < 0) ? (at >= 0 ? "/" : uri) : uri.substring(from); } // ----------------------------------------------------- Encoding utilities /** * Get the all escaped and encoded string with the default protocl charset. * It's the same function to use encode(String unescaped, Bitset * empty, URI.getDefaultProtocolCharset()). * * @param unescaped an unescaped string * @return the escaped string * * @throws URIException if the default protocol charset is not supported * * @see URI#getDefaultProtocolCharset * @see #encode */ public static String encodeAll(String unescaped) throws URIException { return encodeAll(unescaped, URI.getDefaultProtocolCharset()); } /** * Get the all escaped and encoded string with a given charset. * It's the same function to use encode(String unescaped, Bitset * empty, String charset). * * @param unescaped an unescaped string * @param charset the charset * @return the escaped string * * @throws URIException if the charset is not supported * * @see #encode */ public static String encodeAll(String unescaped, String charset) throws URIException { return encode(unescaped, empty, charset); } /** * Escape and encode a string regarded as within the authority component of * an URI with the default protocol charset. * Within the authority component, the characters ";", ":", "@", "?", and * "/" are reserved. * * @param unescaped an unescaped string * @return the escaped string * * @throws URIException if the default protocol charset is not supported * * @see URI#getDefaultProtocolCharset * @see #encode */ public static String encodeWithinAuthority(String unescaped) throws URIException { return encodeWithinAuthority(unescaped, URI.getDefaultProtocolCharset()); } /** * Escape and encode a string regarded as within the authority component of * an URI with a given charset. * Within the authority component, the characters ";", ":", "@", "?", and * "/" are reserved. * * @param unescaped an unescaped string * @param charset the charset * @return the escaped string * * @throws URIException if the charset is not supported * * @see #encode */ public static String encodeWithinAuthority(String unescaped, String charset) throws URIException { return encode(unescaped, URI.allowed_within_authority, charset); } /** * Escape and encode a string regarded as the path and query components of * an URI with the default protocol charset. * * @param unescaped an unescaped string * @return the escaped string * * @throws URIException if the default protocol charset is not supported * * @see URI#getDefaultProtocolCharset * @see #encode */ public static String encodePathQuery(String unescaped) throws URIException { return encodePathQuery(unescaped, URI.getDefaultProtocolCharset()); } /** * Escape and encode a string regarded as the path and query components of * an URI with a given charset. * * @param unescaped an unescaped string * @param charset the charset * @return the escaped string * * @throws URIException if the charset is not supported * * @see #encode */ public static String encodePathQuery(String unescaped, String charset) throws URIException { int at = unescaped.indexOf('?'); if (at < 0) { return encode(unescaped, URI.allowed_abs_path, charset); } // else return encode(unescaped.substring(0, at), URI.allowed_abs_path, charset) + '?' + encode(unescaped.substring(at + 1), URI.allowed_query, charset); } /** * Escape and encode a string regarded as within the path component of an * URI with the default protocol charset. * The path may consist of a sequence of path segments separated by a * single slash "/" character. Within a path segment, the characters * "/", ";", "=", and "?" are reserved. * * @param unescaped an unescaped string * @return the escaped string * * @throws URIException if the default protocol charset is not supported * * @see URI#getDefaultProtocolCharset * @see #encode */ public static String encodeWithinPath(String unescaped) throws URIException { return encodeWithinPath(unescaped, URI.getDefaultProtocolCharset()); } /** * Escape and encode a string regarded as within the path component of an * URI with a given charset. * The path may consist of a sequence of path segments separated by a * single slash "/" character. Within a path segment, the characters * "/", ";", "=", and "?" are reserved. * * @param unescaped an unescaped string * @param charset the charset * @return the escaped string * * @throws URIException if the charset is not supported * * @see #encode */ public static String encodeWithinPath(String unescaped, String charset) throws URIException { return encode(unescaped, URI.allowed_within_path, charset); } /** * Escape and encode a string regarded as the path component of an URI with * the default protocol charset. * * @param unescaped an unescaped string * @return the escaped string * * @throws URIException if the default protocol charset is not supported * * @see URI#getDefaultProtocolCharset * @see #encode */ public static String encodePath(String unescaped) throws URIException { return encodePath(unescaped, URI.getDefaultProtocolCharset()); } /** * Escape and encode a string regarded as the path component of an URI with * a given charset. * * @param unescaped an unescaped string * @param charset the charset * @return the escaped string * * @throws URIException if the charset is not supported * * @see #encode */ public static String encodePath(String unescaped, String charset) throws URIException { return encode(unescaped, URI.allowed_abs_path, charset); } /** * Escape and encode a string regarded as within the query component of an * URI with the default protocol charset. * When a query comprise the name and value pairs, it is used in order * to encode each name and value string. The reserved special characters * within a query component are being included in encoding the query. * * @param unescaped an unescaped string * @return the escaped string * * @throws URIException if the default protocol charset is not supported * * @see URI#getDefaultProtocolCharset * @see #encode */ public static String encodeWithinQuery(String unescaped) throws URIException { return encodeWithinQuery(unescaped, URI.getDefaultProtocolCharset()); } /** * Escape and encode a string regarded as within the query component of an * URI with a given charset. * When a query comprise the name and value pairs, it is used in order * to encode each name and value string. The reserved special characters * within a query component are being included in encoding the query. * * @param unescaped an unescaped string * @param charset the charset * @return the escaped string * * @throws URIException if the charset is not supported * * @see #encode */ public static String encodeWithinQuery(String unescaped, String charset) throws URIException { return encode(unescaped, URI.allowed_within_query, charset); } /** * Escape and encode a string regarded as the query component of an URI with * the default protocol charset. * When a query string is not misunderstood the reserved special characters * ("&", "=", "+", ",", and "$") within a query component, this method * is recommended to use in encoding the whole query. * * @param unescaped an unescaped string * @return the escaped string * * @throws URIException if the default protocol charset is not supported * * @see URI#getDefaultProtocolCharset * @see #encode */ public static String encodeQuery(String unescaped) throws URIException { return encodeQuery(unescaped, URI.getDefaultProtocolCharset()); } /** * Escape and encode a string regarded as the query component of an URI with * a given charset. * When a query string is not misunderstood the reserved special characters * ("&", "=", "+", ",", and "$") within a query component, this method * is recommended to use in encoding the whole query. * * @param unescaped an unescaped string * @param charset the charset * @return the escaped string * * @throws URIException if the charset is not supported * * @see #encode */ public static String encodeQuery(String unescaped, String charset) throws URIException { return encode(unescaped, URI.allowed_query, charset); } /** * Escape and encode a given string with allowed characters not to be * escaped and the default protocol charset. * * @param unescaped a string * @param allowed allowed characters not to be escaped * @return the escaped string * * @throws URIException if the default protocol charset is not supported * * @see URI#getDefaultProtocolCharset */ public static String encode(String unescaped, BitSet allowed) throws URIException { return encode(unescaped, allowed, URI.getDefaultProtocolCharset()); } /** * Escape and encode a given string with allowed characters not to be * escaped and a given charset. * * @param unescaped a string * @param allowed allowed characters not to be escaped * @param charset the charset * @return the escaped string */ public static String encode(String unescaped, BitSet allowed, String charset) throws URIException { byte[] rawdata = URLCodec.encodeUrl(allowed, EncodingUtil.getBytes(unescaped, charset)); return EncodingUtil.getAsciiString(rawdata); } /** * Unescape and decode a given string regarded as an escaped string with the * default protocol charset. * * @param escaped a string * @return the unescaped string * * @throws URIException if the string cannot be decoded (invalid) * * @see URI#getDefaultProtocolCharset */ public static String decode(String escaped) throws URIException { try { byte[] rawdata = URLCodec.decodeUrl(EncodingUtil.getAsciiBytes(escaped)); return EncodingUtil.getString(rawdata, URI.getDefaultProtocolCharset()); } catch (DecoderException e) { throw new URIException(e.getMessage()); } } /** * Unescape and decode a given string regarded as an escaped string. * * @param escaped a string * @param charset the charset * @return the unescaped string * * @throws URIException if the charset is not supported * * @see Coder#decode */ public static String decode(String escaped, String charset) throws URIException { return Coder.decode(escaped.toCharArray(), charset); } // ---------------------------------------------------------- Inner classes /** * The basic and internal utility for URI escape and character encoding and * decoding. * * @deprecated use org.apache.commons.codec.net.URLCodec */ protected static class Coder extends URI { /** * Escape and encode a given string with allowed characters not to be * escaped. * * @param unescapedComponent an unescaped component * @param allowed allowed characters not to be escaped * @param charset the charset to encode * @return the escaped and encoded string * * @throws URIException if the charset is not supported * * @deprecated use org.apache.commons.codec.net.URLCodec */ public static char[] encode(String unescapedComponent, BitSet allowed, String charset) throws URIException { return URI.encode(unescapedComponent, allowed, charset); } /** * Unescape and decode a given string. * * @param escapedComponent an being-unescaped component * @param charset the charset to decode * @return the escaped and encoded string * * @throws URIException if the charset is not supported * * @deprecated use org.apache.commons.codec.net.URLCodec */ public static String decode(char[] escapedComponent, String charset) throws URIException { return URI.decode(escapedComponent, charset); } /** * Verify whether a given string is escaped or not * * @param original given characters * @return true if the given character array is 7 bit ASCII-compatible. */ public static boolean verifyEscaped(char[] original) { for (int i = 0; i < original.length; i++) { int c = original[i]; if (c > 128) { return false; } else if (c == '%') { if (Character.digit(original[++i], 16) == -1 || Character.digit(original[++i], 16) == -1) { return false; } } } return true; } /** * Replace from a given character to given character in an array order * for a given string. * * @param original a given string * @param from a replacing character array * @param to a replaced character array * @return the replaced string */ public static String replace(String original, char[] from, char[] to) { for (int i = from.length; i > 0; --i) { original = replace(original, from[i], to[i]); } return original; } /** * Replace from a given character to given character for a given string. * * @param original a given string * @param from a replacing character array * @param to a replaced character array * @return the replaced string */ public static String replace(String original, char from, char to) { StringBuffer result = new StringBuffer(original.length()); int at, saved = 0; do { at = original.indexOf(from); if (at >= 0) { result.append(original.substring(0, at)); result.append(to); } else { result.append(original.substring(saved)); } saved = at; } while (at >= 0); return result.toString(); } } } commons-httpclient-3.1/src/java/org/apache/commons/httpclient/util/package.html100644 0 0 427 10661532626 25134 0ustar 0 0 Package Documentation for org.apache.commons.httpclient.util Provides some utility classes for use by HttpClient. @since 2.0 commons-httpclient-3.1/src/resources/META-INF/NOTICE.txt100644 0 0 270 10661532626 20004 0ustar 0 0 Apache Jakarta HttpClient Copyright 1999-2007 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). commons-httpclient-3.1/src/resources/META-INF/README.txt100644 0 0 504 10661532626 17760 0ustar 0 0 Jakarta HttpClient =========================== Welcome to the HttpClient component of the Jakarta HttpComponents project. Visit us online at http://jakarta.apache.org/httpcomponents/index.html for more information. Visit http://jakarta.apache.org/httpcomponents/status.html for the status of the project. commons-httpclient-3.1/src/test/org/apache/commons/httpclient/AccessibleHttpConnectionManager.java100644 0 0 3471 10661532626 31031 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/AccessibleHttpConnectionManager.java,v 1.1 2004/10/16 22:40:08 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * A simple connection manager that provides access to the connection used. */ public class AccessibleHttpConnectionManager extends SimpleHttpConnectionManager { public AccessibleHttpConnectionManager() { } public HttpConnection getConection() { return httpConnection; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/EchoService.java100644 0 0 4722 10661532626 25020 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/EchoService.java,v 1.2 2004/11/20 17:56:39 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * A service that echos the request body. */ public class EchoService implements HttpService { public EchoService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); if (request.containsHeader("Content-Length")) { response.addHeader(request.getFirstHeader("Content-Length")); } if (request.containsHeader("Content-Type")) { response.addHeader(request.getFirstHeader("Content-Type")); } response.setBodyString(request.getBodyString()); return true; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/ExecuteMethodThread.java100644 0 0 5035 10661532626 26512 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/ExecuteMethodThread.java,v 1.2 2004/02/22 18:08:49 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; /** * Executes a method from a new thread. * * @author Michael Becke */ class ExecuteMethodThread extends Thread { private HttpMethod method; private HttpClient client; private Exception exception; public ExecuteMethodThread(HttpMethod method, HttpClient client) { this.method = method; this.client = client; } public void run() { try { client.executeMethod(method); method.getResponseBodyAsString(); } catch (Exception e) { this.exception = e; } finally { method.releaseConnection(); } } /** * @return HttpMethod */ public HttpMethod getMethod() { return method; } /** * Gets the exception that occurred when executing the method. * * @return an Exception or null if no exception occurred */ public Exception getException() { return exception; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/FakeHttpMethod.java100644 0 0 4702 10661532627 25467 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/FakeHttpMethod.java,v 1.2 2004/10/31 14:04:13 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; /** * For test-nohost testing purposes only. * * @author Jeff Dever */ public class FakeHttpMethod extends HttpMethodBase{ public FakeHttpMethod(){ super(); } public FakeHttpMethod(String path){ super(path); } public String getName() { return "Simple"; } public void addResponseHeader(final Header header) { getResponseHeaderGroup().addHeader(header); } public String generateRequestLine( final HttpConnection connection ,final HttpVersion version) { if (connection == null) { throw new IllegalArgumentException("Connection may not be null"); } if (version == null) { throw new IllegalArgumentException("HTTP version may not be null"); } return HttpMethodBase.generateRequestLine(connection, this.getName(), this.getPath(), this.getQueryString(), version.toString()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/FeedbackService.java100644 0 0 5700 10661532626 25623 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/FeedbackService.java,v 1.1 2004/11/20 17:56:39 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.StringWriter; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.RequestLine; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; public class FeedbackService implements HttpService { public FeedbackService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine requestline = request.getRequestLine(); HttpVersion httpversion = requestline.getHttpVersion(); StringWriter buffer = new StringWriter(100); buffer.write("Method type: "); buffer.write(requestline.getMethod()); buffer.write("\r\n"); buffer.write("Requested resource: "); buffer.write(requestline.getUri()); buffer.write("\r\n"); buffer.write("Protocol version: "); buffer.write(httpversion.toString()); buffer.write("\r\n"); String requestbody = request.getBodyString(); if (requestbody != null && !requestbody.equals("")) { buffer.write("\r\n"); buffer.write("Request body: "); buffer.write(requestbody); buffer.write("\r\n"); } response.setStatusLine(httpversion, HttpStatus.SC_OK); response.setBodyString(buffer.toString()); return true; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/HttpClientTestBase.java100644 0 0 11610 10661532626 26344 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/HttpClientTestBase.java,v 1.7 2004/11/07 12:31:42 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.httpclient.server.SimpleHttpServer; import org.apache.commons.httpclient.server.SimplePlainSocketFactory; import org.apache.commons.httpclient.server.SimpleProxy; import org.apache.commons.httpclient.server.SimpleSocketFactory; import org.apache.commons.httpclient.ssl.SimpleSSLSocketFactory; import org.apache.commons.httpclient.ssl.SimpleSSLTestProtocolSocketFactory; /** * Base class for test cases using * {@link org.apache.commons.httpclient.server.SimpleHttpServer} based * testing framework. * * @author Oleg Kalnichevski * * @version $Id: HttpClientTestBase.java 480424 2006-11-29 05:56:49Z bayard $ */ public class HttpClientTestBase extends TestCase { protected HttpClient client = null; protected SimpleHttpServer server = null; protected SimpleProxy proxy = null; private boolean useProxy = false; private boolean useSSL = false; // ------------------------------------------------------------ Constructor public HttpClientTestBase(final String testName) throws IOException { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { HttpClientTestBase.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(HttpClientTestBase.class); } public void setUseProxy(boolean useProxy) { this.useProxy = useProxy; } public void setUseSSL(boolean b) { this.useSSL = b; } public boolean isUseSSL() { return this.useSSL; } // ------------------------------------------------- TestCase setup/shutdown public void setUp() throws IOException { // Configure socket factories SimpleSocketFactory serversocketfactory = null; Protocol testhttp = null; if (this.useSSL) { serversocketfactory = new SimpleSSLSocketFactory(); testhttp = new Protocol("https", (ProtocolSocketFactory)new SimpleSSLTestProtocolSocketFactory(), 443); } else { serversocketfactory = new SimplePlainSocketFactory(); testhttp = Protocol.getProtocol("http"); } this.server = new SimpleHttpServer(serversocketfactory, 0); // use arbitrary port this.server.setTestname(getName()); this.client = new HttpClient(); this.client.getHostConfiguration().setHost( this.server.getLocalAddress(), this.server.getLocalPort(), testhttp); if (this.useProxy) { this.proxy = new SimpleProxy(); client.getHostConfiguration().setProxy( proxy.getLocalAddress(), proxy.getLocalPort()); } } public void tearDown() throws IOException { this.client = null; this.server.destroy(); this.server = null; if (proxy != null) { proxy.destroy(); proxy = null; } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/NoHostHttpConnectionManager.java100644 0 0 12163 10661532626 30224 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/NoHostHttpConnectionManager.java,v 1.9 2004/10/31 13:53:03 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; /** */ public class NoHostHttpConnectionManager implements HttpConnectionManager { private HttpConnection connection; private boolean connectionReleased = false; private HttpConnectionManagerParams params = new HttpConnectionManagerParams(); public NoHostHttpConnectionManager() { super(); } /** * This method currently does nothing. */ public void closeIdleConnections(long idleTimeout) { } /** * @return */ public boolean isConnectionReleased() { return connectionReleased; } /** * @param connection */ public void setConnection(HttpConnection connection) { this.connection = connection; connection.setHttpConnectionManager(this); connection.getParams().setDefaults(this.params); } public HttpConnection getConnection(HostConfiguration hostConfiguration) { // make sure the host and proxy are correct for this connection // close it and set the values if they are not if (!hostConfiguration.hostEquals(connection) || !hostConfiguration.proxyEquals(connection)) { if (connection.isOpen()) { connection.close(); } connection.setHost(hostConfiguration.getHost()); connection.setPort(hostConfiguration.getPort()); connection.setProtocol(hostConfiguration.getProtocol()); connection.setLocalAddress(hostConfiguration.getLocalAddress()); connection.setProxyHost(hostConfiguration.getProxyHost()); connection.setProxyPort(hostConfiguration.getProxyPort()); } else { finishLastResponse(connection); } connectionReleased = false; return connection; } /** * @deprecated */ public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout) throws HttpException { return getConnection(hostConfiguration); } public HttpConnection getConnectionWithTimeout( HostConfiguration hostConfiguration, long timeout) throws ConnectionPoolTimeoutException { return getConnection(hostConfiguration); } public void releaseConnection(HttpConnection conn) { if (conn != connection) { throw new IllegalStateException("Unexpected close on a different connection."); } connectionReleased = true; finishLastResponse(connection); } /** * Since the same connection is about to be reused, make sure the * previous request was completely processed, and if not * consume it now. * @param conn The connection */ static void finishLastResponse(HttpConnection conn) { InputStream lastResponse = conn.getLastResponseInputStream(); if (lastResponse != null) { conn.setLastResponseInputStream(null); try { lastResponse.close(); } catch (IOException ioe) { //FIXME: badness - close to force reconnect. conn.close(); } } } public HttpConnectionManagerParams getParams() { return this.params; } public void setParams(final HttpConnectionManagerParams params) { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } this.params = params; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/NoncompliantHeadMethod.java100644 0 0 3702 10661532627 27203 0ustar 0 0 /* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.methods.HeadMethod; /** * HTTP GET methid intended to simulate side-effects of * interaction with non-compiant HTTP servers or proxies * * @author Oleg Kalnichevski */ public class NoncompliantHeadMethod extends HeadMethod { public NoncompliantHeadMethod(){ super(); } public NoncompliantHeadMethod(String uri) { super(uri); } /** * Expect HTTP HEAD but perform HTTP GET instead in order to * simulate the behaviour of a non-compliant HTTP server sending * body content in response to HTTP HEAD request * */ public String getName() { return "GET"; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/NoncompliantPostMethod.java100644 0 0 5330 10661532626 27265 0ustar 0 0 /* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.IOException; import org.apache.commons.httpclient.methods.PostMethod; /** * HTTP POST methid intended to simulate side-effects of * interaction with non-compiant HTTP servers or proxies * * @author Oleg Kalnichevski */ public class NoncompliantPostMethod extends PostMethod { public NoncompliantPostMethod(){ super(); } public NoncompliantPostMethod(String uri) { super(uri); } /** * NoncompliantPostMethod class skips "Expect: 100-continue" * header when sending request headers to an HTTP server. * *

      * That makes the server expect the request body to follow * immediately after the request head. The HTTP server does not * send status code 100 expected by the client. The client should * be able to recover gracefully by sending the request body * after a defined timeout without having received "continue" * code. *

      */ protected void writeRequestHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException { addRequestHeaders(state, conn); Header[] headers = getRequestHeaders(); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; // Write all the headers but "Expect" if (!header.getName().equalsIgnoreCase("Expect") ) { conn.print(header.toExternalForm(), "US-ASCII"); } } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/ProxyTestDecorator.java100644 0 0 5356 10661532627 26452 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/ProxyTestDecorator.java,v 1.1 2004/11/01 02:21:15 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.util.Enumeration; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; /** * A TestDecorator that configures instances of HttpClientTestBase to use * a proxy server. */ public class ProxyTestDecorator extends TestSetup { /** * Iterates through all test cases included in the suite and adds * copies of them modified to use a proxy server. * @param suite */ public static void addTests(TestSuite suite) { TestSuite ts2 = new TestSuite(); addTest(ts2, suite); suite.addTest(ts2); } private static void addTest(TestSuite suite, Test t) { if (t instanceof HttpClientTestBase) { suite.addTest(new ProxyTestDecorator((HttpClientTestBase) t)); } else if (t instanceof TestSuite) { Enumeration en = ((TestSuite) t).tests(); while (en.hasMoreElements()) { addTest(suite, (Test) en.nextElement()); } } } public ProxyTestDecorator(HttpClientTestBase test) { super(test); } protected void setUp() throws Exception { HttpClientTestBase base = (HttpClientTestBase) fTest; base.setUseProxy(true); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestAll.java100644 0 0 11133 10661532627 24204 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestAll.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.auth.TestAuthAll; import org.apache.commons.httpclient.cookie.TestCookieAll; import org.apache.commons.httpclient.params.TestParamsAll; import junit.framework.*; /** * @author Remy Maucherat * @author Rodney Waldhoff * @version $Id: TestAll.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); // Fundamentals suite.addTest(TestHttpMethodFundamentals.suite()); suite.addTest(TestHttpStatus.suite()); suite.addTest(TestStatusLine.suite()); suite.addTest(TestRequestLine.suite()); suite.addTest(TestHeader.suite()); suite.addTest(TestHeaderElement.suite()); suite.addTest(TestHeaderOps.suite()); suite.addTest(TestResponseHeaders.suite()); suite.addTest(TestRequestHeaders.suite()); suite.addTest(TestStreams.suite()); suite.addTest(TestParameterParser.suite()); suite.addTest(TestParameterFormatter.suite()); suite.addTest(TestNVP.suite()); suite.addTest(TestMethodCharEncoding.suite()); suite.addTest(TestHttpVersion.suite()); suite.addTest(TestEffectiveHttpVersion.suite()); suite.addTest(TestHttpParser.suite()); suite.addTest(TestBadContentLength.suite()); suite.addTest(TestEquals.suite()); suite.addTest(TestQueryParameters.suite()); // Exceptions suite.addTest(TestExceptions.suite()); // HTTP state management suite.addTest(TestHttpState.suite()); suite.addTest(TestCookieAll.suite()); // Authentication suite.addTest(TestCredentials.suite()); suite.addTest(TestAuthAll.suite()); // Redirects suite.addTest(TestRedirects.suite()); // Connection management suite.addTest(TestHttpConnection.suite()); suite.addTest(TestHttpConnectionManager.suite()); suite.addTest(TestConnectionPersistence.suite()); suite.addTest(TestIdleConnectionTimeout.suite()); suite.addTest(TestMethodAbort.suite()); // Preferences suite.addTest(TestParamsAll.suite()); suite.addTest(TestVirtualHost.suite()); suite.addTest(TestHostConfiguration.suite()); // URIs suite.addTest(TestURI.suite()); suite.addTest(TestURIUtil.suite()); suite.addTest(TestURIUtil2.suite()); // Method specific suite.addTest(TestEntityEnclosingMethod.suite()); suite.addTest(TestPostParameterEncoding.suite()); suite.addTest(TestPostMethod.suite()); suite.addTest(TestPartsNoHost.suite()); suite.addTest(TestMultipartPost.suite()); // Non compliant behaviour suite.addTest(TestNoncompliant.suite()); // Proxy suite.addTest(TestProxy.suite()); suite.addTest(TestProxyWithRedirect.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = { TestAll.class.getName() }; junit.textui.TestRunner.main(testCaseName); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestBadContentLength.java100644 0 0 16500 10661532627 26662 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestBadContentLength.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.server.HttpRequestHandler; import org.apache.commons.httpclient.server.RequestLine; import org.apache.commons.httpclient.server.ResponseWriter; import org.apache.commons.httpclient.server.SimpleHttpServer; import org.apache.commons.httpclient.server.SimpleHttpServerConnection; import org.apache.commons.httpclient.server.SimpleRequest; /** * Tests HttpClient's behaviour when receiving more response data than expected. *

      * A very simple HTTP Server will be setup on a free port during testing, which * returns an incorrect response Content-Length, sending surplus response data, * which may contain malicious/fake response headers. *

      * * @author Christian Kohlschuetter * @version $Id: TestBadContentLength.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestBadContentLength extends TestCase { private HttpClient client = null; private SimpleHttpServer server = null; // ------------------------------------------------------------ Constructor public TestBadContentLength(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestBadContentLength.class.getName()}; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestBadContentLength.class); } // ----------------------------------------------------------- Test Methods public void setUp() throws IOException { client = new HttpClient(); server = new SimpleHttpServer(); // use arbitrary port server.setTestname(getName()); server.setRequestHandler(new MyHttpRequestHandler()); } public void tearDown() throws IOException { client = null; server.destroy(); } /** * HttpClient connects to the test server and performs two subsequent * requests to the same URI in lenient mode. * * Expected behavior: * For both requests, status code 200 and a response body of "12345" * should be returned. * * @throws IOException */ public void test1Lenient() throws IOException { client.getParams().makeLenient(); GetMethod m = new GetMethod("http://localhost:" + server.getLocalPort() + "/"); client.executeMethod(m); assertEquals(200, m.getStatusCode()); assertEquals("12345", m.getResponseBodyAsString()); m = new GetMethod("http://localhost:" + server.getLocalPort() + "/"); client.executeMethod(m); assertEquals(200, m.getStatusCode()); assertEquals("12345", m.getResponseBodyAsString()); m.releaseConnection(); } /** * HttpClient connects to the test server and performs two subsequent * requests to the same URI in strict mode. *

      * The first response body will be read with getResponseBodyAsString(), * which returns null if an error occured. *

      *

      * The second response body will be read using an InputStream, which * throws an IOException if something went wrong. *

      * Expected behavior: * For both requests, status code 200 should be returned.
      * For request 1, a null response body should be returned.
      * For request 2, a {@link ProtocolException} is expected. * * @throws IOException */ public void test1Strict() throws IOException { client.getParams().makeStrict(); GetMethod m = new GetMethod("http://localhost:" + server.getLocalPort() + "/"); client.executeMethod(m); assertEquals(200, m.getStatusCode()); assertEquals("12345", m.getResponseBodyAsString()); m = new GetMethod("http://localhost:" + server.getLocalPort() + "/"); client.executeMethod(m); assertEquals(200, m.getStatusCode()); InputStream in = m.getResponseBodyAsStream(); while (in.read() != -1) { } m.releaseConnection(); } public void enableThisTestForDebuggingOnly() throws InterruptedException { while (server.isRunning()) { Thread.sleep(100); } } private class MyHttpRequestHandler implements HttpRequestHandler { private int requestNo = 0; public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { RequestLine requestLine = request.getRequestLine(); ResponseWriter out = conn.getWriter(); if ("GET".equals(requestLine.getMethod()) && "/".equals(requestLine.getUri())) { requestNo++; out.println("HTTP/1.1 200 OK"); out.println("Content-Type: text/html"); out.println("Content-Length: 5"); out.println("Connection: keep-alive"); out.println(); out.println("12345"); // send exactly 5 bytes // and some more garbage! out.println("AND SOME MORE\r\nGARBAGE!"); out.println("HTTP/1.0 404 Not Found"); out.println("Content-Type: text/plain"); out.println(""); out.println("THIS-IS-A-FAKE-RESPONSE!"); out.flush(); // process max. 2 subsequents requests per connection if (requestNo < 2) { conn.setKeepAlive(true); } } return true; } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestConnectionPersistence.java100644 0 0 22700 10661532627 30002 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestConnectionPersistence.java,v 1.2 2004/12/20 11:42:30 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient; import java.io.IOException; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.server.HttpRequestHandler; import org.apache.commons.httpclient.server.SimpleHttpServerConnection; import org.apache.commons.httpclient.server.SimpleProxy; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; import junit.framework.Test; import junit.framework.TestSuite; /** * Connection persistence tests * * @author Oleg Kalnichevski * * @version $Id: TestConnectionPersistence.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestConnectionPersistence extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestConnectionPersistence(final String testName) throws IOException { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestConnectionPersistence.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestConnectionPersistence.class); } // ----------------------------------------------------------- Test Methods public void testConnPersisenceHTTP10() throws Exception { this.server.setHttpService(new EchoService()); AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager(); this.client.getParams().setVersion(HttpVersion.HTTP_1_0); this.client.setHttpConnectionManager(connman); PostMethod httppost = new PostMethod("/test/"); httppost.setRequestEntity(new StringRequestEntity("stuff", null, null)); try { this.client.executeMethod(httppost); } finally { httppost.releaseConnection(); } assertFalse(connman.getConection().isOpen()); httppost = new PostMethod("/test/"); httppost.setRequestEntity(new StringRequestEntity("more stuff", null, null)); try { this.client.executeMethod(httppost); } finally { httppost.releaseConnection(); } assertFalse(connman.getConection().isOpen()); } public void testConnPersisenceHTTP11() throws Exception { this.server.setHttpService(new EchoService()); AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager(); this.client.getParams().setVersion(HttpVersion.HTTP_1_1); this.client.setHttpConnectionManager(connman); PostMethod httppost = new PostMethod("/test/"); httppost.setRequestEntity(new StringRequestEntity("stuff", null, null)); try { this.client.executeMethod(httppost); } finally { httppost.releaseConnection(); } assertTrue(connman.getConection().isOpen()); httppost = new PostMethod("/test/"); httppost.setRequestEntity(new StringRequestEntity("more stuff", null, null)); try { this.client.executeMethod(httppost); } finally { httppost.releaseConnection(); } assertTrue(connman.getConection().isOpen()); } public void testConnClose() throws Exception { this.server.setHttpService(new EchoService()); AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager(); this.client.getParams().setVersion(HttpVersion.HTTP_1_1); this.client.setHttpConnectionManager(connman); PostMethod httppost = new PostMethod("/test/"); httppost.setRequestEntity(new StringRequestEntity("stuff", null, null)); try { this.client.executeMethod(httppost); } finally { httppost.releaseConnection(); } assertTrue(connman.getConection().isOpen()); httppost = new PostMethod("/test/"); httppost.setRequestHeader("Connection", "close"); httppost.setRequestEntity(new StringRequestEntity("more stuff", null, null)); try { this.client.executeMethod(httppost); } finally { httppost.releaseConnection(); } assertFalse(connman.getConection().isOpen()); } public void testConnKeepAlive() throws Exception { this.server.setHttpService(new EchoService()); AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager(); this.client.getParams().setVersion(HttpVersion.HTTP_1_0); this.client.setHttpConnectionManager(connman); PostMethod httppost = new PostMethod("/test/"); httppost.setRequestEntity(new StringRequestEntity("stuff", null, null)); try { this.client.executeMethod(httppost); } finally { httppost.releaseConnection(); } assertFalse(connman.getConection().isOpen()); httppost = new PostMethod("/test/"); httppost.setRequestHeader("Connection", "keep-alive"); httppost.setRequestEntity(new StringRequestEntity("more stuff", null, null)); try { this.client.executeMethod(httppost); } finally { httppost.releaseConnection(); } assertTrue(connman.getConection().isOpen()); } public void testRequestConnClose() throws Exception { this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { // Make sure the request if fully consumed request.getBodyBytes(); SimpleResponse response = new SimpleResponse(); response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK); response.setBodyString("stuff back"); conn.setKeepAlive(true); conn.writeResponse(response); return true; } }); AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager(); this.client.getParams().setVersion(HttpVersion.HTTP_1_0); this.client.setHttpConnectionManager(connman); PostMethod httppost = new PostMethod("/test/"); httppost.setRequestHeader("Connection", "close"); httppost.setRequestEntity(new StringRequestEntity("stuff", null, null)); try { this.client.executeMethod(httppost); } finally { httppost.releaseConnection(); } assertFalse(connman.getConection().isOpen()); } public void testProxyConnClose() throws Exception { this.server.setHttpService(new EchoService()); this.proxy = new SimpleProxy(); this.client.getHostConfiguration().setProxy( proxy.getLocalAddress(), proxy.getLocalPort()); AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager(); this.client.setHttpConnectionManager(connman); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertTrue(connman.getConection().isOpen()); httpget = new GetMethod("/test/"); httpget.setRequestHeader("Proxy-Connection", "Close"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertFalse(connman.getConection().isOpen()); assertEquals("Close", httpget.getRequestHeader("Proxy-Connection").getValue()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestCredentials.java100644 0 0 11451 10661532626 25733 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestCredentials.java,v 1.1 2004/10/31 13:46:54 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit tests for {@link Credentials}. * * @author Rodney Waldhoff * @author Jeff Dever * @version $Id: TestCredentials.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestCredentials extends TestCase { // ------------------------------------------------------------ Constructor public TestCredentials(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestCredentials.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestCredentials.class); } public void testCredentialConstructors() { try { new UsernamePasswordCredentials(null, null); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } try { new NTCredentials("user", "password", null, null); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } try { new NTCredentials("user", "password", "host", null); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } NTCredentials creds = new NTCredentials("user", null, "host", "domain"); assertNotNull(creds.getUserName()); assertNull(creds.getPassword()); assertNotNull(creds.getDomain()); assertNotNull(creds.getHost()); } /** * Verifies that credentials report equal when they should. */ public void testCredentialEquals() { Credentials creds1 = new UsernamePasswordCredentials("user1", "password1"); Credentials creds1Again = new UsernamePasswordCredentials("user1", "password1"); Credentials creds2 = new UsernamePasswordCredentials("user2", "password2"); Credentials creds3 = new UsernamePasswordCredentials("user3", null); Credentials creds3Again = new UsernamePasswordCredentials("user3", null); assertEquals(creds1, creds1Again); assertNotSame(creds1, creds2); assertEquals(creds3, creds3Again); Credentials ntCreds1 = new NTCredentials("user1", "password1", "host1", "domain1"); Credentials ntCreds1Again = new NTCredentials("user1", "password1", "host1", "domain1"); Credentials ntCreds2 = new NTCredentials("user1", "password2", "host1", "domain1"); Credentials ntCreds3 = new NTCredentials("user1", "password1", "host2", "domain1"); Credentials ntCreds4 = new NTCredentials("user1", "password1", "host1", "domain2"); assertEquals(ntCreds1, ntCreds1Again); assertNotSame(ntCreds1, creds1); assertNotSame(creds1, ntCreds1); assertNotSame(ntCreds1, ntCreds2); assertNotSame(ntCreds1, ntCreds3); assertNotSame(ntCreds1, ntCreds4); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestEffectiveHttpVersion.java100644 0 0 12652 10661532626 27610 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestEffectiveHttpVersion.java,v 1.4 2004/10/31 14:42:59 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.IOException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; /** * HTTP protocol versioning tests. * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class TestEffectiveHttpVersion extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestEffectiveHttpVersion(final String testName) throws IOException { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestEffectiveHttpVersion.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestEffectiveHttpVersion.class); } public void testClientLevelHttpVersion() throws IOException { this.server.setHttpService(new EchoService()); HttpVersion testver = new HttpVersion(1, 10); this.client.getParams().setVersion(testver); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertEquals(testver, httpget.getEffectiveVersion()); } public void testMethodLevelHttpVersion() throws IOException { this.server.setHttpService(new EchoService()); HttpVersion globalver = new HttpVersion(1, 10); HttpVersion testver1 = new HttpVersion(1, 11); HttpVersion testver2 = new HttpVersion(1, 12); this.client.getParams().setVersion(globalver); GetMethod httpget1 = new GetMethod("/test/"); httpget1.getParams().setVersion(testver1); try { this.client.executeMethod(httpget1); } finally { httpget1.releaseConnection(); } assertEquals(testver1, httpget1.getEffectiveVersion()); GetMethod httpget2 = new GetMethod("/test/"); httpget2.getParams().setVersion(testver2); try { this.client.executeMethod(httpget2); } finally { httpget2.releaseConnection(); } assertEquals(testver2, httpget2.getEffectiveVersion()); GetMethod httpget3 = new GetMethod("/test/"); try { this.client.executeMethod(httpget3); } finally { httpget3.releaseConnection(); } assertEquals(globalver, httpget3.getEffectiveVersion()); } public void testHostLevelHttpVersion() throws IOException { this.server.setHttpService(new EchoService()); HttpVersion testver = new HttpVersion(1, 11); HttpVersion hostver = new HttpVersion(1, 12); this.client.getParams().setVersion(testver); GetMethod httpget1 = new GetMethod("/test/"); httpget1.getParams().setVersion(testver); HostConfiguration hostconf = new HostConfiguration(); hostconf.setHost(this.server.getLocalAddress(), this.server.getLocalPort(), "http"); try { this.client.executeMethod(hostconf, httpget1); } finally { httpget1.releaseConnection(); } assertEquals(testver, httpget1.getEffectiveVersion()); GetMethod httpget2 = new GetMethod("/test/"); hostconf.setHost(this.server.getLocalAddress(), this.server.getLocalPort(), "http"); hostconf.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, hostver); try { this.client.executeMethod(hostconf, httpget2); } finally { httpget2.releaseConnection(); } assertEquals(hostver, httpget2.getEffectiveVersion()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestEntityEnclosingMethod.java100644 0 0 35616 10661532627 27767 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestEntityEnclosingMethod.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.server.AuthRequestHandler; import org.apache.commons.httpclient.server.HttpRequestHandlerChain; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.HttpServiceHandler; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * Tests specific to entity enclosing methods. * * @author Oleg Kalnichevski * @version $Id: TestEntityEnclosingMethod.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestEntityEnclosingMethod extends HttpClientTestBase { public TestEntityEnclosingMethod(String testName) throws IOException { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(TestEntityEnclosingMethod.class); return suite; } public static void main(String args[]) { String[] testCaseName = { TestEntityEnclosingMethod.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------------------ Tests public void testEnclosedEntityAutoLength() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals(inputstr, body); assertNull(method.getRequestHeader("Transfer-Encoding")); assertNotNull(method.getRequestHeader("Content-Length")); assertEquals(input.length, Integer.parseInt( method.getRequestHeader("Content-Length").getValue())); } finally { method.releaseConnection(); } } public void testEnclosedEntityExplicitLength() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, 14); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals("This is a test", body); assertNull(method.getRequestHeader("Transfer-Encoding")); assertNotNull(method.getRequestHeader("Content-Length")); assertEquals(14, Integer.parseInt( method.getRequestHeader("Content-Length").getValue())); } finally { method.releaseConnection(); } } public void testEnclosedEntityChunked() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(true); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals(inputstr, body); assertNotNull(method.getRequestHeader("Transfer-Encoding")); assertNull(method.getRequestHeader("Content-Length")); } finally { method.releaseConnection(); } } public void testEnclosedEntityChunkedHTTP1_0() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(true); method.getParams().setVersion(HttpVersion.HTTP_1_0); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } finally { method.releaseConnection(); } } public void testEnclosedEntityRepeatable() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new EchoService())); this.server.setRequestHandler(handlerchain); this.client.getState().setCredentials(AuthScope.ANY, creds); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals(inputstr, body); assertNull(method.getRequestHeader("Transfer-Encoding")); assertNotNull(method.getRequestHeader("Content-Length")); assertEquals(input.length, Integer.parseInt( method.getRequestHeader("Content-Length").getValue())); } finally { method.releaseConnection(); } } public void testEnclosedEntityNonRepeatable() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(true); UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new EchoService())); this.server.setRequestHandler(handlerchain); this.client.getState().setCredentials(AuthScope.ANY, creds); try { this.client.executeMethod(method); fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } finally { method.releaseConnection(); } } public void testEnclosedEntityNegativeLength() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, -14); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(false); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals(inputstr, body); assertNotNull(method.getRequestHeader("Transfer-Encoding")); assertNull(method.getRequestHeader("Content-Length")); } finally { method.releaseConnection(); } } public void testEnclosedEntityNegativeLengthHTTP1_0() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, -14); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(false); method.getParams().setVersion(HttpVersion.HTTP_1_0); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } finally { method.releaseConnection(); } } class RequestBodyStatsService implements HttpService { public RequestBodyStatsService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Content-Type", "text/plain")); StringBuffer buffer = new StringBuffer(); buffer.append("Request bosy stats:\r\n"); buffer.append("===================\r\n"); long l = request.getContentLength(); if (l >= 0) { buffer.append("Content-Length: "); buffer.append(l); buffer.append("\r\n"); } Header te = request.getFirstHeader("Transfer-Encoding"); if (te != null) { buffer.append("Content-Length: "); buffer.append(te.getValue()); buffer.append("\r\n"); } byte[] b = request.getBodyBytes(); if (b.length <= 0) { buffer.append("No body submitted\r\n"); } response.setBodyString(buffer.toString()); return true; } } public void testEmptyPostMethod() throws Exception { this.server.setHttpService(new RequestBodyStatsService()); PostMethod method = new PostMethod("/"); method.setRequestHeader("Content-Type", "text/plain"); this.client.executeMethod(method); assertEquals(200,method.getStatusLine().getStatusCode()); String response = method.getResponseBodyAsString(); assertNotNull(method.getRequestHeader("Content-Length")); assertTrue(response.indexOf("No body submitted") >= 0); method = new PostMethod("/"); method.setRequestHeader("Content-Type", "text/plain"); method.setRequestEntity(new StringRequestEntity("", null, null)); this.client.executeMethod(method); assertEquals(200,method.getStatusLine().getStatusCode()); assertNotNull(method.getRequestHeader("Content-Length")); response = method.getResponseBodyAsString(); assertTrue(response.indexOf("No body submitted") >= 0); method = new PostMethod("/"); method.setRequestHeader("Content-Type", "text/plain"); method.setContentChunked(true); this.client.executeMethod(method); assertEquals(200,method.getStatusLine().getStatusCode()); assertNotNull(method.getRequestHeader("Content-Length")); response = method.getResponseBodyAsString(); assertTrue(response.indexOf("No body submitted") >= 0); method = new PostMethod("/"); method.setRequestHeader("Content-Type", "text/plain"); method.setRequestEntity(new StringRequestEntity("", null, null)); method.setContentChunked(true); this.client.executeMethod(method); assertNull(method.getRequestHeader("Content-Length")); assertNotNull(method.getRequestHeader("Transfer-Encoding")); assertEquals(200,method.getStatusLine().getStatusCode()); response = method.getResponseBodyAsString(); assertTrue(response.indexOf("No body submitted") >= 0); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestEquals.java100644 0 0 7731 10661532626 24716 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestEquals.java,v 1.2 2004/02/22 18:08:49 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** */ public class TestEquals extends TestCase { public static Test suite() { return new TestSuite(TestEquals.class); } /** * */ public TestEquals() { super(); } /** * @param arg0 */ public TestEquals(String arg0) { super(arg0); } public void testProtocol() { Protocol p1 = new Protocol("test", new DefaultProtocolSocketFactory(), 123); Protocol p2 = new Protocol("test", new DefaultProtocolSocketFactory(), 123); assertTrue(p1.equals(p2)); assertTrue(p2.equals(p1)); } public void testProtocolSocketFactory() { ProtocolSocketFactory p1 = new DefaultProtocolSocketFactory(); ProtocolSocketFactory p2 = new DefaultProtocolSocketFactory(); assertTrue(p1.equals(p2)); assertTrue(p2.equals(p1)); p1 = new SSLProtocolSocketFactory(); p2 = new SSLProtocolSocketFactory(); assertTrue(p1.equals(p2)); assertTrue(p2.equals(p1)); } public void testProtocolSocketFactorySublass() { ProtocolSocketFactory factory1 = new DefaultProtocolSocketFactory(); ProtocolSocketFactory factory2 = new DefaultProtocolSocketFactory() {}; Protocol protocolA = new Protocol("http", factory1, 80); Protocol protocolB = new Protocol("http", factory2, 80); Protocol protocolC = new Protocol("http", factory2, 80); assertTrue(protocolB.equals(protocolC)); assertFalse(protocolA.equals(protocolB)); assertFalse(protocolB.equals(protocolA)); assertFalse(protocolA.equals(protocolB) != protocolB.equals(protocolA)); assertTrue(protocolB.equals(protocolB)); } public void testHostConfiguration() { HostConfiguration hc1 = new HostConfiguration(); hc1.setHost("http", 80, "http"); HostConfiguration hc2 = new HostConfiguration(); hc2.setHost("http", 80, "http"); assertTrue(hc1.equals(hc2)); assertTrue(hc2.equals(hc1)); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestExceptions.java100644 0 0 11737 10661532626 25626 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestExceptions.java,v 1.4 2004/03/25 20:37:20 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * * @author Laura Werner */ public class TestExceptions extends TestCase { // ------------------------------------------------------------ Constructor public TestExceptions(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestExceptions.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestExceptions.class); } /** Make sure that you can retrieve the "cause" from an HttpException */ public void testGetCause() { Exception aCause = new IOException("the cause"); try { throw new HttpException("http exception", aCause); } catch (HttpException e) { assertEquals("Retrieve cause from caught exception", e.getCause(), aCause); } } /** Make sure HttpConnection prints its stack trace to a PrintWriter properly */ public void testStackTraceWriter() { Exception aCause = new IOException("initial exception"); try { throw new HttpException("http exception", aCause); } catch (HttpException e) { // Get the stack trace printed into a string StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); e.printStackTrace(writer); writer.flush(); String stackTrace = stringWriter.toString(); // Do some validation on what got printed validateStackTrace(e, stackTrace); } } /** Make sure HttpConnection prints its stack trace to a PrintStream properly */ public void testStackTraceStream() { Exception aCause = new IOException("initial exception"); try { throw new HttpException("http exception", aCause); } catch (HttpException e) { // Get the stack trace printed into a string ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(byteStream); e.printStackTrace(stream); stream.flush(); String stackTrace = byteStream.toString(); // Assume default charset // Do some validation on what got printed validateStackTrace(e, stackTrace); } } /** * Make sure an HttpException stack trace has the right info in it. * This doesn't bother parsing the whole thing, just does some sanity checks. */ private void validateStackTrace(HttpException exception, String stackTrace) { assertTrue("Starts with exception string", stackTrace.startsWith(exception.toString())); Throwable cause = exception.getCause(); if (cause != null) { assertTrue("Contains 'cause'", stackTrace.toLowerCase().indexOf("cause") != -1); assertTrue("Contains cause.toString()", stackTrace.indexOf(cause.toString()) != -1); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestHeader.java100644 0 0 7015 10661532626 24647 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHeader.java,v 1.6 2004/02/22 18:08:49 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import junit.framework.*; /** * Simple tests for {@link NameValuePair}. * * @author Rodney Waldhoff * @version $Id: TestHeader.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestHeader extends TestNVP { // ------------------------------------------------------------ Constructor public TestHeader(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestHeader.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestHeader.class); } // ------------------------------------------------------ Protected Methods protected NameValuePair makePair() { return new Header(); } protected NameValuePair makePair(String name, String value) { return new Header(name,value); } // ----------------------------------------------------------- Test Methods public void testToExternalFormNull() { Header header = (Header)makePair(); assertEquals(": \r\n",header.toExternalForm()); } public void testToExternalFormNullName() { Header header = (Header)makePair(null,"value"); assertEquals(": value\r\n",header.toExternalForm()); } public void testToExternalFormNullValue() { Header header = (Header)makePair("name",null); assertEquals("name: \r\n",header.toExternalForm()); } public void testToExternalForm() { Header header = (Header)makePair("a","b"); assertEquals("a: b\r\n",header.toExternalForm()); } public void testEqualToNVP() { NameValuePair header = makePair("a","b"); NameValuePair pair = new NameValuePair("a","b"); assertTrue(header.equals(pair)); assertTrue(pair.equals(header)); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestHeaderElement.java100644 0 0 12712 10661532626 26201 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHeaderElement.java,v 1.7 2004/02/22 18:08:49 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import junit.framework.*; /** * Simple tests for {@link HeaderElement}. * * @author Rodney Waldhoff * @author B.C. Holmes * @author Park, Sung-Gu * @author oleg Kalnichevski * @version $Id: TestHeaderElement.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestHeaderElement extends TestNVP { // ------------------------------------------------------------ Constructor public TestHeaderElement(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestHeaderElement.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestHeaderElement.class); } // ------------------------------------------------------ Protected Methods protected NameValuePair makePair() { return new HeaderElement(); } protected NameValuePair makePair(String name, String value) { return new HeaderElement(name,value); } // ----------------------------------------------------------- Test Methods public void testOldMain() throws Exception { // this is derived from the old main method in HeaderElement String headerValue = "name1 = value1; name2; name3=\"value3\" , name4=value4; " + "name5=value5, name6= ; name7 = value7; name8 = \" value8\""; HeaderElement[] elements = HeaderElement.parseElements(headerValue); // there are 3 elements assertEquals(3,elements.length); // 1st element assertEquals("name1",elements[0].getName()); assertEquals("value1",elements[0].getValue()); // 1st element has 2 getParameters() assertEquals(2,elements[0].getParameters().length); assertEquals("name2",elements[0].getParameters()[0].getName()); assertEquals(null, elements[0].getParameters()[0].getValue()); assertEquals("name3",elements[0].getParameters()[1].getName()); assertEquals("value3",elements[0].getParameters()[1].getValue()); // 2nd element assertEquals("name4",elements[1].getName()); assertEquals("value4",elements[1].getValue()); // 2nd element has 1 parameter assertEquals(1,elements[1].getParameters().length); assertEquals("name5",elements[1].getParameters()[0].getName()); assertEquals("value5",elements[1].getParameters()[0].getValue()); // 3rd element assertEquals("name6",elements[2].getName()); assertEquals("",elements[2].getValue()); // 3rd element has 2 getParameters() assertEquals(2,elements[2].getParameters().length); assertEquals("name7",elements[2].getParameters()[0].getName()); assertEquals("value7",elements[2].getParameters()[0].getValue()); assertEquals("name8",elements[2].getParameters()[1].getName()); assertEquals(" value8",elements[2].getParameters()[1].getValue()); } public void testFringeCase1() throws Exception { String headerValue = "name1 = value1,"; HeaderElement[] elements = HeaderElement.parseElements(headerValue); assertEquals("Number of elements", 1, elements.length); } public void testFringeCase2() throws Exception { String headerValue = "name1 = value1, "; HeaderElement[] elements = HeaderElement.parseElements(headerValue); assertEquals("Number of elements", 1, elements.length); } public void testFringeCase3() throws Exception { String headerValue = ",, ,, ,"; HeaderElement[] elements = HeaderElement.parseElements(headerValue); assertEquals("Number of elements", 0, elements.length); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestHeaderOps.java100644 0 0 20571 10661532626 25353 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestHeaderOps.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.net.InetAddress; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * @author Rodney Waldhoff * @version $Id: TestHeaderOps.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestHeaderOps extends HttpClientTestBase { public TestHeaderOps(String testName) throws Exception { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(TestHeaderOps.class); return suite; } public static void main(String args[]) { String[] testCaseName = { TestHeaderOps.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------------------ Tests class HeaderDumpService implements HttpService { public HeaderDumpService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Content-Type", "text/plain")); response.addHeader(new Header("HeaderSetByServlet", "Yes")); StringBuffer buffer = new StringBuffer(); buffer.append("Request headers: \r\n"); for (Iterator i = request.getHeaderIterator(); i.hasNext(); ) { Header header = (Header) i.next(); buffer.append("name=\""); buffer.append(header.getName().toLowerCase()); buffer.append("\";value=\""); buffer.append(header.getValue()); buffer.append("\"\r\n"); } response.setBodyString(buffer.toString()); return true; } } /** * Test {@link HttpMethod#addRequestHeader}. */ public void testAddRequestHeader() throws Exception { this.server.setHttpService(new HeaderDumpService()); GetMethod method = new GetMethod("/"); method.setRequestHeader(new Header("addRequestHeader(Header)","True")); method.setRequestHeader("addRequestHeader(String,String)","Also True"); try { this.client.executeMethod(method); String s = method.getResponseBodyAsString(); assertTrue(s.indexOf("name=\"addrequestheader(header)\";value=\"True\"") >= 0); assertTrue(s.indexOf("name=\"addrequestheader(string,string)\";value=\"Also True\"") >= 0); } finally { method.releaseConnection(); } } /** * Test {@link HttpMethod#removeRequestHeader}. */ public void testRemoveRequestHeader() throws Exception { this.server.setHttpService(new HeaderDumpService()); GetMethod method = new GetMethod("/"); method.setRequestHeader(new Header("XXX-A-HEADER","true")); method.removeRequestHeader("XXX-A-HEADER"); try { this.client.executeMethod(method); String s = method.getResponseBodyAsString(); assertTrue(!(s.indexOf("xxx-a-header") >= 0)); } finally { method.releaseConnection(); } } /** * Test {@link HttpMethod#setRequestHeader}. */ public void testOverwriteRequestHeader() throws Exception { this.server.setHttpService(new HeaderDumpService()); GetMethod method = new GetMethod("/"); method.setRequestHeader(new Header("xxx-a-header","one")); method.setRequestHeader("XXX-A-HEADER","two"); try { this.client.executeMethod(method); String s = method.getResponseBodyAsString(); assertTrue(s.indexOf("name=\"xxx-a-header\";value=\"two\"") >= 0); } finally { method.releaseConnection(); } } /** * Test {@link HttpMethod#getResponseHeader}. */ public void testGetResponseHeader() throws Exception { this.server.setHttpService(new HeaderDumpService()); GetMethod method = new GetMethod("/"); try { this.client.executeMethod(method); Header h = new Header("HeaderSetByServlet","Yes"); assertEquals(h, method.getResponseHeader("headersetbyservlet")); } finally { method.releaseConnection(); } } /** * Test {@link HttpMethodBase.addHostRequestHeader}. */ public void testHostRequestHeader() throws Exception { this.server.setHttpService(new HeaderDumpService()); String hostname = this.server.getLocalAddress(); int port = this.server.getLocalPort(); InetAddress addr = InetAddress.getByName(hostname); String ip = addr.getHostAddress(); GetMethod get = new GetMethod("/"); // Open connection using IP. Host header should be sent // Note: RFC 2616 is somewhat unclear on whether a host should // be sent in this context - however, both Mozilla and IE send // the header for an IP address, instead of sending blank. this.client.getHostConfiguration().setHost(ip, port); try { this.client.executeMethod(get); Header hostHeader = get.getRequestHeader("Host"); assertTrue(hostHeader != null); if (port == Protocol.getProtocol("http").getDefaultPort()) { // no port information should be in the value assertTrue(hostHeader.getValue().equals(ip)); } else { assertTrue(hostHeader.getValue().equals(ip + ":" + port)); } } finally { get.releaseConnection(); } get = new GetMethod("/"); // Open connection using Host. Host header should // contain this value (this test will fail if DNS // is not available. Additionally, if the port is // something other that 80, then the port value // should also be present in the header. this.client.getHostConfiguration().setHost(hostname, port); try { this.client.executeMethod(get); Header hostHeader = get.getRequestHeader("Host"); assertTrue(hostHeader != null); if (port == Protocol.getProtocol("http").getDefaultPort()) { // no port information should be in the value assertTrue(hostHeader.getValue().equals(hostname)); } else { assertTrue(hostHeader.getValue().equals(hostname + ":" + port)); } } finally { get.releaseConnection(); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestHostConfiguration.java100644 0 0 21006 10661532626 27140 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestHostConfiguration.java $ * $Revision: 509577 $ * $Date: 2007-02-20 15:28:18 +0100 (Tue, 20 Feb 2007) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient; import java.io.IOException; import java.net.UnknownHostException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.server.SimpleProxy; /** * Tests basic HostConfiguration functionality. * * @author Oleg Kalnichevski * * @version $Id: TestHostConfiguration.java 509577 2007-02-20 14:28:18Z rolandw $ */ public class TestHostConfiguration extends HttpClientTestBase { public TestHostConfiguration(final String testName) throws IOException { super(testName); } public static Test suite() { return new TestSuite(TestHostConfiguration.class); } public static void main(String args[]) { String[] testCaseName = { TestHostConfiguration.class.getName() }; junit.textui.TestRunner.main(testCaseName); } public void testRelativeURLHitWithDefaultHost() throws IOException { this.server.setHttpService(new EchoService()); // Set default host this.client.getHostConfiguration().setHost( this.server.getLocalAddress(), this.server.getLocalPort(), Protocol.getProtocol("http")); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); } finally { httpget.releaseConnection(); } } public void testRelativeURLHitWithoutDefaultHost() throws IOException { this.server.setHttpService(new EchoService()); // reset default host configuration this.client.setHostConfiguration(new HostConfiguration()); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException expected) { } finally { httpget.releaseConnection(); } } public void testAbsoluteURLHitWithoutDefaultHost() throws IOException { this.server.setHttpService(new EchoService()); // reset default host configuration this.client.setHostConfiguration(new HostConfiguration()); GetMethod httpget = new GetMethod("http://" + this.server.getLocalAddress() + ":" + this.server.getLocalPort() + "/test/"); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); } finally { httpget.releaseConnection(); } } public void testAbsoluteURLOverridesClientDefaultHost() throws IOException { this.server.setHttpService(new EchoService()); // Somewhere out there in pampa this.client.getHostConfiguration().setHost("somewhere.outthere.in.pampa", 9999); GetMethod httpget = new GetMethod("http://" + this.server.getLocalAddress() + ":" + this.server.getLocalPort() + "/test/"); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); } finally { httpget.releaseConnection(); } httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); fail("UnknownHostException should have been thrown"); } catch (UnknownHostException expected) { } finally { httpget.releaseConnection(); } } public void testAbsoluteURLOverridesDefaultHostParam() throws IOException { this.proxy = new SimpleProxy(); this.server.setHttpService(new EchoService()); // reset default host configuration HostConfiguration hostconfig = new HostConfiguration(); hostconfig.setHost("somehwere.outthere.in.pampa", 9999); hostconfig.setProxy( this.proxy.getLocalAddress(), this.proxy.getLocalPort()); GetMethod httpget = new GetMethod("http://" + this.server.getLocalAddress() + ":" + this.server.getLocalPort() + "/test/"); try { this.client.executeMethod(hostconfig, httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertNotNull(httpget.getResponseHeader("Via")); } finally { httpget.releaseConnection(); } httpget = new GetMethod("/test/"); try { this.client.executeMethod(hostconfig, httpget); assertEquals(HttpStatus.SC_NOT_FOUND, httpget.getStatusCode()); } finally { httpget.releaseConnection(); } } /** * Test that HttpClient uses HostConfiguration.clone (not the copy * constructor) to copy its default HostConfiguration when preparing to * execute a method. This behavior is required to support specialized * Protocols; for example, HostConfigurationWithStickyProtocol. * * @see org.apache.commons.httpclient.contrib.ssl.HostConfigurationWithStickyProtocol */ public void testClientClonesHostConfiguration() throws IOException { this.server.setHttpService(new EchoService()); SpecialHostConfiguration configuration = new SpecialHostConfiguration(this.client .getHostConfiguration()); configuration.setHost(this.server.getLocalAddress(), this.server.getLocalPort(), new String(HttpURL.DEFAULT_SCHEME)); this.client.setHostConfiguration(configuration); HttpMethod method = new GetMethod(configuration.getHostURL() + "/test/"); try { this.client.executeMethod(method); fail("HostConfiguration wasn't cloned"); } catch (ExpectedError e) { assertNotSame("ExpectedError.configuration", configuration, e.configuration); } finally { method.releaseConnection(); } method = new GetMethod("/test/"); try { this.client.executeMethod(method); fail("HostConfiguration wasn't cloned"); } catch (ExpectedError e) { assertNotSame("ExpectedError.configuration", configuration, e.configuration); } finally { method.releaseConnection(); } } /** A HostConfiguration that refuses to provide a protocol. */ private class SpecialHostConfiguration extends HostConfiguration { SpecialHostConfiguration(HostConfiguration hostConfiguration) { super(hostConfiguration); } public Object clone() { return new SpecialHostConfiguration(this); } public synchronized Protocol getProtocol() { throw new ExpectedError(this); } } private class ExpectedError extends Error { ExpectedError(SpecialHostConfiguration c) { configuration = c; } SpecialHostConfiguration configuration; private static final long serialVersionUID = 1L; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestHttpConnection.java100644 0 0 21620 10661532630 26427 0ustar 0 0 /* * $Header$ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory; /** * * Unit tests for {@link HttpConnection}. * * @author Sean C. Sullivan * * @version $Id: TestHttpConnection.java 480424 2006-11-29 05:56:49Z bayard $ * */ public class TestHttpConnection extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestHttpConnection(String testName) throws Exception { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestHttpConnection.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestHttpConnection.class); } // ----------------------------------------------------------- Test Methods public void testConstructThenClose() { this.server.setHttpService(new EchoService()); HttpConnection conn = new HttpConnection( this.server.getLocalAddress(), this.server.getLocalPort()); conn.close(); assertTrue(!conn.isOpen()); } public void testConnTimeoutRelease() { this.server.setHttpService(new EchoService()); // create a custom protocol that will delay for 500 milliseconds Protocol testProtocol = new Protocol( "timeout", new DelayedProtocolSocketFactory( 500, Protocol.getProtocol("http").getSocketFactory() ), this.server.getLocalPort() ); NoHostHttpConnectionManager connectionManager = new NoHostHttpConnectionManager(); connectionManager.setConnection( new HttpConnection( this.server.getLocalAddress(), this.server.getLocalPort(), testProtocol)); this.client.setHttpConnectionManager(connectionManager); client.getHostConfiguration().setHost( this.server.getLocalAddress(), this.server.getLocalPort(), testProtocol); client.getHttpConnectionManager().getParams().setConnectionTimeout(1); try { GetMethod get = new GetMethod(); client.executeMethod(get); fail("Should have timed out"); } catch(IOException e) { /* should fail */ assertTrue(e instanceof ConnectTimeoutException); assertTrue(connectionManager.isConnectionReleased()); } } public void testConnTimeout() { // create a custom protocol that will delay for 500 milliseconds Protocol testProtocol = new Protocol( "timeout", new DelayedProtocolSocketFactory( 500, Protocol.getProtocol("http").getSocketFactory() ), this.server.getLocalPort() ); HttpConnection conn = new HttpConnection( this.server.getLocalAddress(), this.server.getLocalPort(), testProtocol); // 1 ms is short enough to make this fail conn.getParams().setConnectionTimeout(1); try { conn.open(); fail("Should have timed out"); } catch(IOException e) { assertTrue(e instanceof ConnectTimeoutException); /* should fail */ } } public void testForIllegalStateExceptions() { HttpConnection conn = new HttpConnection( this.server.getLocalAddress(), this.server.getLocalPort()); try { OutputStream out = conn.getRequestOutputStream(); fail("getRequestOutputStream did not throw the expected exception"); } catch (IllegalStateException expected) { // this exception is expected } catch (IOException ex) { fail("getRequestOutputStream did not throw the expected exception"); } try { OutputStream out = new ChunkedOutputStream(conn.getRequestOutputStream()); fail("getRequestOutputStream(true) did not throw the expected exception"); } catch (IllegalStateException expected) { // this exception is expected } catch (IOException ex) { fail("getRequestOutputStream(true) did not throw the expected exception"); } try { InputStream in = conn.getResponseInputStream(); fail("getResponseInputStream() did not throw the expected exception"); } catch (IllegalStateException expected) { // this exception is expected } catch (IOException ex) { fail("getResponseInputStream() did not throw the expected exception"); } } /** * A ProtocolSocketFactory that delays before creating a socket. */ class DelayedProtocolSocketFactory implements ProtocolSocketFactory { private int delay; private ProtocolSocketFactory realFactory; public DelayedProtocolSocketFactory(int delay, ProtocolSocketFactory realFactory) { this.delay = delay; this.realFactory = realFactory; } public Socket createSocket( String host, int port, InetAddress localAddress, int localPort ) throws IOException, UnknownHostException { synchronized (this) { try { this.wait(delay); } catch (InterruptedException e) {} } return realFactory.createSocket(host, port, localAddress, localPort); } public Socket createSocket( final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params ) throws IOException, UnknownHostException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); ControllerThreadSocketFactory.SocketTask task = new ControllerThreadSocketFactory.SocketTask() { public void doit() throws IOException { synchronized (this) { try { this.wait(delay); } catch (InterruptedException e) {} } setSocket(realFactory.createSocket(host, port, localAddress, localPort)); } }; return ControllerThreadSocketFactory.createSocket(task, timeout); } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { synchronized (this) { try { this.wait(delay); } catch (InterruptedException e) {} } return realFactory.createSocket(host, port); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestHttpConnectionManager.java100644 0 0 101017 10661532630 27741 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttpConnectionManager.java,v 1.23 2004/07/17 18:58:33 mbecke Exp $ * $Revision: 509320 $ * $Date: 2007-02-19 20:52:43 +0100 (Mon, 19 Feb 2007) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * Unit tests for {@link HttpConnectionManager}. * * @author Marc A. Saegesser * @version $Id: TestHttpConnectionManager.java 509320 2007-02-19 19:52:43Z mbecke $ */ public class TestHttpConnectionManager extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestHttpConnectionManager(String testName) throws IOException { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestHttpConnectionManager.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestHttpConnectionManager.class); } // ----------------------------------------------------------- Test Methods /** * Test that the ConnectMethod correctly releases connections when * CONNECT fails. */ public void testConnectMethodFailureRelease() throws Exception { MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); mgr.getParams().setIntParameter( HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 1); client.setHttpConnectionManager(mgr); this.server.setHttpService(new RejectConnectService()); // we're going to execute a connect method against the localhost, assuming // that CONNECT is not supported. This should test the fakeResponse() // code on HttpMethodBase. client.getHostConfiguration().setProxy(server.getLocalAddress(), server.getLocalPort()); // we must set the host to a secure destination or the CONNECT method // will not be used client.getHostConfiguration().setHost( "notARealHost", 1234, new Protocol( "https", (ProtocolSocketFactory)new FakeSecureProtocolSocketFactory(), 443) ); GetMethod get = new GetMethod("/"); try { assertTrue(client.executeMethod(get) != 200); } catch (IOException e) { e.printStackTrace(); fail("Error executing connect: " + e); } // this should calling releaseConnection() releases the connection try { get.releaseConnection(); mgr.getConnectionWithTimeout(client.getHostConfiguration(), 1).releaseConnection(); } catch (ConnectTimeoutException e1) { fail("Connection should have been available."); } get = new GetMethod("/"); try { assertTrue(client.executeMethod(get) != 200); } catch (IOException e) { e.printStackTrace(); fail("Error executing connect: " + e); } // make sure reading the response fully releases the connection try { get.getResponseBodyAsString(); mgr.getConnectionWithTimeout(client.getHostConfiguration(), 1).releaseConnection(); } catch (ConnectTimeoutException e1) { fail("Connection should have been available."); } get = new GetMethod("/"); try { assertTrue(client.executeMethod(get) != 200); } catch (IOException e) { e.printStackTrace(); fail("Error executing connect: " + e); } // make sure closing the output stream releases the connection try { get.getResponseBodyAsStream().close(); mgr.getConnectionWithTimeout(client.getHostConfiguration(), 1).releaseConnection(); } catch (ConnectTimeoutException e) { fail("Connection should have been available."); } catch (IOException e) { e.printStackTrace(); fail("Close connection failed: " + e); } } public void testGetConnection() { MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setHost("www.nosuchserver.com", 80, "http"); // Create a new connection HttpConnection conn = mgr.getConnection(hostConfiguration); // Validate the connection properties assertEquals("Host", "www.nosuchserver.com", conn.getHost()); assertEquals("Port", 80, conn.getPort()); // Release the connection mgr.releaseConnection(conn); // Create a new connection hostConfiguration.setHost("www.nosuchserver.com", -1, "https"); conn = mgr.getConnection(hostConfiguration); // Validate the connection properties assertEquals("Host", "www.nosuchserver.com", conn.getHost()); assertEquals("Port", 443, conn.getPort()); // Release the connection mgr.releaseConnection(conn); // Create a new connection hostConfiguration.setHost("www.nowhere.org", 8080, "http"); conn = mgr.getConnection(hostConfiguration); // Validate the connection properties assertEquals("Host", "www.nowhere.org", conn.getHost()); assertEquals("Port", 8080, conn.getPort()); // Release the connection mgr.releaseConnection(conn); } public void testDroppedThread() throws Exception { this.server.setHttpService(new EchoService()); MultiThreadedHttpConnectionManager mthcm = new MultiThreadedHttpConnectionManager(); client.setHttpConnectionManager(mthcm); WeakReference wr = new WeakReference(mthcm); GetMethod method = new GetMethod("/"); client.executeMethod(method); method.releaseConnection(); mthcm = null; client = null; method = null; System.gc(); // this sleep appears to be necessary in order to give the JVM // time to clean up the miscellaneous pointers to the connection manager try { Thread.sleep(1000); } catch (InterruptedException e) { fail("shouldn't be interrupted."); } Object connectionManager = wr.get(); assertNull("connectionManager should be null", connectionManager); } public void testWriteRequestReleaseConnection() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(1); client.setHttpConnectionManager(connectionManager); GetMethod get = new GetMethod("/") { protected boolean writeRequestBody(HttpState state, HttpConnection conn) throws IOException, HttpException { throw new IOException("Oh no!!"); } }; try { client.executeMethod(get); fail("An exception should have occurred."); } catch (HttpException e) { e.printStackTrace(); fail("HttpException should not have occurred: " + e); } catch (IOException e) { // expected } try { connectionManager.getConnectionWithTimeout(client.getHostConfiguration(), 1); } catch (ConnectTimeoutException e) { e.printStackTrace(); fail("Connection was not released: " + e); } } public void testReleaseConnection() { this.server.setHttpService(new EchoService()); MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(1); client.setHttpConnectionManager(connectionManager); // we shouldn't have to wait if a connection is available client.getParams().setConnectionManagerTimeout(1); GetMethod getMethod = new GetMethod("/"); try { client.executeMethod(getMethod); } catch (Exception e) { fail("error reading from server: " + e); } try { // this should fail quickly since the connection has not been released client.executeMethod(getMethod); fail("a httpConnection should not be available"); } catch (ConnectTimeoutException e) { } catch (HttpException e) { fail("error reading from server; " + e); } catch (IOException e) { e.printStackTrace(); fail("error reading from server; " + e); } // this should release the connection getMethod.releaseConnection(); getMethod = new GetMethod("/"); try { // this should fail quickly if the connection has not been released client.executeMethod(getMethod); } catch (HttpException e) { fail("httpConnection does not appear to have been released: " + e); } catch (IOException e) { fail("error reading from server; " + e); } } /** * Makes sure that a connection gets released after the content of the body * is read. */ public void testResponseAutoRelease() throws Exception { this.server.setHttpService(new EchoService()); MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(1); client.setHttpConnectionManager(connectionManager); // we shouldn't have to wait if a connection is available client.getParams().setConnectionManagerTimeout( 1 ); GetMethod getMethod = new GetMethod("/"); try { client.executeMethod(getMethod); } catch (Exception e) { fail("error reading from server: " + e); } // this should release the connection getMethod.getResponseBody(); getMethod = new GetMethod("/"); try { // this should fail quickly if the connection has not been released client.executeMethod(getMethod); } catch (HttpException e) { fail("httpConnection does not appear to have been released: " + e); } catch (IOException e) { fail("error reading from server; " + e); } } /** * Tests the MultiThreadedHttpConnectionManager's ability to reclaim unused * connections. */ public void testConnectionReclaiming() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(1); connectionManager.getParams().setMaxTotalConnections(1); HostConfiguration host1 = new HostConfiguration(); host1.setHost("host1", -1, "http"); HostConfiguration host2 = new HostConfiguration(); host2.setHost("host2", -1, "http"); HttpConnection connection = connectionManager.getConnection(host1); // now release this connection connection.releaseConnection(); connection = null; try { // the connection from host1 should be reclaimed connection = connectionManager.getConnectionWithTimeout(host2, 100); } catch (ConnectTimeoutException e) { e.printStackTrace(); fail("a httpConnection should have been available: " + e); } } /** * Tests that {@link MultiThreadedHttpConnectionManager#shutdownAll()} closes all resources * and makes all connection mangers unusable. */ public void testShutdownAll() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(1); connectionManager.getParams().setMaxTotalConnections(1); HostConfiguration host1 = new HostConfiguration(); host1.setHost("host1", -1, "http"); // hold on to the only connection HttpConnection connection = connectionManager.getConnection(host1); // wait for a connection on another thread GetConnectionThread getConn = new GetConnectionThread(host1, connectionManager, 0); getConn.start(); MultiThreadedHttpConnectionManager.shutdownAll(); // now release this connection, this should close the connection, but have no other effect connection.releaseConnection(); connection = null; try { getConn.join(); } catch (InterruptedException e) { e.printStackTrace(); } // this thread should have caught an exception without getting a connection assertNull("Not connection should have been checked out", getConn.getConnection()); assertNotNull("There should have been an exception", getConn.getException()); try { connectionManager.getConnection(host1); fail("An exception should have occurred"); } catch (Exception e) { // this is expected } } /** * Tests that {@link MultiThreadedHttpConnectionManager#shutdown()} closes all resources * and makes the connection manger unusable. */ public void testShutdown() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(1); connectionManager.getParams().setMaxTotalConnections(1); HostConfiguration host1 = new HostConfiguration(); host1.setHost("host1", -1, "http"); // hold on to the only connection HttpConnection connection = connectionManager.getConnection(host1); // wait for a connection on another thread GetConnectionThread getConn = new GetConnectionThread(host1, connectionManager, 0); getConn.start(); connectionManager.shutdown(); // now release this connection, this should close the connection, but have no other effect connection.releaseConnection(); connection = null; try { getConn.join(); } catch (InterruptedException e) { e.printStackTrace(); } // this thread should have caught an exception without getting a connection assertNull("Not connection should have been checked out", getConn.getConnection()); assertNotNull("There should have been an exception", getConn.getException()); try { connectionManager.getConnection(host1); fail("An exception should have occurred"); } catch (Exception e) { // this is expected } } /** * Tests the MultiThreadedHttpConnectionManager's ability to restrict the maximum number * of connections. */ public void testMaxConnections() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(1); connectionManager.getParams().setMaxTotalConnections(2); HostConfiguration host1 = new HostConfiguration(); host1.setHost("host1", -1, "http"); HostConfiguration host2 = new HostConfiguration(); host2.setHost("host2", -1, "http"); HttpConnection connection1 = connectionManager.getConnection(host1); HttpConnection connection2 = connectionManager.getConnection(host2); try { // this should fail quickly since the connection has not been released connectionManager.getConnectionWithTimeout(host2, 100); fail("ConnectionPoolTimeoutException should not be available"); } catch (ConnectionPoolTimeoutException e) { // this should throw an exception } // release one of the connections connection2.releaseConnection(); connection2 = null; try { // there should be a connection available now connection2 = connectionManager.getConnectionWithTimeout(host2, 100); } catch (ConnectionPoolTimeoutException e) { e.printStackTrace(); fail("a httpConnection should have been available: " + e); } } /** * Tests the MultiThreadedHttpConnectionManager's ability to restrict the maximum number * of connections per host. */ public void testMaxConnectionsPerHost() throws Exception { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(1); connectionManager.getParams().setMaxTotalConnections(100); HostConfiguration host1 = new HostConfiguration(); host1.setHost("host1", -1, "http"); HostConfiguration host2 = new HostConfiguration(); host2.setHost("host2", -1, "http"); HostConfiguration host3 = new HostConfiguration(); host3.setHost("host3", -1, "http"); connectionManager.getParams().setMaxConnectionsPerHost(host1, 3); connectionManager.getParams().setMaxConnectionsPerHost(host2, 2); // Host1 HttpConnection connection1 = connectionManager.getConnectionWithTimeout(host1, 1000); HttpConnection connection2 = connectionManager.getConnectionWithTimeout(host1, 1000); HttpConnection connection3 = connectionManager.getConnectionWithTimeout(host1, 1000); try { // this should fail quickly since the connection has not been released connectionManager.getConnectionWithTimeout(host1, 100); fail("ConnectionPoolTimeoutException should not be available"); } catch (ConnectionPoolTimeoutException e) { // expected } // Host2 connection1 = connectionManager.getConnectionWithTimeout(host2, 1000); connection2 = connectionManager.getConnectionWithTimeout(host2, 1000); try { // this should fail quickly since the connection has not been released connectionManager.getConnectionWithTimeout(host2, 100); fail("ConnectionPoolTimeoutException should not be available"); } catch (ConnectionPoolTimeoutException e) { // expected } // Host3 (should use the default per host value) connection1 = connectionManager.getConnectionWithTimeout(host3, 1000); try { // this should fail quickly since the connection has not been released connectionManager.getConnectionWithTimeout(host3, 100); fail("ConnectionPoolTimeoutException should not be available"); } catch (ConnectionPoolTimeoutException e) { // expected } } public void testHostReusePreference() { final MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(1); connectionManager.getParams().setMaxTotalConnections(1); final HostConfiguration host1 = new HostConfiguration(); host1.setHost("host1", -1, "http"); final HostConfiguration host2 = new HostConfiguration(); host2.setHost("host2", -1, "http"); HttpConnection connection = connectionManager.getConnection(host1); GetConnectionThread getHost1 = new GetConnectionThread(host1, connectionManager, 200); GetConnectionThread getHost2 = new GetConnectionThread(host2, connectionManager, 200); getHost2.start(); getHost1.start(); // give the threads some time to startup try { Thread.sleep(100); } catch (InterruptedException e1) { e1.printStackTrace(); } // after the connection to host1 is released it should be given to getHost1 connection.releaseConnection(); connection = null; try { getHost1.join(); getHost2.join(); } catch (InterruptedException e) { e.printStackTrace(); } assertNotSame( "Connection should have been given to someone", getHost1.getConnection(), getHost2.getConnection() ); assertNotNull("Connection should have been given to host1", getHost1.getConnection()); assertNull("Connection should NOT have been given to host2", getHost2.getConnection()); } public void testMaxConnectionsPerServer() { this.server.setHttpService(new EchoService()); MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(1); client.setHttpConnectionManager(connectionManager); // we shouldn't have to wait if a connection is available client.getParams().setConnectionManagerTimeout( 1 ); GetMethod getMethod = new GetMethod("/"); try { client.executeMethod(getMethod); } catch (Exception e) { fail("error reading from server: " + e); } GetMethod getMethod2 = new GetMethod("/"); try { // this should fail quickly since the connection has not been released client.executeMethod(getMethod2); fail("a httpConnection should not be available"); } catch (ConnectTimeoutException e) { } catch (HttpException e) { fail("error reading from server; " + e); } catch (IOException e) { fail("error reading from server; " + e); } } public void testDeleteClosedConnections() { MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager(); HttpConnection conn = manager.getConnection(client.getHostConfiguration()); assertEquals("connectionsInPool", manager.getConnectionsInPool(), 1); assertEquals("connectionsInPool(host)", manager.getConnectionsInPool(client.getHostConfiguration()), 1); conn.close(); conn.releaseConnection(); assertEquals("connectionsInPool", manager.getConnectionsInPool(), 1); assertEquals("connectionsInPool(host)", manager.getConnectionsInPool(client.getHostConfiguration()), 1); manager.deleteClosedConnections(); assertEquals("connectionsInPool", manager.getConnectionsInPool(), 0); assertEquals("connectionsInPool(host)", manager.getConnectionsInPool(client.getHostConfiguration()), 0); } /** * Tests that thread waiting in the MultiThreadedHttpConnectionManager can be * interrupted. */ public void testWaitingThreadInterrupted() { this.server.setHttpService(new EchoService()); MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setIntParameter( HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 1); HostConfiguration host1 = new HostConfiguration(); host1.setHost("host1", -1, "http"); // hold on to the only connection HttpConnection connection = connectionManager.getConnection(host1); // wait for a connection on another thread GetConnectionThread getConn = new GetConnectionThread(host1, connectionManager, 1000); getConn.start(); // give the thread a chance to block synchronized (this) { try { this.wait(500); } catch (InterruptedException e) { e.printStackTrace(); } } // interrupt the thread, this should cancel waiting with a RuntimeException getConn.interrupt(); try { getConn.join(); } catch (InterruptedException e) { e.printStackTrace(); } // make sure the correct exception was thrown assertTrue(getConn.exception != null); assertEquals(getConn.exception.getClass(), IllegalThreadStateException.class); // make sure the connection manager is still working connection.releaseConnection(); try { connectionManager.getConnectionWithTimeout(host1, 10); } catch (ConnectionPoolTimeoutException e) { fail("Connection not available"); } } public void testReclaimUnusedConnection() { this.server.setHttpService(new EchoService()); MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setIntParameter( HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 1); client.setHttpConnectionManager(connectionManager); // we shouldn't have to wait if a connection is available client.getParams().setConnectionManagerTimeout( 30000 ); GetMethod getMethod = new GetMethod("/"); try { client.executeMethod(getMethod); } catch (Exception e) { fail("error reading from server: " + e); } getMethod = new GetMethod("/"); Runtime.getRuntime().gc(); try { // we didn't explicitly release the connection, but it should be // reclaimed by the garbage collector, we hope:) client.executeMethod(getMethod); } catch (HttpException e) { fail("httpConnection does not appear to have been reclaimed by the GC: " + e); } catch (IOException e) { fail("error reading from server; " + e); } } public void testGetFromMultipleThreads() { this.server.setHttpService(new EchoService()); client.setHttpConnectionManager(new MultiThreadedHttpConnectionManager()); ExecuteMethodThread[] threads = new ExecuteMethodThread[10]; for (int i = 0; i < threads.length; i++) { GetMethod method = new GetMethod("/"); method.setFollowRedirects(true); threads[i] = new ExecuteMethodThread(method, client); threads[i].start(); } for (int i = 0; i < threads.length; i++) { try { // wait until this thread finishes. we'll give it 10 seconds, // but it shouldn't take that long threads[i].join(10000); } catch (InterruptedException e) { } // make sure an exception did not occur Exception e = threads[i].getException(); if (e != null) { fail("An error occured in the get: " + e); } // we should have a 200 status assertEquals(threads[i].getMethod().getStatusCode(), HttpStatus.SC_OK); } } public void testTimeout() { MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); mgr.getParams().setDefaultMaxConnectionsPerHost(2); try{ HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost("www.nosuchserver.com", 80, "http"); HttpConnection conn1 = mgr.getConnection(hostConfig); HttpConnection conn2 = mgr.getConnection(hostConfig); HttpConnection conn3 = mgr.getConnectionWithTimeout(hostConfig, 1000); fail("Expected an HttpException."); }catch(ConnectTimeoutException e){ //Expected result } } static class FakeSecureProtocolSocketFactory implements SecureProtocolSocketFactory { public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { throw new IllegalStateException("createSocket() should never have been called."); } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { throw new IllegalStateException("createSocket() should never have been called."); } public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { throw new IllegalStateException("createSocket() should never have been called."); } public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort, HttpConnectionParams params) throws IOException, UnknownHostException { throw new IllegalStateException("createSocket() should never have been called."); } } static class RejectConnectService extends EchoService { public boolean process(SimpleRequest request, SimpleResponse response) throws IOException { if (request.getRequestLine().getMethod().equalsIgnoreCase("CONNECT")) { response.setStatusLine(request.getRequestLine().getHttpVersion(), HttpStatus.SC_METHOD_NOT_ALLOWED); response.setHeader(new Header("Connection", "close")); return true; } else { return super.process(request, response); } } } static class GetConnectionThread extends Thread { private HostConfiguration hostConfiguration; private MultiThreadedHttpConnectionManager connectionManager; private HttpConnection connection; private long timeout; private Exception exception; public GetConnectionThread( HostConfiguration hostConfiguration, MultiThreadedHttpConnectionManager connectionManager, long timeout ) { this.hostConfiguration = hostConfiguration; this.connectionManager = connectionManager; this.timeout = timeout; } public void run() { try { connection = connectionManager.getConnectionWithTimeout(hostConfiguration, timeout); } catch (Exception e) { this.exception = e; } } public Exception getException() { return exception; } public HttpConnection getConnection() { return connection; } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestHttpMethodFundamentals.java100644 0 0 32020 10661532626 30113 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttpMethodFundamentals.java,v 1.6 2004/11/06 23:47:58 olegk Exp $ * $Revision: 481225 $ * $Date: 2006-12-01 12:26:28 +0100 (Fri, 01 Dec 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests basic method functionality. * * @author Remy Maucherat * @author Rodney Waldhoff * @author Oleg Kalnichevski * * @version $Id: TestHttpMethodFundamentals.java 481225 2006-12-01 11:26:28Z oglueck $ */ public class TestHttpMethodFundamentals extends HttpClientTestBase { public TestHttpMethodFundamentals(final String testName) throws IOException { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(TestHttpMethodFundamentals.class); ProxyTestDecorator.addTests(suite); return suite; } public static void main(String args[]) { String[] testCaseName = { TestHttpMethodFundamentals.class.getName() }; junit.textui.TestRunner.main(testCaseName); } class ManyAService implements HttpService { public ManyAService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Content-Type", "text/plain")); response.addHeader(new Header("Connection", "close")); StringBuffer buffer = new StringBuffer(1024); for (int i = 0; i < 1024; i++) { buffer.append('A'); } response.setBodyString(buffer.toString()); return true; } } class SimpleChunkedService implements HttpService { public SimpleChunkedService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Content-Type", "text/plain")); response.addHeader(new Header("Content-Length", "garbage")); response.addHeader(new Header("Transfer-Encoding", "chunked")); response.addHeader(new Header("Connection", "close")); response.setBodyString("1234567890123"); return true; } } class EmptyResponseService implements HttpService { public EmptyResponseService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Content-Type", "text/plain")); response.addHeader(new Header("Transfer-Encoding", "chunked")); response.addHeader(new Header("Connection", "close")); return true; } } public void testHttpMethodBasePaths() throws Exception { HttpMethod simple = new FakeHttpMethod(); String[] paths = { "/some/absolute/path", "../some/relative/path", "/", "/some/path/with?query=string" }; for (int i=0; i. * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.ByteArrayInputStream; import java.io.InputStream; import junit.framework.*; /** * Simple tests for {@link HttpParser}. * * @author Oleg Kalnichevski * @version $Id: TestHttpParser.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestHttpParser extends TestCase { private static final String HTTP_ELEMENT_CHARSET = "US-ASCII"; // ------------------------------------------------------------ Constructor public TestHttpParser(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestHeader.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestHttpParser.class); } public void testReadHttpLine() throws Exception { InputStream instream = new ByteArrayInputStream( "\r\r\nstuff\r\n".getBytes(HTTP_ELEMENT_CHARSET)); assertEquals("\r", HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET)); assertEquals("stuff", HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET)); assertEquals(null, HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET)); instream = new ByteArrayInputStream( "\n\r\nstuff\r\n".getBytes("US-ASCII")); assertEquals("", HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET)); assertEquals("", HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET)); assertEquals("stuff", HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET)); assertEquals(null, HttpParser.readLine(instream, HTTP_ELEMENT_CHARSET)); } public void testReadWellFormedHttpHeaders() throws Exception { InputStream instream = new ByteArrayInputStream( "a: a\r\nb: b\r\n\r\nwhatever".getBytes(HTTP_ELEMENT_CHARSET)); Header[] headers = HttpParser.parseHeaders(instream, HTTP_ELEMENT_CHARSET); assertNotNull(headers); assertEquals(2, headers.length); assertEquals("a", headers[0].getName()); assertEquals("a", headers[0].getValue()); assertEquals("b", headers[1].getName()); assertEquals("b", headers[1].getValue()); } public void testReadMalformedHttpHeaders() throws Exception { InputStream instream = new ByteArrayInputStream( "a: a\r\nb b\r\n\r\nwhatever".getBytes(HTTP_ELEMENT_CHARSET)); try { Header[] headers = HttpParser.parseHeaders(instream, HTTP_ELEMENT_CHARSET); fail("HttpException should have been thrown"); } catch (HttpException expected) { } } public void testHeadersTerminatorLeniency1() throws Exception { InputStream instream = new ByteArrayInputStream( "a: a\r\nb: b\r\n\r\r\nwhatever".getBytes(HTTP_ELEMENT_CHARSET)); Header[] headers = HttpParser.parseHeaders(instream, HTTP_ELEMENT_CHARSET); assertNotNull(headers); assertEquals(2, headers.length); assertEquals("a", headers[0].getName()); assertEquals("a", headers[0].getValue()); assertEquals("b", headers[1].getName()); assertEquals("b", headers[1].getValue()); } public void testHeadersTerminatorLeniency2() throws Exception { InputStream instream = new ByteArrayInputStream( "a: a\r\nb: b\r\n \r\nwhatever".getBytes(HTTP_ELEMENT_CHARSET)); Header[] headers = HttpParser.parseHeaders(instream, HTTP_ELEMENT_CHARSET); assertNotNull(headers); assertEquals(2, headers.length); assertEquals("a", headers[0].getName()); assertEquals("a", headers[0].getValue()); assertEquals("b", headers[1].getName()); assertEquals("b", headers[1].getValue()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestHttpState.java100644 0 0 24350 10661532630 25413 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttpState.java,v 1.7 2004/06/23 06:50:25 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.auth.AuthScope; import junit.framework.*; /** * * Simple tests for {@link HttpState}. * * @author Rodney Waldhoff * @author Jeff Dever * @author Sean C. Sullivan * @author Oleg Kalnichevski * * @version $Id: TestHttpState.java 480424 2006-11-29 05:56:49Z bayard $ * */ public class TestHttpState extends TestCase { public final static Credentials CREDS1 = new UsernamePasswordCredentials("user1", "pass1"); public final static Credentials CREDS2 = new UsernamePasswordCredentials("user2", "pass2"); public final static AuthScope SCOPE1 = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "realm1"); public final static AuthScope SCOPE2 = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "realm2"); public final static AuthScope BOGUS = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "bogus"); public final static AuthScope DEFSCOPE = new AuthScope("host", AuthScope.ANY_PORT, "realm"); // ------------------------------------------------------------ Constructor public TestHttpState(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestHttpState.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestHttpState.class); } // ----------------------------------------------------------- Test Methods public void testHttpStateCredentials() { HttpState state = new HttpState(); state.setCredentials(SCOPE1, CREDS1); state.setCredentials(SCOPE2, CREDS2); assertEquals(CREDS1, state.getCredentials(SCOPE1)); assertEquals(CREDS2, state.getCredentials(SCOPE2)); } public void testToString() { HttpState state = new HttpState(); assertNotNull(state.toString()); state.addCookie(new Cookie("foo", "bar", "yeah")); assertNotNull(state.toString()); state.addCookie(new Cookie("flub", "duck", "yuck")); assertNotNull(state.toString()); state.setCredentials(SCOPE1, CREDS1); assertNotNull(state.toString()); state.setProxyCredentials(SCOPE2, CREDS2); assertNotNull(state.toString()); } public void testHttpStateNoCredentials() { HttpState state = new HttpState(); assertEquals(null, state.getCredentials(BOGUS)); } public void testHttpStateDefaultCredentials() { HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, CREDS1); state.setCredentials(SCOPE2, CREDS2); assertEquals(CREDS1, state.getCredentials(BOGUS)); } public void testHttpStateProxyCredentials() { HttpState state = new HttpState(); state.setProxyCredentials(SCOPE1, CREDS1); state.setProxyCredentials(SCOPE2, CREDS2); assertEquals(CREDS1, state.getProxyCredentials(SCOPE1)); assertEquals(CREDS2, state.getProxyCredentials(SCOPE2)); } public void testHttpStateProxyNoCredentials() { HttpState state = new HttpState(); assertEquals(null, state.getProxyCredentials(BOGUS)); } public void testHttpStateProxyDefaultCredentials() { HttpState state = new HttpState(); state.setProxyCredentials(AuthScope.ANY, CREDS1); state.setProxyCredentials(SCOPE2, CREDS2); assertEquals(CREDS1, state.getProxyCredentials(BOGUS)); } // --------------------------------- Test Methods for Selecting Credentials public void testDefaultCredentials() throws Exception { HttpState state = new HttpState(); Credentials expected = new UsernamePasswordCredentials("name", "pass"); state.setCredentials(AuthScope.ANY, expected); Credentials got = state.getCredentials(DEFSCOPE); assertEquals(got, expected); } public void testRealmCredentials() throws Exception { HttpState state = new HttpState(); Credentials expected = new UsernamePasswordCredentials("name", "pass"); state.setCredentials(DEFSCOPE, expected); Credentials got = state.getCredentials(DEFSCOPE); assertEquals(expected, got); } public void testHostCredentials() throws Exception { HttpState state = new HttpState(); Credentials expected = new UsernamePasswordCredentials("name", "pass"); state.setCredentials( new AuthScope("host", AuthScope.ANY_PORT, AuthScope.ANY_REALM), expected); Credentials got = state.getCredentials(DEFSCOPE); assertEquals(expected, got); } public void testWrongHostCredentials() throws Exception { HttpState state = new HttpState(); Credentials expected = new UsernamePasswordCredentials("name", "pass"); state.setCredentials( new AuthScope("host1", AuthScope.ANY_PORT, "realm"), expected); Credentials got = state.getCredentials( new AuthScope("host2", AuthScope.ANY_PORT, "realm")); assertNotSame(expected, got); } public void testWrongRealmCredentials() throws Exception { HttpState state = new HttpState(); Credentials cred = new UsernamePasswordCredentials("name", "pass"); state.setCredentials( new AuthScope("host", AuthScope.ANY_PORT, "realm1"), cred); Credentials got = state.getCredentials( new AuthScope("host", AuthScope.ANY_PORT, "realm2")); assertNotSame(cred, got); } // ------------------------------- Test Methods for matching Credentials public void testScopeMatching() { AuthScope authscope1 = new AuthScope("somehost", 80, "somerealm", "somescheme"); AuthScope authscope2 = new AuthScope("someotherhost", 80, "somerealm", "somescheme"); assertTrue(authscope1.match(authscope2) < 0); int m1 = authscope1.match( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "somescheme")); int m2 = authscope1.match( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "somerealm", AuthScope.ANY_SCHEME)); assertTrue(m2 > m1); m1 = authscope1.match( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "somescheme")); m2 = authscope1.match( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "somerealm", AuthScope.ANY_SCHEME)); assertTrue(m2 > m1); m1 = authscope1.match( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "somerealm", "somescheme")); m2 = authscope1.match( new AuthScope(AuthScope.ANY_HOST, 80, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME)); assertTrue(m2 > m1); m1 = authscope1.match( new AuthScope(AuthScope.ANY_HOST, 80, "somerealm", "somescheme")); m2 = authscope1.match( new AuthScope("somehost", AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME)); assertTrue(m2 > m1); m1 = authscope1.match(AuthScope.ANY); m2 = authscope1.match( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "somescheme")); assertTrue(m2 > m1); } public void testCredentialsMatching() { Credentials creds1 = new UsernamePasswordCredentials("name1", "pass1"); Credentials creds2 = new UsernamePasswordCredentials("name2", "pass2"); Credentials creds3 = new UsernamePasswordCredentials("name3", "pass3"); AuthScope scope1 = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); AuthScope scope2 = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, "somerealm"); AuthScope scope3 = new AuthScope("somehost", AuthScope.ANY_PORT, AuthScope.ANY_REALM); HttpState state = new HttpState(); state.setCredentials(scope1, creds1); state.setCredentials(scope2, creds2); state.setCredentials(scope3, creds3); Credentials got = state.getCredentials( new AuthScope("someotherhost", 80, "someotherrealm", "basic")); Credentials expected = creds1; assertEquals(expected, got); got = state.getCredentials( new AuthScope("someotherhost", 80, "somerealm", "basic")); expected = creds2; assertEquals(expected, got); got = state.getCredentials( new AuthScope("somehost", 80, "someotherrealm", "basic")); expected = creds3; assertEquals(expected, got); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestHttpStatus.java100644 0 0 7230 10661532630 25574 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttpStatus.java,v 1.4 2004/05/02 11:21:13 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import junit.framework.*; import java.lang.reflect.*; /** * * Unit tests for {@link HttpStatus} * * @author Sean C. Sullivan * @version $Id: TestHttpStatus.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestHttpStatus extends TestCase { // ------------------------------------------------------------ Constructor public TestHttpStatus(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestHttpStatus.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestHttpStatus.class); } // ----------------------------------------------------------- Test Methods public void testStatusText() throws IllegalAccessException { Field[] publicFields = HttpStatus.class.getFields(); assertTrue( publicFields != null ); assertTrue( publicFields.length > 0 ); for (int i = 0; i < publicFields.length; i++) { final Field f = publicFields[i]; 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 = HttpStatus.getStatusText(iValue); assertTrue( "text is null for HttpStatus." + f.getName(), (text != null) ); assertTrue( text.length() > 0 ); } } } public void testStatusTextNegative() throws Exception { try { HttpStatus.getStatusText(-1); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testStatusTextAll() throws Exception { for (int i = 0; i < 600; i++) { HttpStatus.getStatusText(i); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestHttpVersion.java100644 0 0 15241 10661532626 25764 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttpVersion.java,v 1.3 2004/05/09 12:16:12 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test cases for HTTP version class * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class TestHttpVersion extends TestCase { // ------------------------------------------------------------ Constructor public TestHttpVersion(String name) { super(name); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestHttpVersion.class); } // ------------------------------------------------------------------ Tests public void testHttpVersionInvalidConstructorInput() throws Exception { try { HttpVersion ver = new HttpVersion(-1, -1); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } try { HttpVersion ver = new HttpVersion(0, -1); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } } public void testHttpVersionParsing() throws Exception { String s = "HTTP/1.1"; HttpVersion version = HttpVersion.parse(s); assertEquals("HTTP major version number", 1, version.getMajor()); assertEquals("HTTP minor version number", 1, version.getMinor()); assertEquals("HTTP version number", s, version.toString()); s = "HTTP/123.4567"; version = HttpVersion.parse(s); assertEquals("HTTP major version number", 123, version.getMajor()); assertEquals("HTTP minor version number", 4567, version.getMinor()); assertEquals("HTTP version number", s, version.toString()); } public void testInvalidHttpVersionParsing() throws Exception { try { HttpVersion.parse(null); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { //expected } try { HttpVersion.parse("crap"); fail("ProtocolException should have been thrown"); } catch (ProtocolException e) { //expected } try { HttpVersion.parse("HTTP/crap"); fail("ProtocolException should have been thrown"); } catch (ProtocolException e) { //expected } try { HttpVersion.parse("HTTP/1"); fail("ProtocolException should have been thrown"); } catch (ProtocolException e) { //expected } try { HttpVersion.parse("HTTP/1234 "); fail("ProtocolException should have been thrown"); } catch (ProtocolException e) { //expected } try { HttpVersion.parse("HTTP/1."); fail("ProtocolException should have been thrown"); } catch (ProtocolException e) { //expected } try { HttpVersion.parse("HTTP/1.1 crap"); fail("ProtocolException should have been thrown"); } catch (ProtocolException e) { //expected } try { HttpVersion.parse("HTTP/whatever.whatever whatever"); fail("ProtocolException should have been thrown"); } catch (ProtocolException e) { //expected } try { HttpVersion.parse("HTTP/1.whatever whatever"); fail("ProtocolException should have been thrown"); } catch (ProtocolException e) { //expected } } public void testHttpVersionEquality() throws Exception { HttpVersion ver1 = new HttpVersion(1, 1); HttpVersion ver2 = new HttpVersion(1, 1); assertEquals(ver1.hashCode(), ver2.hashCode()); assertTrue(ver1.equals(ver1)); assertTrue(ver1.equals(ver2)); assertTrue(ver1.equals((Object)ver1)); assertTrue(ver1.equals((Object)ver2)); assertFalse(ver1.equals(new Float(1.1))); try { ver1.equals(null); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { } assertTrue((new HttpVersion(0, 9)).equals(HttpVersion.HTTP_0_9)); assertTrue((new HttpVersion(1, 0)).equals(HttpVersion.HTTP_1_0)); assertTrue((new HttpVersion(1, 1)).equals(HttpVersion.HTTP_1_1)); assertFalse((new HttpVersion(1, 1)).equals(HttpVersion.HTTP_1_0)); } public void testHttpVersionComparison() { assertTrue(HttpVersion.HTTP_0_9.lessEquals(HttpVersion.HTTP_1_1)); assertTrue(HttpVersion.HTTP_0_9.greaterEquals(HttpVersion.HTTP_0_9)); assertFalse(HttpVersion.HTTP_0_9.greaterEquals(HttpVersion.HTTP_1_0)); assertTrue(HttpVersion.HTTP_1_0.compareTo((Object)HttpVersion.HTTP_1_1) < 0); assertTrue(HttpVersion.HTTP_1_0.compareTo((Object)HttpVersion.HTTP_0_9) > 0); assertTrue(HttpVersion.HTTP_1_0.compareTo((Object)HttpVersion.HTTP_1_0) == 0); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestHttps.java100644 0 0 13061 10661532626 24577 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestHttps.java,v 1.12 2004/06/13 12:13:08 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; /** * Simple tests for HTTPS support in HttpClient. * * To run this test you'll need: * + a JSSE implementation installed (see README.txt) * + the java.protocol.handler.pkgs system property set * for your provider. e.g.: * -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol * (see build.xml) * * @author Rodney Waldhoff * @author Ortwin Glck * @version $Id: TestHttps.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestHttps extends TestCase { // ---------------------------------------------------------------- Members private String _urlWithPort = null; private String _urlWithoutPort = null; private final String PROXY_HOST = System.getProperty("httpclient.test.proxyHost"); private final String PROXY_PORT = System.getProperty("httpclient.test.proxyPort"); private final String PROXY_USER = System.getProperty("httpclient.test.proxyUser"); private final String PROXY_PASS = System.getProperty("httpclient.test.proxyPass"); // ------------------------------------------------------------ Constructor public TestHttps(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestHttps.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestHttps.class); } public void setUp() throws Exception { _urlWithPort = "https://www.verisign.com:443/"; _urlWithoutPort = "https://www.verisign.com/"; } public void testHttpsGet() { HttpClient client = new HttpClient(); if (PROXY_HOST != null) { if (PROXY_USER != null) { HttpState state = client.getState(); state.setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials( PROXY_USER, PROXY_PASS)); } client.getHostConfiguration().setProxy(PROXY_HOST, Integer.parseInt(PROXY_PORT)); } GetMethod method = new GetMethod(_urlWithPort); try { client.executeMethod(method); } catch (Throwable t) { t.printStackTrace(); fail("Exception thrown during HTTPS GET: " + t.toString()); } try { String data = method.getResponseBodyAsString(); // This enumeration musn't be empty assertTrue("No data returned.", (data.length() > 0)); } catch (Throwable t) { t.printStackTrace(); fail("Exception thrown while retrieving data : " + t.toString()); } } public void testHttpsGetNoPort() { HttpClient client = new HttpClient(); if (PROXY_HOST != null) { if (PROXY_USER != null) { HttpState state = client.getState(); state.setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials( PROXY_USER, PROXY_PASS)); } client.getHostConfiguration().setProxy(PROXY_HOST, Integer.parseInt(PROXY_PORT)); } GetMethod method = new GetMethod(_urlWithoutPort); try { client.executeMethod(method); } catch (Throwable t) { t.printStackTrace(); fail("Exception thrown during HTTPS GET: " + t.toString()); } try { String data = method.getResponseBodyAsString(); // This enumeration musn't be empty assertTrue("No data returned.", (data.length() > 0)); } catch (Throwable t) { t.printStackTrace(); fail("Exception thrown while retrieving data : " + t.toString()); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestIdleConnectionTimeout.java100644 0 0 14061 10661532626 27742 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestIdleConnectionTimeout.java,v 1.5 2004/11/07 12:31:42 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.util.IdleConnectionHandler; import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread; /** */ public class TestIdleConnectionTimeout extends TestCase { /** * */ public TestIdleConnectionTimeout() { super(); } /** * @param arg0 */ public TestIdleConnectionTimeout(String arg0) { super(arg0); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestIdleConnectionTimeout.class); } /** * Tests that the IdleConnectionHandler correctly closes connections. */ public void testHandler() { TimeoutHttpConnection connection = new TimeoutHttpConnection(); IdleConnectionHandler handler = new IdleConnectionHandler(); handler.add(connection); synchronized(this) { try { this.wait(250); } catch (InterruptedException e) { e.printStackTrace(); } } handler.closeIdleConnections(100); assertTrue("Connection not closed", connection.isClosed()); connection.setClosed(false); handler.remove(connection); synchronized(this) { try { this.wait(250); } catch (InterruptedException e) { e.printStackTrace(); } } handler.closeIdleConnections(100); assertFalse("Connection closed", connection.isClosed()); } /** * Tests that the IdleConnectionTimeoutThread works correctly. */ public void testTimeoutThread() { TimeoutHttpConnectionManager cm = new TimeoutHttpConnectionManager(); IdleConnectionTimeoutThread timeoutThread = new IdleConnectionTimeoutThread(); timeoutThread.addConnectionManager(cm); timeoutThread.setTimeoutInterval(100); timeoutThread.start(); synchronized(this) { try { this.wait(250); } catch (InterruptedException e) { e.printStackTrace(); } } assertTrue("closeIdleConnections() not called", cm.closed); timeoutThread.removeConnectionManager(cm); cm.closed = false; synchronized(this) { try { this.wait(250); } catch (InterruptedException e) { e.printStackTrace(); } } assertFalse("closeIdleConnections() called", cm.closed); timeoutThread.shutdown(); } private static class TimeoutHttpConnectionManager implements HttpConnectionManager { public boolean closed = false; public void closeIdleConnections(long idleTimeout) { this.closed = true; } /** * @deprecated */ public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout) throws HttpException { return null; } public HttpConnection getConnection(HostConfiguration hostConfiguration) { return null; } public HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration, long timeout) throws ConnectionPoolTimeoutException { return null; } public HttpConnectionManagerParams getParams() { return null; } public void releaseConnection(HttpConnection conn) { } public void setParams(HttpConnectionManagerParams params) { } } private static class TimeoutHttpConnection extends HttpConnection { private boolean closed = false;; public TimeoutHttpConnection() { super("fake-host", 80); } /** * @return Returns the closed. */ public boolean isClosed() { return closed; } /** * @param closed The closed to set. */ public void setClosed(boolean closed) { this.closed = closed; } /* (non-Javadoc) * @see org.apache.commons.httpclient.HttpConnection#close() */ public void close() { closed = true; } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestMethodAbort.java100644 0 0 12331 10661532626 25704 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestMethodAbort.java,v 1.3 2004/10/31 14:42:59 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.server.HttpRequestHandler; import org.apache.commons.httpclient.server.ResponseWriter; import org.apache.commons.httpclient.server.SimpleHttpServerConnection; import org.apache.commons.httpclient.server.SimpleRequest; /** * Tests ability to abort method execution. * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class TestMethodAbort extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestMethodAbort(final String testName) throws IOException { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestMethodAbort.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestMethodAbort.class); } private class ProduceGarbageHandler implements HttpRequestHandler { public ProduceGarbageHandler() { super(); } public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { final String garbage = "garbage!\r\n"; final long count = 1000000000; HttpVersion httpversion = request.getRequestLine().getHttpVersion(); ResponseWriter out = conn.getWriter(); out.println(httpversion + " 200 OK"); out.println("Content-Type: text/plain"); out.println("Content-Length: " + count * garbage.length()) ; out.println("Connection: close"); out.println(); for (int i = 0; i < count; i++) { out.print(garbage); } return true; } } public void testAbortMethod() throws IOException { this.server.setRequestHandler(new ProduceGarbageHandler()); final GetMethod httpget = new GetMethod("/test/"); Thread thread = new Thread(new Runnable() { public void run() { try { Thread.sleep(500); } catch (InterruptedException e) { } httpget.abort(); } }); thread.setDaemon(true); thread.start(); try { this.client.executeMethod(httpget); BufferedReader in = new BufferedReader(new InputStreamReader( httpget.getResponseBodyAsStream())); String line = null; while ((line = in.readLine()) != null) { } fail("IOException must have been thrown"); } catch (IOException e) { // expected } finally { httpget.releaseConnection(); } assertTrue(httpget.isAborted()); } public void testAbortedMethodExecute() throws IOException { final GetMethod httpget = new GetMethod("/test/"); try { httpget.abort(); try { this.client.executeMethod(httpget); fail("IllegalStateException must have been thrown"); } catch (IllegalStateException e) { } } finally { httpget.releaseConnection(); } assertTrue(httpget.isAborted()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestMethodCharEncoding.java100644 0 0 25001 10661532626 27157 0ustar 0 0 /* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import junit.framework.Test; import junit.framework.TestSuite; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.util.URIUtil; /** * @author Oleg Kalnichevski * @author Andre John Mas * @author Laura Werner */ public class TestMethodCharEncoding extends HttpClientTestBase { static final String CHARSET_DEFAULT = "ISO-8859-1"; static final String CHARSET_ASCII = "US-ASCII"; static final String CHARSET_UTF8 = "UTF-8"; static final String CHARSET_KOI8_R = "KOI8_R"; static final String CHARSET_WIN1251 = "Cp1251"; static final int SWISS_GERMAN_STUFF_UNICODE [] = { 0x47, 0x72, 0xFC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xE4, 0x6D, 0xE4 }; static final int SWISS_GERMAN_STUFF_ISO8859_1 [] = { 0x47, 0x72, 0xFC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xE4, 0x6D, 0xE4 }; static final int SWISS_GERMAN_STUFF_UTF8 [] = { 0x47, 0x72, 0xC3, 0xBC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xC3, 0xA4, 0x6D, 0xC3, 0xA4 }; static final int RUSSIAN_STUFF_UNICODE [] = { 0x412, 0x441, 0x435, 0x43C, 0x5F, 0x43F, 0x440, 0x438, 0x432, 0x435, 0x442 }; static final int RUSSIAN_STUFF_UTF8 [] = { 0xD0, 0x92, 0xD1, 0x81, 0xD0, 0xB5, 0xD0, 0xBC, 0x5F, 0xD0, 0xBF, 0xD1, 0x80, 0xD0, 0xB8, 0xD0, 0xB2, 0xD0, 0xB5, 0xD1, 0x82 }; static final int RUSSIAN_STUFF_KOI8R [] = { 0xF7, 0xD3, 0xC5, 0xCD, 0x5F, 0xD0, 0xD2, 0xC9, 0xD7, 0xC5, 0xD4 }; static final int RUSSIAN_STUFF_WIN1251 [] = { 0xC2, 0xF1, 0xE5, 0xEC, 0x5F, 0xEF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2 }; // ------------------------------------------------------------ Constructor public TestMethodCharEncoding(final String testName) throws IOException { super(testName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestMethodCharEncoding.class); } // ----------------------------------------------------------------- Tests public void testRequestCharEncoding() throws IOException { GetMethod httpget = new GetMethod("/"); assertEquals(CHARSET_DEFAULT, httpget.getRequestCharSet()); httpget.setRequestHeader("Content-Type", "text/plain; charset=" + CHARSET_ASCII); assertEquals(CHARSET_ASCII, httpget.getRequestCharSet()); httpget.setRequestHeader("Content-Type", "text/plain; charset=" + CHARSET_UTF8); assertEquals(CHARSET_UTF8, httpget.getRequestCharSet()); } public void testNoExplicitCharEncoding() throws Exception { this.server.setHttpService(new EchoService()); GetMethod httpget = new GetMethod("/test/"); httpget.setRequestHeader("Content-Type", "text/plain"); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals(CHARSET_DEFAULT, httpget.getResponseCharSet()); } finally { httpget.releaseConnection(); } } public void testExplicitCharEncoding() throws Exception { this.server.setHttpService(new EchoService()); GetMethod httpget = new GetMethod("/test/"); httpget.setRequestHeader("Content-Type", "text/plain; charset=" + CHARSET_UTF8); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals(CHARSET_UTF8, httpget.getResponseCharSet()); } finally { httpget.releaseConnection(); } } private String constructString(int [] unicodeChars) { StringBuffer buffer = new StringBuffer(); if (unicodeChars != null) { for (int i = 0; i < unicodeChars.length; i++) { buffer.append((char)unicodeChars[i]); } } return buffer.toString(); } private void verifyEncoding(RequestEntity entity, int[] sample) throws IOException { assertNotNull("Request body", entity); ByteArrayOutputStream bos = new ByteArrayOutputStream(); entity.writeRequest(bos); InputStream instream = new ByteArrayInputStream(bos.toByteArray()); for (int i = 0; i < sample.length; i++) { int b = instream.read(); assertTrue("Unexpected end of stream", b != -1); if (sample[i] != b) { fail("Invalid request body encoding"); } } assertTrue("End of stream expected", instream.read() == -1); } public void testLatinAccentInRequestBody() throws IOException { PostMethod httppost = new PostMethod("/"); String s = constructString(SWISS_GERMAN_STUFF_UNICODE); // Test default encoding ISO-8859-1 httppost.setRequestEntity( new StringRequestEntity(s, "text/plain", CHARSET_DEFAULT)); verifyEncoding(httppost.getRequestEntity(), SWISS_GERMAN_STUFF_ISO8859_1); // Test UTF-8 encoding httppost.setRequestEntity( new StringRequestEntity(s, "text/plain", CHARSET_UTF8)); verifyEncoding(httppost.getRequestEntity(), SWISS_GERMAN_STUFF_UTF8); } public void testRussianInRequestBody() throws IOException { PostMethod httppost = new PostMethod("/"); String s = constructString(RUSSIAN_STUFF_UNICODE); // Test UTF-8 encoding httppost.setRequestEntity( new StringRequestEntity(s, "text/plain", CHARSET_UTF8)); verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_UTF8); // Test KOI8-R httppost.setRequestEntity( new StringRequestEntity(s, "text/plain", CHARSET_KOI8_R)); verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_KOI8R); // Test WIN1251 httppost.setRequestEntity( new StringRequestEntity(s, "text/plain", CHARSET_WIN1251)); verifyEncoding(httppost.getRequestEntity(), RUSSIAN_STUFF_WIN1251); } public void testQueryParams() throws Exception { GetMethod get = new GetMethod("/"); String ru_msg = constructString(RUSSIAN_STUFF_UNICODE); String ch_msg = constructString(SWISS_GERMAN_STUFF_UNICODE); get.setQueryString(new NameValuePair[] { new NameValuePair("ru", ru_msg), new NameValuePair("ch", ch_msg) }); Map params = new HashMap(); StringTokenizer tokenizer = new StringTokenizer( get.getQueryString(), "&"); while (tokenizer.hasMoreTokens()) { String s = tokenizer.nextToken(); int i = s.indexOf('='); assertTrue("Invalid url-encoded parameters", i != -1); String name = s.substring(0, i).trim(); String value = s.substring(i + 1, s.length()).trim(); value = URIUtil.decode(value, CHARSET_UTF8); params.put(name, value); } assertEquals(ru_msg, params.get("ru")); assertEquals(ch_msg, params.get("ch")); } public void testUrlEncodedRequestBody() throws Exception { PostMethod httppost = new PostMethod("/"); String ru_msg = constructString(RUSSIAN_STUFF_UNICODE); String ch_msg = constructString(SWISS_GERMAN_STUFF_UNICODE); httppost.setRequestBody(new NameValuePair[] { new NameValuePair("ru", ru_msg), new NameValuePair("ch", ch_msg) }); httppost.setRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE + "; charset=" + CHARSET_UTF8); ByteArrayOutputStream bos = new ByteArrayOutputStream(); httppost.getRequestEntity().writeRequest(bos); Map params = new HashMap(); StringTokenizer tokenizer = new StringTokenizer( new String(bos.toByteArray(), CHARSET_UTF8), "&"); while (tokenizer.hasMoreTokens()) { String s = tokenizer.nextToken(); int i = s.indexOf('='); assertTrue("Invalid url-encoded parameters", i != -1); String name = s.substring(0, i).trim(); String value = s.substring(i + 1, s.length()).trim(); value = URIUtil.decode(value, CHARSET_UTF8); params.put(name, value); } assertEquals(ru_msg, params.get("ru")); assertEquals(ch_msg, params.get("ch")); } public void testRequestEntityLength() throws IOException { String s = constructString(SWISS_GERMAN_STUFF_UNICODE); RequestEntity requestentity = new StringRequestEntity(s, "text/plain", CHARSET_UTF8); assertEquals( s.getBytes(CHARSET_UTF8).length, requestentity.getContentLength()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestMultipartPost.java100644 0 0 15146 10661532626 26332 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestMultipartPost.java,v 1.3 2004/11/01 02:21:15 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.PartSource; import org.apache.commons.httpclient.methods.multipart.StringPart; /** * Webapp tests specific to the MultiPostMethod. * * @author Oleg Kalnichevski */ public class TestMultipartPost extends HttpClientTestBase { public TestMultipartPost(final String testName) throws IOException { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(TestMultipartPost.class); ProxyTestDecorator.addTests(suite); return suite; } public static void main(String args[]) { String[] testCaseName = { TestMultipartPost.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------------------ Tests /** * Test that the body consisting of a string part can be posted. */ public void testPostStringPart() throws Exception { this.server.setHttpService(new EchoService()); PostMethod method = new PostMethod(); MultipartRequestEntity entity = new MultipartRequestEntity( new Part[] { new StringPart("param", "Hello", "ISO-8859-1") }, method.getParams()); method.setRequestEntity(entity); client.executeMethod(method); assertEquals(200,method.getStatusCode()); String body = method.getResponseBodyAsString(); assertTrue(body.indexOf("Content-Disposition: form-data; name=\"param\"") >= 0); assertTrue(body.indexOf("Content-Type: text/plain; charset=ISO-8859-1") >= 0); assertTrue(body.indexOf("Content-Transfer-Encoding: 8bit") >= 0); assertTrue(body.indexOf("Hello") >= 0); } /** * Test that the body consisting of a file part can be posted. */ public void testPostFilePart() throws Exception { this.server.setHttpService(new EchoService()); PostMethod method = new PostMethod(); byte[] content = "Hello".getBytes(); MultipartRequestEntity entity = new MultipartRequestEntity( new Part[] { new FilePart( "param1", new ByteArrayPartSource("filename.txt", content), "text/plain", "ISO-8859-1") }, method.getParams()); method.setRequestEntity(entity); client.executeMethod(method); assertEquals(200,method.getStatusCode()); String body = method.getResponseBodyAsString(); assertTrue(body.indexOf("Content-Disposition: form-data; name=\"param1\"; filename=\"filename.txt\"") >= 0); assertTrue(body.indexOf("Content-Type: text/plain; charset=ISO-8859-1") >= 0); assertTrue(body.indexOf("Content-Transfer-Encoding: binary") >= 0); assertTrue(body.indexOf("Hello") >= 0); } /** * Test that the body consisting of a file part of unknown length can be posted. */ public class TestPartSource implements PartSource { private String fileName; private byte[] data; public TestPartSource(String fileName, byte[] data) { this.fileName = fileName; this.data = data; } public long getLength() { return -1; } public String getFileName() { return fileName; } public InputStream createInputStream() throws IOException { return new ByteArrayInputStream(data); } } public void testPostFilePartUnknownLength() throws Exception { this.server.setHttpService(new EchoService()); String enc = "ISO-8859-1"; PostMethod method = new PostMethod(); byte[] content = "Hello".getBytes(enc); MultipartRequestEntity entity = new MultipartRequestEntity( new Part[] { new FilePart( "param1", new TestPartSource("filename.txt", content), "text/plain", enc) }, method.getParams()); method.setRequestEntity(entity); client.executeMethod(method); assertEquals(200,method.getStatusCode()); String body = method.getResponseBodyAsString(); assertTrue(body.indexOf("Content-Disposition: form-data; name=\"param1\"; filename=\"filename.txt\"") >= 0); assertTrue(body.indexOf("Content-Type: text/plain; charset="+enc) >= 0); assertTrue(body.indexOf("Content-Transfer-Encoding: binary") >= 0); assertTrue(body.indexOf("Hello") >= 0); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestNVP.java100644 0 0 7716 10661532626 24132 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestNVP.java,v 1.5 2004/02/22 18:08:49 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import junit.framework.*; /** * Simple tests for {@link NameValuePair}. * * @author Rodney Waldhoff * @version $Id: TestNVP.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestNVP extends TestCase { // ------------------------------------------------------------ Constructor public TestNVP(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestNVP.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestNVP.class); } // ------------------------------------------------------ Protected Methods protected NameValuePair makePair() { return new NameValuePair(); } protected NameValuePair makePair(String name, String value) { return new NameValuePair(name,value); } // ----------------------------------------------------------- Test Methods public void testGet() { NameValuePair pair = makePair("name 1","value 1"); assertEquals("name 1",pair.getName()); assertEquals("value 1",pair.getValue()); } public void testSet() { NameValuePair pair = makePair(); assertTrue(null == pair.getName()); assertTrue(null == pair.getValue()); pair.setName("name"); assertEquals("name",pair.getName()); pair.setValue("value"); assertEquals("value",pair.getValue()); } public void testHashCode() { NameValuePair param1 = new NameValuePair("name1", "value1"); NameValuePair param2 = new NameValuePair("name2", "value2"); NameValuePair param3 = new NameValuePair("name1", "value1"); assertTrue(param1.hashCode() != param2.hashCode()); assertTrue(param1.hashCode() == param3.hashCode()); } public void testEquals() { NameValuePair param1 = new NameValuePair("name1", "value1"); NameValuePair param2 = new NameValuePair("name2", "value2"); NameValuePair param3 = new NameValuePair("name1", "value1"); assertFalse(param1.equals(param2)); assertFalse(param1.equals(null)); assertFalse(param1.equals("name1 = value1")); assertTrue(param1.equals(param1)); assertTrue(param2.equals(param2)); assertTrue(param1.equals(param3)); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestNoHost.java100644 0 0 4240 10661532626 24666 0ustar 0 0 /* * $HeadURL: * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Tests that don't require any external host. * I.e., that run entirely within this JVM. * * (True unit tests, by some definitions.) * * @author Rodney Waldhoff * @author Jeff Dever * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * @deprecated Use TestAll */ public class TestNoHost extends TestCase { public TestNoHost(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestAll.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = { TestNoHost.class.getName() }; junit.textui.TestRunner.main(testCaseName); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestNoncompliant.java100644 0 0 21270 10661532630 26132 0ustar 0 0 /* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.IOException; import junit.framework.*; import org.apache.commons.httpclient.methods.*; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.server.HttpRequestHandler; import org.apache.commons.httpclient.server.ResponseWriter; import org.apache.commons.httpclient.server.SimpleHttpServerConnection; import org.apache.commons.httpclient.server.SimpleRequest; /** * Tests handling of non-compliant responses. * * @author Oleg Kalnichevski * @author Jeff Dever */ public class TestNoncompliant extends HttpClientTestBase { public TestNoncompliant(String s) throws IOException { super(s); } public static Test suite() { TestSuite suite = new TestSuite(TestNoncompliant.class); return suite; } /** * Tests if client is able to recover gracefully when HTTP server or * proxy fails to send 100 status code when expected. The client should * resume sending the request body after a defined timeout without having * received "continue" code. */ public void testNoncompliantPostMethodString() throws Exception { this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println("Connection: close"); out.println("Content-Length: 0"); out.println(); out.flush(); return true; } }); PostMethod method = new PostMethod("/"); method.getParams().setBooleanParameter( HttpMethodParams.USE_EXPECT_CONTINUE, true); method.setRequestEntity(new StringRequestEntity( "This is data to be sent in the body of an HTTP POST.", null, null)); client.executeMethod(method); assertEquals(200, method.getStatusCode()); } /** * Tests that a response status line containing \r and \n is handled. */ public void testNoncompliantStatusLine() { this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 444 This status message contains\n" + " a newline and a\r" + " carrage return but that should be OK."); out.println("Connection: close"); out.println("Content-Length: 0"); out.println(); out.flush(); return true; } }); GetMethod method = new GetMethod("/"); try { client.executeMethod(method); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception: " + e.toString()); } assertEquals(444, method.getStatusCode()); } /** * Test if a response to HEAD method from non-compliant server that contains * an unexpected body content can be correctly redirected */ public void testNoncompliantHeadWithResponseBody() throws Exception { final String body = "Test body"; this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println("Connection: close"); out.println("Content-Length: " + body.length()); out.println(); out.print(body); out.flush(); return true; } }); HeadMethod method = new HeadMethod("/"); method.getParams().setIntParameter( HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, 50); client.executeMethod(method); assertEquals(200, method.getStatusCode()); method.releaseConnection(); } /** * Test if a response to HEAD method from non-compliant server causes an * HttpException to be thrown */ public void testNoncompliantHeadStrictMode() throws Exception { final String body = "Test body"; this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println("Connection: close"); out.println("Content-Length: " + body.length()); out.println(); out.print(body); out.flush(); return true; } }); client.getParams().setBooleanParameter( HttpMethodParams.REJECT_HEAD_BODY, true); HeadMethod method = new NoncompliantHeadMethod("/"); method.getParams().setIntParameter( HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, 50); try { client.executeMethod(method); fail("HttpException should have been thrown"); } catch (HttpException e) { // Expected } method.releaseConnection(); } /** * Tests if client is able to handle gracefully malformed responses * that may not include response body. */ public void testMalformed304Response() throws Exception { this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { conn.setSocketTimeout(20000); ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 304 OK"); out.println("Connection: keep-alive"); out.println("Content-Length: 100"); out.println(); out.flush(); conn.setKeepAlive(true); return true; } }); GetMethod method = new GetMethod("/"); method.getParams().setSoTimeout(1000); client.executeMethod(method); assertEquals(HttpStatus.SC_NOT_MODIFIED, method.getStatusCode()); method.getResponseBody(); } public void testMalformed204Response() throws Exception { this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { conn.setSocketTimeout(20000); ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 204 OK"); out.println("Connection: close"); out.println("Content-Length: 100"); out.println(); out.flush(); conn.setKeepAlive(true); return true; } }); GetMethod method = new GetMethod("/"); method.getParams().setSoTimeout(1000); client.executeMethod(method); assertEquals(HttpStatus.SC_NO_CONTENT, method.getStatusCode()); method.getResponseBody(); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestParameterFormatter.java100644 0 0 10206 10661532627 27300 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestParameterFormatter.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.util.ParameterFormatter; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit tests for {@link ParameterFormatter}. * * @author Oleg Kalnichevski */ public class TestParameterFormatter extends TestCase { // ------------------------------------------------------------ Constructor public TestParameterFormatter(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestParameterFormatter.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestParameterFormatter.class); } public void testBasicValueFormatting() throws Exception { ParameterFormatter formatter = new ParameterFormatter(); NameValuePair param1 = new NameValuePair("param", "regular_stuff"); NameValuePair param2 = new NameValuePair("param", "this\\that"); NameValuePair param3 = new NameValuePair("param", "this,that"); NameValuePair param4 = new NameValuePair("param", "quote marks (\") must be escaped"); NameValuePair param5 = new NameValuePair("param", "back slash (\\) must be escaped too"); NameValuePair param6 = new NameValuePair("param", "values with\tblanks must always be quoted"); formatter.setAlwaysUseQuotes(false); assertEquals("param=regular_stuff", formatter.format(param1)); assertEquals("param=\"this\\\\that\"", formatter.format(param2)); assertEquals("param=\"this,that\"", formatter.format(param3)); assertEquals("param=\"quote marks (\\\") must be escaped\"", formatter.format(param4)); assertEquals("param=\"back slash (\\\\) must be escaped too\"", formatter.format(param5)); assertEquals("param=\"values with\tblanks must always be quoted\"", formatter.format(param6)); formatter.setAlwaysUseQuotes(true); assertEquals("param=\"regular_stuff\"", formatter.format(param1)); assertEquals("param=\"this\\\\that\"", formatter.format(param2)); assertEquals("param=\"this,that\"", formatter.format(param3)); assertEquals("param=\"quote marks (\\\") must be escaped\"", formatter.format(param4)); assertEquals("param=\"back slash (\\\\) must be escaped too\"", formatter.format(param5)); assertEquals("param=\"values with\tblanks must always be quoted\"", formatter.format(param6)); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestParameterParser.java100644 0 0 13660 10661532626 26577 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestParameterParser.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.util.List; import org.apache.commons.httpclient.util.ParameterParser; /** * Unit tests for {@link ParameterParser}. * * @author Oleg Kalnichevski */ public class TestParameterParser extends TestCase { // ------------------------------------------------------------ Constructor public TestParameterParser(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestParameterParser.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestParameterParser.class); } public void testParsing() { String s = "test; test1 = stuff ; test2 = \"stuff; stuff\"; test3=\"stuff"; ParameterParser parser = new ParameterParser(); List params = parser.parse(s, ';'); assertEquals("test", ((NameValuePair)params.get(0)).getName()); assertEquals(null, ((NameValuePair)params.get(0)).getValue()); assertEquals("test1", ((NameValuePair)params.get(1)).getName()); assertEquals("stuff", ((NameValuePair)params.get(1)).getValue()); assertEquals("test2", ((NameValuePair)params.get(2)).getName()); assertEquals("stuff; stuff", ((NameValuePair)params.get(2)).getValue()); assertEquals("test3", ((NameValuePair)params.get(3)).getName()); assertEquals("\"stuff", ((NameValuePair)params.get(3)).getValue()); s = " test , test1=stuff , , test2=, test3, "; params = parser.parse(s, ','); assertEquals("test", ((NameValuePair)params.get(0)).getName()); assertEquals(null, ((NameValuePair)params.get(0)).getValue()); assertEquals("test1", ((NameValuePair)params.get(1)).getName()); assertEquals("stuff", ((NameValuePair)params.get(1)).getValue()); assertEquals("test2", ((NameValuePair)params.get(2)).getName()); assertEquals("", ((NameValuePair)params.get(2)).getValue()); assertEquals("test3", ((NameValuePair)params.get(3)).getName()); assertEquals(null, ((NameValuePair)params.get(3)).getValue()); s = " test"; params = parser.parse(s, ';'); assertEquals("test", ((NameValuePair)params.get(0)).getName()); assertEquals(null, ((NameValuePair)params.get(0)).getValue()); s = " "; params = parser.parse(s, ';'); assertEquals(0, params.size()); s = " = stuff "; params = parser.parse(s, ';'); assertEquals(1, params.size()); assertEquals("", ((NameValuePair)params.get(0)).getName()); assertEquals("stuff", ((NameValuePair)params.get(0)).getValue()); } public void testParsingEscapedChars() { String s = "param = \"stuff\\\"; more stuff\""; ParameterParser parser = new ParameterParser(); List params = parser.parse(s, ';'); assertEquals(1, params.size()); assertEquals("param", ((NameValuePair)params.get(0)).getName()); assertEquals("stuff\\\"; more stuff", ((NameValuePair)params.get(0)).getValue()); s = "param = \"stuff\\\\\"; anotherparam"; params = parser.parse(s, ';'); assertEquals(2, params.size()); assertEquals("param", ((NameValuePair)params.get(0)).getName()); assertEquals("stuff\\\\", ((NameValuePair)params.get(0)).getValue()); assertEquals("anotherparam", ((NameValuePair)params.get(1)).getName()); assertNull( ((NameValuePair)params.get(1)).getValue()); } public void testParsingBlankParams() { String s = "test; test1 = ; test2 = \"\""; ParameterParser parser = new ParameterParser(); List params = parser.parse(s, ';'); assertEquals("test", ((NameValuePair)params.get(0)).getName()); assertEquals(null, ((NameValuePair)params.get(0)).getValue()); assertEquals("test1", ((NameValuePair)params.get(1)).getName()); assertEquals("", ((NameValuePair)params.get(1)).getValue()); assertEquals("test2", ((NameValuePair)params.get(2)).getName()); assertEquals("", ((NameValuePair)params.get(2)).getValue()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestPartsNoHost.java100644 0 0 10600 10661532626 25715 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestPartsNoHost.java,v 1.7 2004/02/22 18:08:49 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.StringPart; /** * @author Adrian Sutton * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ */ public class TestPartsNoHost extends TestCase { static final String PART_DATA = "This is the part data."; static final String NAME = "name"; // ------------------------------------------------------------ Constructor public TestPartsNoHost(String testName) { super(testName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestPartsNoHost.class); } // ----------------------------------------------------------------- Tests public void testFilePartResendsFileData() throws Exception { File file = createTempTestFile(); FilePart part = new FilePart(NAME, file); ByteArrayOutputStream stream = new ByteArrayOutputStream(); part.send(stream); String resp1 = stream.toString(); stream = new ByteArrayOutputStream(); part.send(stream); String resp2 = stream.toString(); file.delete(); assertEquals(resp1, resp2); } public void testStringPartResendsData() throws Exception { StringPart part = new StringPart(NAME, PART_DATA); ByteArrayOutputStream stream = new ByteArrayOutputStream(); part.send(stream); String resp1 = stream.toString(); stream = new ByteArrayOutputStream(); part.send(stream); String resp2 = stream.toString(); assertEquals(resp1, resp2); } public void testFilePartNullFileResendsData() throws Exception { FilePart part = new FilePart(NAME, "emptyfile.ext", null); ByteArrayOutputStream stream = new ByteArrayOutputStream(); part.send(stream); String resp1 = stream.toString(); stream = new ByteArrayOutputStream(); part.send(stream); String resp2 = stream.toString(); assertEquals(resp1, resp2); } /** Writes PART_DATA out to a temporary file and returns the file it * was written to. * @return the File object representing the file the data was * written to. */ private File createTempTestFile() throws IOException { File file = File.createTempFile("FilePartTest", ".txt"); PrintWriter out = new PrintWriter(new FileWriter(file)); out.println(PART_DATA); out.flush(); out.close(); return file; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestPostMethod.java100644 0 0 16513 10661532626 25570 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestWebappPostMethod.java,v 1.7 2004/05/12 20:43:54 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import junit.framework.*; import org.apache.commons.httpclient.methods.*; import java.io.*; /** * Webapp tests specific to the PostMethod. * * @author Jeff Dever * @version $Id: TestPostMethod.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestPostMethod extends HttpClientTestBase { public TestPostMethod(String testName) throws IOException { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(TestPostMethod.class); return suite; } public static void main(String args[]) { String[] testCaseName = { TestPostMethod.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------------------ Tests /** * Test that the body can be set as a array of parameters */ public void testParametersBodyToParamServlet() throws Exception { PostMethod method = new PostMethod("/"); NameValuePair[] parametersBody = new NameValuePair[] { new NameValuePair("pname1","pvalue1"), new NameValuePair("pname2","pvalue2") }; method.setRequestBody(parametersBody); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals("pname1=pvalue1&pname2=pvalue2", body); } finally { method.releaseConnection(); } } /** * Test that the body can be set as a String */ public void testStringBodyToParamServlet() throws Exception { PostMethod method = new PostMethod("/"); String stringBody = "pname1=pvalue1&pname2=pvalue2"; method.setRequestEntity( new StringRequestEntity(stringBody, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE, null)); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals("pname1=pvalue1&pname2=pvalue2", body); } finally { method.releaseConnection(); } } /** * Test that the body can be set as a String without an explict * content type */ public void testStringBodyToBodyServlet() throws Exception { PostMethod method = new PostMethod("/"); String stringBody = "pname1=pvalue1&pname2=pvalue2"; method.setRequestEntity(new StringRequestEntity(stringBody, null, null)); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals("pname1=pvalue1&pname2=pvalue2", body); } finally { method.releaseConnection(); } } /** * Test that parameters can be added. */ public void testAddParametersToParamServlet() throws Exception { PostMethod method = new PostMethod("/"); method.addParameter(new NameValuePair("pname1","pvalue1")); method.addParameter(new NameValuePair("pname2","pvalue2")); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals("pname1=pvalue1&pname2=pvalue2", body); } finally { method.releaseConnection(); } } /** * Test that parameters can be added and removed. */ public void testAddRemoveParametersToParamServlet() throws Exception { PostMethod method = new PostMethod("/"); method.addParameter(new NameValuePair("pname0","pvalue0")); method.addParameter(new NameValuePair("pname1","pvalue1")); method.addParameter(new NameValuePair("pname2","pvalue2")); method.addParameter(new NameValuePair("pname3","pvalue3")); method.removeParameter("pname0"); method.removeParameter("pname3"); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals("pname1=pvalue1&pname2=pvalue2", body); } finally { method.releaseConnection(); } } /** * Test the return value of the PostMethod#removeParameter. */ public void testRemoveParameterReturnValue() throws Exception { PostMethod method = new PostMethod("/"); method.addParameter("param", "whatever"); assertTrue("Return value of the method is expected to be true", method.removeParameter("param")); assertFalse("Return value of the method is expected to be false", method.removeParameter("param")); } private String getRequestAsString(RequestEntity entity) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); entity.writeRequest(bos); return new String(bos.toByteArray(), "UTF-8"); } /** * Test if setParameter overwrites existing parameter values. */ public void testAddParameterFollowedBySetParameter() throws Exception { PostMethod method = new PostMethod("/"); method.addParameter("param", "a"); method.addParameter("param", "b"); method.addParameter("param", "c"); assertEquals("param=a¶m=b¶m=c", getRequestAsString(method.getRequestEntity())); method.setParameter("param", "a"); assertEquals("param=a", getRequestAsString(method.getRequestEntity())); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestPostParameterEncoding.java100644 0 0 10746 10661532626 27741 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestPostMethod.java,v 1.5 2004/12/12 10:02:38 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.ByteArrayOutputStream; import java.io.IOException; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; /** * Tests basic method functionality. * * @author Remy Maucherat * @author Rodney Waldhoff * * @version $Id: TestPostParameterEncoding.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestPostParameterEncoding extends TestCase { static final String NAME = "name", VALUE = "value"; static final String NAME0 = "name0", VALUE0 = "value0"; static final String NAME1 = "name1", VALUE1 = "value1"; static final String NAME2 = "name2", VALUE2 = "value2"; static final NameValuePair PAIR = new NameValuePair(NAME, VALUE); static final NameValuePair PAIR0 = new NameValuePair(NAME0, VALUE0); static final NameValuePair PAIR1 = new NameValuePair(NAME1, VALUE1); static final NameValuePair PAIR2 = new NameValuePair(NAME2, VALUE2); public TestPostParameterEncoding(final String testName) throws IOException { super(testName); } public static Test suite() { return new TestSuite(TestPostParameterEncoding.class); } public static void main(String args[]) { String[] testCaseName = { TestPostParameterEncoding.class.getName() }; junit.textui.TestRunner.main(testCaseName); } private String getRequestAsString(RequestEntity entity) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); entity.writeRequest(bos); return new String(bos.toByteArray(), "UTF-8"); } public void testPostParametersEncoding() throws Exception { PostMethod post = new PostMethod(); post.setRequestBody(new NameValuePair[] { PAIR }); assertEquals("name=value", getRequestAsString(post.getRequestEntity())); post.setRequestBody(new NameValuePair[]{ PAIR, PAIR1, PAIR2 }); assertEquals("name=value&name1=value1&name2=value2", getRequestAsString(post.getRequestEntity())); post.setRequestBody(new NameValuePair[]{ PAIR, PAIR1, PAIR2, new NameValuePair("hasSpace", "a b c d") }); assertEquals("name=value&name1=value1&name2=value2&hasSpace=a+b+c+d", getRequestAsString(post.getRequestEntity())); post.setRequestBody(new NameValuePair[]{ new NameValuePair("escaping", ",.-\u00f6\u00e4\u00fc!+@#*&()=?:;}{[]$") }); assertEquals("escaping=%2C.-%F6%E4%FC%21%2B%40%23*%26%28%29%3D%3F%3A%3B%7D%7B%5B%5D%24", getRequestAsString(post.getRequestEntity())); } public void testPostSetRequestBody() throws Exception { PostMethod post = new PostMethod("/foo"); String body = "this+is+the+body"; post.setRequestEntity(new StringRequestEntity(body, null, null)); assertEquals(body, getRequestAsString(post.getRequestEntity())); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestProxy.java100644 0 0 74765 10661532626 24640 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestProxy.java,v 1.11 2004/12/11 22:35:26 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import java.util.Enumeration; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.auth.AuthScheme; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.auth.CredentialsNotAvailableException; import org.apache.commons.httpclient.auth.CredentialsProvider; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.server.AuthRequestHandler; import org.apache.commons.httpclient.server.HttpRequestHandlerChain; import org.apache.commons.httpclient.server.HttpServiceHandler; /** * Tests for proxied connections. * * @author Ortwin Glueck * @author Oleg Kalnichevski */ public class TestProxy extends HttpClientTestBase { public TestProxy(String testName) throws IOException { super(testName); setUseProxy(true); } static class SSLDecorator extends TestSetup { public static void addTests(TestSuite suite) { TestSuite ts2 = new TestSuite(); addTest(ts2, suite); suite.addTest(ts2); } private static void addTest(TestSuite suite, Test t) { if (t instanceof TestProxy) { suite.addTest(new SSLDecorator((TestProxy) t)); } else if (t instanceof TestSuite) { Enumeration en = ((TestSuite) t).tests(); while (en.hasMoreElements()) { addTest(suite, (Test) en.nextElement()); } } } public SSLDecorator(TestProxy test) { super(test); } protected void setUp() throws Exception { TestProxy base = (TestProxy)getTest(); base.setUseSSL(true); } } public static Test suite() { TestSuite suite = new TestSuite(TestProxy.class); SSLDecorator.addTests(suite); return suite; } class GetItWrongThenGetItRight implements CredentialsProvider { private int hostcount = 0; private int proxycount = 0; public GetItWrongThenGetItRight() { super(); } public Credentials getCredentials(AuthScheme scheme, String host, int port, boolean proxy) throws CredentialsNotAvailableException { if (!proxy) { this.hostcount++; return provideCredentials(this.hostcount); } else { this.proxycount++; return provideCredentials(this.proxycount); } } private Credentials provideCredentials(int count) { switch (count) { case 1: return new UsernamePasswordCredentials("testuser", "wrongstuff"); case 2: return new UsernamePasswordCredentials("testuser", "testpass"); default: return null; } } } /** * Tests GET via non-authenticating proxy */ public void testSimpleGet() throws Exception { this.server.setHttpService(new FeedbackService()); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests GET via non-authenticating proxy + host auth + connection keep-alive */ public void testGetHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests GET via non-authenticating proxy + host auth + connection close */ public void testGetHostAuthConnClose() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests GET via non-authenticating proxy + invalid host auth */ public void testGetHostInvalidAuth() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testuser", "wrongstuff")); this.server.setRequestHandler(handlerchain); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_UNAUTHORIZED, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests GET via non-authenticating proxy + interactive host auth + connection keep-alive */ public void testGetInteractiveHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getParams().setParameter(CredentialsProvider.PROVIDER, new GetItWrongThenGetItRight()); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests GET via non-authenticating proxy + interactive host auth + connection close */ public void testGetInteractiveHostAuthConnClose() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getParams().setParameter(CredentialsProvider.PROVIDER, new GetItWrongThenGetItRight()); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests GET via authenticating proxy + host auth + connection keep-alive */ public void testGetProxyAuthHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests GET via authenticating proxy */ public void testGetAuthProxy() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.server.setHttpService(new FeedbackService()); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests GET via authenticating proxy + host auth + connection close */ public void testGetProxyAuthHostAuthConnClose() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests GET via authenticating proxy + invalid host auth */ public void testGetProxyAuthHostInvalidAuth() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testuser", "wrongstuff")); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_UNAUTHORIZED, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests GET via authenticating proxy + interactive host and proxy auth + connection keep-alive */ public void testGetInteractiveProxyAuthHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getParams().setParameter(CredentialsProvider.PROVIDER, new GetItWrongThenGetItRight()); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests GET via authenticating proxy + interactive host and proxy auth + connection close */ public void testGetInteractiveProxyAuthHostAuthConnClose() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getParams().setParameter(CredentialsProvider.PROVIDER, new GetItWrongThenGetItRight()); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } /** * Tests POST via non-authenticating proxy */ public void testSimplePost() throws Exception { this.server.setHttpService(new FeedbackService()); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } } /** * Tests POST via non-authenticating proxy + host auth + connection keep-alive */ public void testPostHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } } /** * Tests POST via non-authenticating proxy + host auth + connection close */ public void testPostHostAuthConnClose() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } } /** * Tests POST via non-authenticating proxy + invalid host auth */ public void testPostHostInvalidAuth() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testuser", "wrongstuff")); this.server.setRequestHandler(handlerchain); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_UNAUTHORIZED, post.getStatusCode()); } finally { post.releaseConnection(); } } /** * Tests POST via non-authenticating proxy + interactive host auth + connection keep-alive */ public void testPostInteractiveHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getParams().setParameter(CredentialsProvider.PROVIDER, new GetItWrongThenGetItRight()); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } } /** * Tests POST via non-authenticating proxy + interactive host auth + connection close */ public void testPostInteractiveHostAuthConnClose() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getParams().setParameter(CredentialsProvider.PROVIDER, new GetItWrongThenGetItRight()); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } } /** * Tests POST via authenticating proxy */ public void testPostAuthProxy() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.server.setHttpService(new FeedbackService()); this.proxy.requireAuthentication(creds, "test", true); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } } /** * Tests POST via authenticating proxy + host auth + connection keep-alive */ public void testPostProxyAuthHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } } /** * Tests POST via authenticating proxy + host auth + connection close */ public void testPostProxyAuthHostAuthConnClose() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } } /** * Tests POST via non-authenticating proxy + invalid host auth */ public void testPostProxyAuthHostInvalidAuth() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testuser", "wrongstuff")); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_UNAUTHORIZED, post.getStatusCode()); } finally { post.releaseConnection(); } } /** * Tests POST via non-authenticating proxy + interactive host auth + connection keep-alive */ public void testPostInteractiveProxyAuthHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getParams().setParameter(CredentialsProvider.PROVIDER, new GetItWrongThenGetItRight()); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } } /** * Tests POST via non-authenticating proxy + interactive host auth + connection close */ public void testPostInteractiveProxyAuthHostAuthConnClose() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getParams().setParameter(CredentialsProvider.PROVIDER, new GetItWrongThenGetItRight()); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } } public void testPreemptiveAuthProxy() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.client.getParams().setAuthenticationPreemptive(true); this.server.setHttpService(new FeedbackService()); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); if (isUseSSL()) { assertNull(get.getRequestHeader("Proxy-Authorization")); } else { assertNotNull(get.getRequestHeader("Proxy-Authorization")); } } finally { get.releaseConnection(); } } /** * Tests GET via authenticating proxy + host auth + HTTP/1.0 */ public void testGetProxyAuthHostAuthHTTP10() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.client.getParams().setVersion(HttpVersion.HTTP_1_0); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", false); GetMethod get = new GetMethod("/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestProxyWithRedirect.java100644 0 0 12343 10661532627 27137 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestProxyWithRedirect.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.server.RequestLine; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * Tests for proxied connections. * * @author Ortwin Glueck * @author Oleg Kalnichevski */ public class TestProxyWithRedirect extends HttpClientTestBase { public TestProxyWithRedirect(String testName) throws IOException { super(testName); setUseProxy(true); } public static Test suite() { return new TestSuite(TestProxyWithRedirect.class); } private class BasicRedirectService extends EchoService { private String location = null; public BasicRedirectService(final String location) { super(); this.location = location; } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine reqline = request.getRequestLine(); HttpVersion ver = reqline.getHttpVersion(); if (reqline.getUri().equals("/redirect/")) { response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new Header("Location", this.location)); response.addHeader(new Header("Connection", "Close")); return true; } else { return super.process(request, response); } } } public void testAuthProxyWithRedirect() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.server.setHttpService(new BasicRedirectService("/")); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/redirect/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } public void testAuthProxyWithCrossSiteRedirect() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.server.setHttpService(new BasicRedirectService( "http://127.0.0.1:" + this.server.getLocalPort())); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/redirect/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } public void testPreemptiveAuthProxyWithCrossSiteRedirect() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.client.getParams().setAuthenticationPreemptive(true); this.server.setHttpService(new BasicRedirectService( "http://127.0.0.1:" + this.server.getLocalPort())); this.proxy.requireAuthentication(creds, "test", true); GetMethod get = new GetMethod("/redirect/"); try { this.client.executeMethod(get); assertEquals(HttpStatus.SC_OK, get.getStatusCode()); } finally { get.releaseConnection(); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestQueryParameters.java100644 0 0 23402 10661532630 26621 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestQueryParameters.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import junit.framework.*; import org.apache.commons.httpclient.methods.*; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * @author Rodney Waldhoff * @version $Id: TestQueryParameters.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestQueryParameters extends HttpClientTestBase { public TestQueryParameters(String testName) throws Exception { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(TestQueryParameters.class); return suite; } public static void main(String args[]) { String[] testCaseName = { TestQueryParameters.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------------------ Tests class QueryInfoService implements HttpService { public QueryInfoService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Content-Type", "text/plain")); URI uri = new URI(request.getRequestLine().getUri(), true); StringBuffer buffer = new StringBuffer(); buffer.append("QueryString=\""); buffer.append(uri.getQuery()); buffer.append("\"\r\n"); response.setBodyString(buffer.toString()); return true; } } /** * Test that {@link GetMethod#setQueryString(java.lang.String)} * can include a leading question mark. */ public void testGetMethodQueryString() throws Exception { this.server.setHttpService(new QueryInfoService()); GetMethod method = new GetMethod("/"); method.setQueryString("?hadQuestionMark=true"); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String response = method.getResponseBodyAsString(); assertTrue(response.indexOf("QueryString=\"hadQuestionMark=true\"") >= 0); } finally { method.releaseConnection(); } } /** * Test that {@link GetMethod#setQueryString(java.lang.String)} * doesn't have to include a leading question mark. */ public void testGetMethodQueryString2() throws Exception { this.server.setHttpService(new QueryInfoService()); GetMethod method = new GetMethod("/"); method.setQueryString("hadQuestionMark=false"); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String response = method.getResponseBodyAsString(); assertTrue(response.indexOf("QueryString=\"hadQuestionMark=false\"") >= 0); } finally { method.releaseConnection(); } } /** * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)} * values get added to the query string. */ public void testGetMethodParameters() throws Exception { this.server.setHttpService(new QueryInfoService()); GetMethod method = new GetMethod("/"); method.setQueryString(new NameValuePair[] { new NameValuePair("param-one","param-value") }); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String response = method.getResponseBodyAsString(); assertTrue(response.indexOf("QueryString=\"param-one=param-value\"") >= 0); } finally { method.releaseConnection(); } } /** * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)} * works with multiple parameters. */ public void testGetMethodMultiParameters() throws Exception { this.server.setHttpService(new QueryInfoService()); GetMethod method = new GetMethod("/"); method.setQueryString(new NameValuePair[] { new NameValuePair("param-one","param-value"), new NameValuePair("param-two","param-value2"), new NameValuePair("special-chars",":/?~.") }); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String response = method.getResponseBodyAsString(); assertTrue(response.indexOf("QueryString=\"param-one=param-value¶m-two=param-value2&special-chars=:/?~.\"") >= 0); } finally { method.releaseConnection(); } } /** * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)} * works with a parameter name but no value. */ public void testGetMethodParameterWithoutValue() throws Exception { this.server.setHttpService(new QueryInfoService()); GetMethod method = new GetMethod("/"); method.setQueryString(new NameValuePair[] { new NameValuePair("param-without-value", null) }); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String response = method.getResponseBodyAsString(); assertTrue(response.indexOf("QueryString=\"param-without-value=\"") >= 0); } finally { method.releaseConnection(); } } /** * Test that {@link GetMethod#addParameter(java.lang.String,java.lang.String)} * works with a parameter name that occurs more than once. */ public void testGetMethodParameterAppearsTwice() throws Exception { this.server.setHttpService(new QueryInfoService()); GetMethod method = new GetMethod("/"); method.setQueryString(new NameValuePair[] { new NameValuePair("foo","one"), new NameValuePair("foo","two") }); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String response = method.getResponseBodyAsString(); assertTrue(response.indexOf("QueryString=\"foo=one&foo=two\"") >= 0); } finally { method.releaseConnection(); } } public void testGetMethodOverwriteQueryString() throws Exception { this.server.setHttpService(new QueryInfoService()); GetMethod method = new GetMethod("/"); method.setQueryString("query=string"); method.setQueryString(new NameValuePair[] { new NameValuePair("param","eter"), new NameValuePair("para","meter") }); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String response = method.getResponseBodyAsString(); assertFalse(response.indexOf("QueryString=\"query=string\"") >= 0); assertTrue(response.indexOf("QueryString=\"param=eter¶=meter\"") >= 0); } finally { method.releaseConnection(); } } /** * Test that {@link PostMethod#addParameter(java.lang.String,java.lang.String)} * and {@link PostMethod#setQueryString(java.lang.String)} combine * properly. */ public void testPostMethodParameterAndQueryString() throws Exception { this.server.setHttpService(new QueryInfoService()); PostMethod method = new PostMethod("/"); method.setQueryString("query=string"); method.setRequestBody(new NameValuePair[] { new NameValuePair("param","eter"), new NameValuePair("para","meter") } ); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String response = method.getResponseBodyAsString(); assertTrue(response.indexOf("QueryString=\"query=string\"") >= 0); assertFalse(response.indexOf("QueryString=\"param=eter¶=meter\"") >= 0); } finally { method.releaseConnection(); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestRedirects.java100644 0 0 52261 10661532630 25421 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestRedirects.java,v 1.9 2005/01/14 19:40:39 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import java.io.IOException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.RequestLine; import org.apache.commons.httpclient.server.SimpleHttpServer; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * Redirection test cases. * * @author Oleg Kalnichevski * * @version $Id: TestRedirects.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestRedirects extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestRedirects(final String testName) throws IOException { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestRedirects.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { TestSuite suite = new TestSuite(TestRedirects.class); ProxyTestDecorator.addTests(suite); return suite; } private class BasicRedirectService implements HttpService { private int statuscode = HttpStatus.SC_MOVED_TEMPORARILY; private String host = null; private int port; public BasicRedirectService(final String host, int port, int statuscode) { super(); this.host = host; this.port = port; if (statuscode > 0) { this.statuscode = statuscode; } } public BasicRedirectService(final String host, int port) { this(host, port, -1); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine reqline = request.getRequestLine(); HttpVersion ver = reqline.getHttpVersion(); if (reqline.getUri().equals("/oldlocation/")) { response.setStatusLine(ver, this.statuscode); response.addHeader(new Header("Location", "http://" + this.host + ":" + this.port + "/newlocation/")); response.addHeader(new Header("Connection", "close")); } else if (reqline.getUri().equals("/newlocation/")) { response.setStatusLine(ver, HttpStatus.SC_OK); response.setBodyString("Successful redirect"); } else { response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND); } return true; } } private class CircularRedirectService implements HttpService { private int invocations = 0; public CircularRedirectService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine reqline = request.getRequestLine(); HttpVersion ver = reqline.getHttpVersion(); if (reqline.getUri().startsWith("/circular-oldlocation")) { response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new Header("Location", "/circular-location2?invk=" + (++this.invocations))); } else if (reqline.getUri().startsWith("/circular-location2")) { response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new Header("Location", "/circular-oldlocation?invk=" + (++this.invocations))); } else { response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND); } return true; } } private class RelativeRedirectService implements HttpService { public RelativeRedirectService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine reqline = request.getRequestLine(); HttpVersion ver = reqline.getHttpVersion(); if (reqline.getUri().equals("/oldlocation/")) { response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new Header("Location", "/relativelocation/")); } else if (reqline.getUri().equals("/relativelocation/")) { response.setStatusLine(ver, HttpStatus.SC_OK); response.setBodyString("Successful redirect"); } else { response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND); } return true; } } private class BogusRedirectService implements HttpService { private String url; public BogusRedirectService(String redirectUrl) { super(); this.url = redirectUrl; } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine reqline = request.getRequestLine(); HttpVersion ver = reqline.getHttpVersion(); if (reqline.getUri().equals("/oldlocation/")) { response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new Header("Location", url)); } else if (reqline.getUri().equals("/relativelocation/")) { response.setStatusLine(ver, HttpStatus.SC_OK); response.setBodyString("Successful redirect"); } else { response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND); } return true; } } public void testBasicRedirect300() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService( new BasicRedirectService(host, port, HttpStatus.SC_MULTIPLE_CHOICES)); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(false); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, httpget.getStatusCode()); assertEquals("/oldlocation/", httpget.getPath()); assertEquals(new URI("/oldlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } } public void testBasicRedirect301() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService( new BasicRedirectService(host, port, HttpStatus.SC_MOVED_PERMANENTLY)); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("/newlocation/", httpget.getPath()); assertEquals(host, httpget.getURI().getHost()); assertEquals(port, httpget.getURI().getPort()); assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } } public void testBasicRedirect302() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService( new BasicRedirectService(host, port, HttpStatus.SC_MOVED_TEMPORARILY)); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("/newlocation/", httpget.getPath()); assertEquals(host, httpget.getURI().getHost()); assertEquals(port, httpget.getURI().getPort()); assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } } public void testBasicRedirect303() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService( new BasicRedirectService(host, port, HttpStatus.SC_SEE_OTHER)); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("/newlocation/", httpget.getPath()); assertEquals(host, httpget.getURI().getHost()); assertEquals(port, httpget.getURI().getPort()); assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } } public void testBasicRedirect304() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService( new BasicRedirectService(host, port, HttpStatus.SC_NOT_MODIFIED)); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_NOT_MODIFIED, httpget.getStatusCode()); assertEquals("/oldlocation/", httpget.getPath()); assertEquals(new URI("/oldlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } } public void testBasicRedirect305() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService( new BasicRedirectService(host, port, HttpStatus.SC_USE_PROXY)); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_USE_PROXY, httpget.getStatusCode()); assertEquals("/oldlocation/", httpget.getPath()); assertEquals(new URI("/oldlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } } public void testBasicRedirect307() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService( new BasicRedirectService(host, port, HttpStatus.SC_TEMPORARY_REDIRECT)); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("/newlocation/", httpget.getPath()); assertEquals(host, httpget.getURI().getHost()); assertEquals(port, httpget.getURI().getPort()); assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } } public void testNoRedirect() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService(new BasicRedirectService(host, port)); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(false); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, httpget.getStatusCode()); assertEquals("/oldlocation/", httpget.getPath()); assertEquals(new URI("/oldlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } } public void testMaxRedirectCheck() throws IOException { this.server.setHttpService(new CircularRedirectService()); GetMethod httpget = new GetMethod("/circular-oldlocation/"); try { this.client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); this.client.getParams().setIntParameter(HttpClientParams.MAX_REDIRECTS, 5); this.client.executeMethod(httpget); fail("RedirectException exception should have been thrown"); } catch (RedirectException e) { // expected } finally { httpget.releaseConnection(); } } public void testCircularRedirect() throws IOException { this.server.setHttpService(new CircularRedirectService()); GetMethod httpget = new GetMethod("/circular-oldlocation/"); try { this.client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, false); this.client.executeMethod(httpget); fail("CircularRedirectException exception should have been thrown"); } catch (CircularRedirectException expected) { } finally { httpget.releaseConnection(); } } public void testPostRedirect() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService(new BasicRedirectService(host, port)); PostMethod httppost = new PostMethod("/oldlocation/"); httppost.setRequestEntity(new StringRequestEntity("stuff", null, null)); try { this.client.executeMethod(httppost); assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, httppost.getStatusCode()); assertEquals("/oldlocation/", httppost.getPath()); assertEquals(new URI("/oldlocation/", false), httppost.getURI()); } finally { httppost.releaseConnection(); } } public void testRelativeRedirect() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService(new RelativeRedirectService()); this.client.getParams().setBooleanParameter( HttpClientParams.REJECT_RELATIVE_REDIRECT, false); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals("/relativelocation/", httpget.getPath()); assertEquals(host, httpget.getURI().getHost()); assertEquals(port, httpget.getURI().getPort()); assertEquals(new URI("http://" + host + ":" + port + "/relativelocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } } public void testRejectRelativeRedirect() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService(new RelativeRedirectService()); this.client.getParams().setBooleanParameter( HttpClientParams.REJECT_RELATIVE_REDIRECT, true); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, httpget.getStatusCode()); assertEquals("/oldlocation/", httpget.getPath()); assertEquals(new URI("/oldlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } } public void testRejectBogusRedirectLocation() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService(new BogusRedirectService("xxx://bogus")); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); fail("BogusRedirectService should have been thrown"); } catch (IllegalStateException e) { //expected } finally { httpget.releaseConnection(); } } public void testRejectInvalidRedirectLocation() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService(new BogusRedirectService("http://"+ host +":"+ port +"/newlocation/?p=I have spaces")); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); fail("InvalidRedirectLocationException should have been thrown"); } catch (InvalidRedirectLocationException e) { //expected a protocol exception } finally { httpget.releaseConnection(); } } public void testCrossSiteRedirect() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); SimpleHttpServer thatserver = new SimpleHttpServer(); this.server.setHttpService(new BasicRedirectService(host, port)); thatserver.setHttpService(new BasicRedirectService(host, port)); thatserver.setTestname(getName()); HostConfiguration hostconfig = new HostConfiguration(); hostconfig.setHost( thatserver.getLocalAddress(), thatserver.getLocalPort(), Protocol.getProtocol("http")); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(hostconfig, httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("/newlocation/", httpget.getPath()); assertEquals(host, httpget.getURI().getHost()); assertEquals(port, httpget.getURI().getPort()); assertEquals(new URI("http://" + host + ":" + port + "/newlocation/", false), httpget.getURI()); } finally { httpget.releaseConnection(); } thatserver.destroy(); } public void testRedirectWithCookie() throws IOException { client.getState().addCookie(new Cookie("localhost", "name", "value", "/", -1, false)); String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); this.server.setHttpService(new BasicRedirectService(host, port)); GetMethod httpget = new GetMethod("/oldlocation/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("/newlocation/", httpget.getPath()); Header[] headers = httpget.getRequestHeaders(); int cookiecount = 0; for (int i = 0; i < headers.length; i++) { if ("cookie".equalsIgnoreCase(headers[i].getName())) { ++cookiecount; } } assertEquals("There can only be one (cookie)", 1, cookiecount); } finally { httpget.releaseConnection(); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestRequestHeaders.java100644 0 0 12012 10661532626 26414 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestRequestHeaders.java,v 1.8 2004/10/31 14:04:13 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.protocol.Protocol; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Tests for reading response headers. * * @author Jeff Dever * @version $Id: TestRequestHeaders.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestRequestHeaders extends TestCase { // ------------------------------------------------------------ Constructor public TestRequestHeaders(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = {TestRequestHeaders.class.getName()}; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestRequestHeaders.class); } public void testNullHeader() throws Exception { FakeHttpMethod method = new FakeHttpMethod(); assertEquals(null, method.getRequestHeader(null)); assertEquals(null, method.getRequestHeader("bogus")); } public void testHostHeaderPortHTTP80() throws Exception { HttpConnection conn = new HttpConnection("some.host.name", 80); HttpState state = new HttpState(); FakeHttpMethod method = new FakeHttpMethod(); method.addRequestHeaders(state, conn); assertEquals("Host: some.host.name", method.getRequestHeader("Host").toString().trim()); } public void testHostHeaderPortHTTP81() throws Exception { HttpConnection conn = new HttpConnection("some.host.name", 81); HttpState state = new HttpState(); FakeHttpMethod method = new FakeHttpMethod(); method.addRequestHeaders(state, conn); assertEquals("Host: some.host.name:81", method.getRequestHeader("Host").toString().trim()); } public void testHostHeaderPortHTTPS443() throws Exception { HttpConnection conn = new HttpConnection("some.host.name", 443, Protocol.getProtocol("https")); HttpState state = new HttpState(); FakeHttpMethod method = new FakeHttpMethod(); method.addRequestHeaders(state, conn); assertEquals("Host: some.host.name", method.getRequestHeader("Host").toString().trim()); } public void testHostHeaderPortHTTPS444() throws Exception { HttpConnection conn = new HttpConnection("some.host.name", 444, Protocol.getProtocol("https")); HttpState state = new HttpState(); FakeHttpMethod method = new FakeHttpMethod(); method.addRequestHeaders(state, conn); assertEquals("Host: some.host.name:444", method.getRequestHeader("Host").toString().trim()); } public void testHeadersPreserveCaseKeyIgnoresCase() throws Exception { FakeHttpMethod method = new FakeHttpMethod(); method.addRequestHeader(new Header("NAME", "VALUE")); Header upHeader = method.getRequestHeader("NAME"); Header loHeader = method.getRequestHeader("name"); Header mixHeader = method.getRequestHeader("nAmE"); assertEquals("NAME", upHeader.getName()); assertEquals("VALUE", upHeader.getValue()); assertEquals("NAME", loHeader.getName()); assertEquals("VALUE", loHeader.getValue()); assertEquals("NAME", mixHeader.getName()); assertEquals("VALUE", mixHeader.getValue()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestRequestLine.java100644 0 0 12022 10661532626 25731 0ustar 0 0 /* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.protocol.Protocol; import junit.framework.*; /** * Simple tests for {@link StatusLine}. * * @author oleg Kalnichevski * @version $Id: TestRequestLine.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestRequestLine extends TestCase { // ------------------------------------------------------------ Constructor public TestRequestLine(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestRequestLine.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestRequestLine.class); } // ----------------------------------------------------------- Test Methods public void testRequestLineGeneral() throws Exception { HttpConnection conn = new HttpConnection("localhost", 80); FakeHttpMethod method = new FakeHttpMethod(); assertEquals("Simple / HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1)); method = new FakeHttpMethod("stuff"); assertEquals("Simple stuff HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1)); conn = new HttpConnection("proxy", 8080, "localhost", 80, Protocol.getProtocol("http")); method = new FakeHttpMethod(); assertEquals("Simple http://localhost/ HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1)); method = new FakeHttpMethod("stuff"); assertEquals("Simple http://localhost/stuff HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1)); conn = new HttpConnection("proxy", 8080, "localhost", -1, Protocol.getProtocol("http")); method = new FakeHttpMethod(); assertEquals("Simple http://localhost/ HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1)); method = new FakeHttpMethod("stuff"); assertEquals("Simple http://localhost/stuff HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1)); conn = new HttpConnection("proxy", 8080, "localhost", 666, Protocol.getProtocol("http")); method = new FakeHttpMethod(); assertEquals("Simple http://localhost:666/ HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1)); method = new FakeHttpMethod("stuff"); assertEquals("Simple http://localhost:666/stuff HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1)); } public void testRequestLineQuery() throws Exception { HttpConnection conn = new HttpConnection("localhost", 80); FakeHttpMethod method = new FakeHttpMethod(); method.setQueryString( new NameValuePair[] { new NameValuePair("param1", " !#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~"), new NameValuePair("param2", "some stuff") } ); assertEquals("Simple /?param1=+%21%23%24%25%26%27%28%29*%2B%2C-.%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E_%60%7B%7C%7D%7E¶m2=some+stuff HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1)); } public void testRequestLinePath() throws Exception { HttpConnection conn = new HttpConnection("localhost", 80); FakeHttpMethod method = new FakeHttpMethod(); method.setPath("/some%20stuff/"); assertEquals("Simple /some%20stuff/ HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1)); method = new FakeHttpMethod("/some%20stuff/"); assertEquals("Simple /some%20stuff/ HTTP/1.1\r\n", method.generateRequestLine(conn, HttpVersion.HTTP_1_1)); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestResponseHeaders.java100644 0 0 42517 10661532630 26572 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestResponseHeaders.java,v 1.18 2004/11/07 12:31:42 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.IOException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.server.HttpRequestHandler; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.ResponseWriter; import org.apache.commons.httpclient.server.SimpleHttpServerConnection; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * Tests for reading response headers. * * @author Davanum Srinivas * @author Jeff Dever * @author Adrian Sutton * @version $Id: TestResponseHeaders.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestResponseHeaders extends HttpClientTestBase { private AccessibleHttpConnectionManager connectionManager; // ------------------------------------------------------------ Constructor public TestResponseHeaders(final String testName) throws IOException { super(testName); } public void setUp() throws IOException { super.setUp(); this.connectionManager = new AccessibleHttpConnectionManager(); this.client.setHttpConnectionManager(connectionManager); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = {TestResponseHeaders.class.getName()}; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestResponseHeaders.class); } // ----------------------------------------------------------- Test Methods public void testHeaders() throws Exception { final String body = "XXX\r\nYYY\r\nZZZ"; this.server.setHttpService(new HttpService() { public boolean process(SimpleRequest request, SimpleResponse response) throws IOException { response.setStatusLine(request.getRequestLine().getHttpVersion(), 200); response.addHeader(new Header("Connection", "close")); response.addHeader(new Header("Content-Length", Integer.toString(body.length()))); response.addHeader(new Header("Content-Type", "text/xml; charset=utf-8")); response.addHeader(new Header("Date", "Wed, 28 Mar 2001 05:05:04 GMT")); response.addHeader(new Header("Server", "UserLand Frontier/7.0-WinNT")); response.setBodyString(body); return true; } }); HttpMethod method = new GetMethod(); client.executeMethod(method); assertEquals("close", method.getResponseHeader("Connection").getValue()); assertEquals(body.length(), Integer.parseInt(method.getResponseHeader("Content-Length").getValue())); assertEquals("text/xml; charset=utf-8", method.getResponseHeader("Content-Type").getValue()); assertEquals("Wed, 28 Mar 2001 05:05:04 GMT", method.getResponseHeader("Date").getValue()); assertEquals("UserLand Frontier/7.0-WinNT", method.getResponseHeader("Server").getValue()); } /** * Tests that having a duplicate content length causes no problems. */ public void testDuplicateContentLength() throws Exception { final String body = "XXX\r\nYYY\r\nZZZ"; this.server.setHttpService(new HttpService() { public boolean process(SimpleRequest request, SimpleResponse response) throws IOException { response.setStatusLine(request.getRequestLine().getHttpVersion(), 200); response.addHeader(new Header("Content-Length", Integer.toString(body.length()))); response.addHeader(new Header("Content-Length", Integer.toString(body.length()))); response.setBodyString(body); return true; } }); HttpMethod method = new GetMethod(); client.executeMethod(method); assertNotNull( "Response body is null.", method.getResponseBodyAsStream() ); } public void testDuplicateConnection() throws Exception { this.server.setHttpService(new HttpService() { public boolean process(SimpleRequest request, SimpleResponse response) throws IOException { response.setStatusLine(request.getRequestLine().getHttpVersion(), 200); response.addHeader(new Header("Connection", "close")); response.addHeader(new Header("Connection", "close")); return true; } }); GetMethod method = new GetMethod("/"); client.executeMethod(method); method.getResponseBodyAsString(); assertFalse(connectionManager.getConection().isOpen()); this.server.setHttpService(new HttpService() { public boolean process(SimpleRequest request, SimpleResponse response) throws IOException { response.setStatusLine(HttpVersion.HTTP_1_0, 200); response.addHeader(new Header("Connection", "keep-alive")); response.addHeader(new Header("Connection", "keep-alive")); response.setBodyString("aa"); return true; } }); method = new GetMethod("/"); client.executeMethod(method); method.getResponseBodyAsString(); assertTrue(connectionManager.getConection().isOpen()); } public void testNoContentLength() throws Exception { // test with connection header this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println("Connection: keep-alive"); out.println(); out.println("12345"); out.flush(); return true; } }); GetMethod method = new GetMethod("/"); client.executeMethod(method); method.getResponseBodyAsString(); assertFalse(connectionManager.getConection().isOpen()); // test without connection header this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println(); out.println("12345"); out.flush(); return true; } }); // test with connection header method = new GetMethod("/"); client.executeMethod(method); method.getResponseBodyAsString(); assertFalse(connectionManager.getConection().isOpen()); } public void testInvalidContentLength1() throws Exception { this.server.setHttpService(new HttpService() { public boolean process(SimpleRequest request, SimpleResponse response) throws IOException { response.setStatusLine(request.getRequestLine().getHttpVersion(), 200); response.addHeader(new Header("Content-Length", "5")); response.addHeader(new Header("Content-Length", "stuff")); response.setBodyString("12345"); return true; } }); GetMethod method = new GetMethod("/"); client.executeMethod(method); assertEquals(5, method.getResponseContentLength()); } public void testInvalidContentLength2() throws Exception { this.server.setHttpService(new HttpService() { public boolean process(SimpleRequest request, SimpleResponse response) throws IOException { response.setStatusLine(request.getRequestLine().getHttpVersion(), 200); response.addHeader(new Header("Content-Length", "stuff")); response.addHeader(new Header("Content-Length", "5")); response.setBodyString("12345"); return true; } }); GetMethod method = new GetMethod("/"); client.executeMethod(method); assertEquals(5, method.getResponseContentLength()); } public void testProxyNoContentLength() throws Exception { // test with proxy-connection header this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println("proxy-connection: keep-alive"); out.println(); out.println("12345"); out.flush(); return true; } }); client.getHostConfiguration().setProxy(server.getLocalAddress(), server.getLocalPort()); GetMethod method = new GetMethod("/"); client.executeMethod(method); method.getResponseBodyAsString(); assertFalse(connectionManager.getConection().isOpen()); // test without proxy-connection header this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println(); out.println("12345"); out.flush(); return true; } }); method = new GetMethod("/"); client.executeMethod(method); method.getResponseBodyAsString(); assertFalse(connectionManager.getConection().isOpen()); } public void testNullHeaders() throws Exception { this.server.setHttpService(new HttpService() { public boolean process(SimpleRequest request, SimpleResponse response) throws IOException { response.setStatusLine(request.getRequestLine().getHttpVersion(), 200); response.addHeader(new Header("Connection", "close")); response.setBodyString("XXX\r\nYYY\r\nZZZ"); return true; } }); HttpMethod method = new GetMethod("/"); client.executeMethod(method); assertEquals(null, method.getResponseHeader(null)); assertEquals(null, method.getResponseHeader("bogus")); } public void testFoldedHeaders() throws Exception { final String body = "XXX\r\nYYY\r\nZZZ"; this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println("Connection: close"); out.println("Content-Length: " + body.length()); out.println("Content-Type: text/xml; charset=utf-8"); out.println("\tboundary=XXXX"); out.println("Date: Wed, 28 Mar 2001"); out.println(" 05:05:04 GMT"); out.println("Server: UserLand Frontier/7.0-WinNT"); out.println(); out.println(body); out.flush(); return true; } }); HttpMethod method = new GetMethod("/"); client.executeMethod(method); assertEquals("close", method.getResponseHeader("Connection").getValue()); assertEquals(body.length(), Integer.parseInt(method.getResponseHeader("Content-Length").getValue())); assertEquals("text/xml; charset=utf-8 boundary=XXXX", method.getResponseHeader("Content-Type").getValue()); assertEquals("Wed, 28 Mar 2001 05:05:04 GMT", method.getResponseHeader("Date").getValue()); assertEquals("UserLand Frontier/7.0-WinNT", method.getResponseHeader("Server").getValue()); assertTrue(method.getResponseHeader("Content-Type").toString().indexOf("boundary") != -1); } public void testForceCloseConnection() throws Exception { this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println("Content-Type: garbage"); out.println(); out.println("stuff"); out.flush(); return true; } }); FakeHttpMethod method = new FakeHttpMethod(); client.executeMethod(method); assertTrue("Connection should be closed", method.shouldCloseConnection(connectionManager.getConection())); assertTrue("Connection should be force-closed", method.isConnectionCloseForced()); } public void testForceCloseConnection2() throws Exception { this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println("Content-Type: garbage"); out.println("Connection: close"); out.println(); out.println("stuff"); out.flush(); return true; } }); FakeHttpMethod method = new FakeHttpMethod(); client.executeMethod(method); assertTrue("Connection should be closed", method.shouldCloseConnection(connectionManager.getConection())); assertFalse("Connection should NOT be closed", method.isConnectionCloseForced()); } public void testNoContent() throws Exception { // test with connection header this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 204 NO CONTENT"); out.println(); out.flush(); return true; } }); GetMethod method = new GetMethod("/"); client.executeMethod(method); method.getResponseBodyAsString(); assertTrue(connectionManager.getConection().isOpen()); // test without connection header this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 204 NO CONTENT"); out.println("Connection: keep-alive"); out.println(); out.flush(); return true; } }); // test with connection header method = new GetMethod("/"); client.executeMethod(method); method.getResponseBodyAsString(); assertTrue(connectionManager.getConection().isOpen()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestStatusLine.java100644 0 0 13447 10661532627 25601 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestStatusLine.java,v 1.9 2004/07/19 20:24:21 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import junit.framework.*; /** * Simple tests for {@link StatusLine}. * * @author Jeff Dever * @version $Id: TestStatusLine.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestStatusLine extends TestCase { private StatusLine statusLine = null; // ------------------------------------------------------------ Constructor public TestStatusLine(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestStatusLine.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestStatusLine.class); } // ------------------------------------------------------ Protected Methods // ----------------------------------------------------------- Test Methods public void testIfStatusLine() throws Exception { assertTrue(StatusLine.startsWithHTTP("HTTP")); assertTrue(StatusLine.startsWithHTTP(" HTTP")); assertTrue(StatusLine.startsWithHTTP("\rHTTP")); assertTrue(StatusLine.startsWithHTTP("\tHTTP")); assertFalse(StatusLine.startsWithHTTP("crap")); assertFalse(StatusLine.startsWithHTTP("HTT")); assertFalse(StatusLine.startsWithHTTP("http")); } public void testSuccess() throws Exception { //typical status line statusLine = new StatusLine("HTTP/1.1 200 OK"); assertEquals("HTTP/1.1 200 OK", statusLine.toString()); assertEquals("HTTP/1.1", statusLine.getHttpVersion()); assertEquals(200, statusLine.getStatusCode()); assertEquals("OK", statusLine.getReasonPhrase()); //status line with multi word reason phrase statusLine = new StatusLine("HTTP/1.1 404 Not Found"); assertEquals(404, statusLine.getStatusCode()); assertEquals("Not Found", statusLine.getReasonPhrase()); //reason phrase can be anyting statusLine = new StatusLine("HTTP/1.1 404 Non Trouve"); assertEquals("Non Trouve", statusLine.getReasonPhrase()); //its ok to end with a \n\r statusLine = new StatusLine("HTTP/1.1 404 Not Found\r\n"); assertEquals("Not Found", statusLine.getReasonPhrase()); //this is valid according to the Status-Line BNF statusLine = new StatusLine("HTTP/1.1 200 "); assertEquals(200, statusLine.getStatusCode()); assertEquals("", statusLine.getReasonPhrase()); //this is not strictly valid, but is lienent statusLine = new StatusLine("HTTP/1.1 200"); assertEquals(200, statusLine.getStatusCode()); assertEquals("", statusLine.getReasonPhrase()); //this is not strictly valid, but is lienent statusLine = new StatusLine("HTTP/1.1 200 OK"); assertEquals(200, statusLine.getStatusCode()); assertEquals("OK", statusLine.getReasonPhrase()); //this is not strictly valid, but is lienent statusLine = new StatusLine("\rHTTP/1.1 200 OK"); assertEquals(200, statusLine.getStatusCode()); assertEquals("OK", statusLine.getReasonPhrase()); assertEquals("HTTP/1.1", statusLine.getHttpVersion()); //this is not strictly valid, but is lienent statusLine = new StatusLine(" HTTP/1.1 200 OK"); assertEquals(200, statusLine.getStatusCode()); assertEquals("OK", statusLine.getReasonPhrase()); assertEquals("HTTP/1.1", statusLine.getHttpVersion()); } public void testFailure() throws Exception { try { statusLine = new StatusLine(null); fail(); } catch (NullPointerException e) { /* expected */ } try { statusLine = new StatusLine("xxx 200 OK"); fail(); } catch (HttpException e) { /* expected */ } try { statusLine = new StatusLine("HTTP/1.1 xxx OK"); fail(); } catch (HttpException e) { /* expected */ } try { statusLine = new StatusLine("HTTP/1.1 "); fail(); } catch (HttpException e) { /* expected */ } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestStreams.java100644 0 0 30355 10661532626 25120 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestStreams.java,v 1.19 2004/10/31 14:04:13 olegk Exp $ * $Revision: 505890 $ * $Date: 2007-02-11 12:25:25 +0100 (Sun, 11 Feb 2007) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.util.EncodingUtil; public class TestStreams extends TestCase { private static final String CONTENT_CHARSET = "ISO-8859-1"; public TestStreams(String testName) { super(testName); } public void testChunkedInputStream() throws IOException { String correctInput = "10;key=\"value\r\nnewline\"\r\n1234567890123456\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\r\n"; String correctResult = "123456789012345612345"; HttpMethod method = new FakeHttpMethod(); //Test for when buffer is larger than chunk size InputStream in = new ChunkedInputStream(new ByteArrayInputStream( EncodingUtil.getBytes(correctInput, CONTENT_CHARSET)), method); byte[] buffer = new byte[300]; ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } String result = EncodingUtil.getString(out.toByteArray(), CONTENT_CHARSET); assertEquals(result, correctResult); Header footer = method.getResponseFooter("footer1"); assertEquals(footer.getValue(), "abcde"); footer = method.getResponseFooter("footer2"); assertEquals(footer.getValue(), "fghij"); method = new FakeHttpMethod(); //Test for when buffer is smaller than chunk size. in = new ChunkedInputStream(new ByteArrayInputStream( EncodingUtil.getBytes(correctInput, CONTENT_CHARSET)), method); buffer = new byte[7]; out = new ByteArrayOutputStream(); while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } result = EncodingUtil.getString(out.toByteArray(), CONTENT_CHARSET); assertEquals(result, correctResult); footer = method.getResponseFooter("footer1"); assertEquals(footer.getValue(), "abcde"); footer = method.getResponseFooter("footer2"); assertEquals(footer.getValue(), "fghij"); } public void testCorruptChunkedInputStream1() throws IOException { //missing \r\n at the end of the first chunk String corrupInput = "10;key=\"value\"\r\n123456789012345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\r\n"; HttpMethod method = new FakeHttpMethod(); InputStream in = new ChunkedInputStream(new ByteArrayInputStream( EncodingUtil.getBytes(corrupInput, CONTENT_CHARSET)), method); byte[] buffer = new byte[300]; ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; try { while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } fail("Should have thrown exception"); } catch(IOException e) { /* expected exception */ } } public void testEmptyChunkedInputStream() throws IOException { String input = "0\r\n"; HttpMethod method = new FakeHttpMethod(); InputStream in = new ChunkedInputStream(new ByteArrayInputStream( EncodingUtil.getBytes(input, CONTENT_CHARSET)), method); byte[] buffer = new byte[300]; ByteArrayOutputStream out = new ByteArrayOutputStream(); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } assertEquals(0, out.size()); } public void testContentLengthInputStream() throws IOException { String correct = "1234567890123456"; InputStream in = new ContentLengthInputStream(new ByteArrayInputStream( EncodingUtil.getBytes(correct, CONTENT_CHARSET)), 10L); byte[] buffer = new byte[50]; int len = in.read(buffer); ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(buffer, 0, len); String result = EncodingUtil.getString(out.toByteArray(), CONTENT_CHARSET); assertEquals(result, "1234567890"); } public void testContentLengthInputStreamSkip() throws IOException { InputStream in = new ContentLengthInputStream(new ByteArrayInputStream(new byte[20]), 10L); assertEquals(10, in.skip(10)); assertTrue(in.read() == -1); in = new ContentLengthInputStream(new ByteArrayInputStream(new byte[20]), 10L); in.read(); assertEquals(9, in.skip(10)); assertTrue(in.read() == -1); in = new ContentLengthInputStream(new ByteArrayInputStream(new byte[20]), 2L); in.read(); in.read(); assertTrue(in.skip(10) <= 0); assertTrue(in.read() == -1); } public void testChunkedConsitance() throws IOException { String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb"; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); OutputStream out = new ChunkedOutputStream(buffer); out.write(EncodingUtil.getBytes(input, CONTENT_CHARSET)); out.close(); buffer.close(); InputStream in = new ChunkedInputStream(new ByteArrayInputStream(buffer.toByteArray()), new GetMethod()); byte[] d = new byte[10]; ByteArrayOutputStream result = new ByteArrayOutputStream(); int len = 0; while ((len = in.read(d)) > 0) { result.write(d, 0, len); } String output = EncodingUtil.getString(result.toByteArray(), CONTENT_CHARSET); assertEquals(input, output); } public void testChunkedOutputStream() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ChunkedOutputStream out = new ChunkedOutputStream(buffer, 2); out.write('1'); out.write('2'); out.write('3'); out.write('4'); out.finish(); out.close(); byte [] rawdata = buffer.toByteArray(); assertEquals(19, rawdata.length); assertEquals('2', rawdata[0]); assertEquals('\r', rawdata[1]); assertEquals('\n', rawdata[2]); assertEquals('1', rawdata[3]); assertEquals('2', rawdata[4]); assertEquals('\r', rawdata[5]); assertEquals('\n', rawdata[6]); assertEquals('2', rawdata[7]); assertEquals('\r', rawdata[8]); assertEquals('\n', rawdata[9]); assertEquals('3', rawdata[10]); assertEquals('4', rawdata[11]); assertEquals('\r', rawdata[12]); assertEquals('\n', rawdata[13]); assertEquals('0', rawdata[14]); assertEquals('\r', rawdata[15]); assertEquals('\n', rawdata[16]); assertEquals('\r', rawdata[17]); assertEquals('\n', rawdata[18]); } public void testChunkedOutputStreamLargeChunk() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ChunkedOutputStream out = new ChunkedOutputStream(buffer, 2); out.write(new byte[] {'1', '2', '3', '4'}); out.finish(); out.close(); byte [] rawdata = buffer.toByteArray(); assertEquals(14, rawdata.length); assertEquals('4', rawdata[0]); assertEquals('\r', rawdata[1]); assertEquals('\n', rawdata[2]); assertEquals('1', rawdata[3]); assertEquals('2', rawdata[4]); assertEquals('3', rawdata[5]); assertEquals('4', rawdata[6]); assertEquals('\r', rawdata[7]); assertEquals('\n', rawdata[8]); assertEquals('0', rawdata[9]); assertEquals('\r', rawdata[10]); assertEquals('\n', rawdata[11]); assertEquals('\r', rawdata[12]); assertEquals('\n', rawdata[13]); } public void testChunkedOutputStreamSmallChunk() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ChunkedOutputStream out = new ChunkedOutputStream(buffer, 2); out.write('1'); out.finish(); out.close(); byte [] rawdata = buffer.toByteArray(); assertEquals(11, rawdata.length); assertEquals('1', rawdata[0]); assertEquals('\r', rawdata[1]); assertEquals('\n', rawdata[2]); assertEquals('1', rawdata[3]); assertEquals('\r', rawdata[4]); assertEquals('\n', rawdata[5]); assertEquals('0', rawdata[6]); assertEquals('\r', rawdata[7]); assertEquals('\n', rawdata[8]); assertEquals('\r', rawdata[9]); assertEquals('\n', rawdata[10]); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestStreams.class); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestStreams.class.getName() }; junit.textui.TestRunner.main(testCaseName); } public void testAutoCloseInputStream() throws IOException { // The purpose of this test is to check EOF handling of ACIS with // respect to exceptions being thrown. Putting it on top of a // plain ByteArrayInputStream won't do, since BAIS can't be closed. ByteArrayInputStream bais = new ByteArrayInputStream("whatever".getBytes()); InputStream fbais = new java.io.FilterInputStream(bais) { private boolean closed = false; public void close() throws IOException { closed = true; super.close(); } public int available() throws IOException { if (closed) throw new IOException("closed"); return super.available(); } }; AutoCloseInputStream acis = new AutoCloseInputStream(fbais, null); byte[] data = new byte[16]; int count = 0; while (count >= 0) { count = acis.read(data); } // We're at EOF. The underlying stream should be closed, // but the ACIS itself not. try { fbais.available(); fail("underlying stream not auto-closed"); } catch (IOException x) { // expected, pis should be closed } // don't want to see an exception being thrown here acis.available(); acis.close(); try { acis.available(); fail("auto-close stream not closed"); } catch (IOException x) { // expected, acis should be closed } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestURI.java100644 0 0 34272 10661532626 24143 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/TestURI.java $ * $Revision: 564973 $ * $Date: 2007-08-11 22:51:47 +0200 (Sat, 11 Aug 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.methods.GetMethod; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Simple tests for the URI class. * * @author Michael Becke */ public class TestURI extends TestCase { /** * Constructor for TestURI. * @param testName */ public TestURI(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestURI.class); } public void testIPv4Address() throws URIException { URI base = new URI("http://10.0.1.10:8830", false); URI uri = base; assertTrue("Should be an IPv4 address", uri.isIPv4address()); uri = new URI(base, "/04-1.html", false); assertTrue("Should be an IPv4 address", uri.isIPv4address()); uri = new URI("/04-1.html", false); assertFalse("Should NOT be an IPv4 address", uri.isIPv4address()); uri = new URI(base, "http://10.0.1.10:8830/04-1.html", false); assertTrue("Should be an IPv4 address", uri.isIPv4address()); uri = new URI("http://10.0.1.10:8830/04-1.html", false); assertTrue("Should be an IPv4 address", uri.isIPv4address()); uri = new URI(base, "http://host.org/04-1.html", false); assertFalse("Should NOT be an IPv4 address", uri.isIPv4address()); uri = new URI("http://host.org/04-1.html", false); assertFalse("Should NOT be an IPv4 address", uri.isIPv4address()); } public void testUrl() throws URIException { URI url = new HttpURL("http://jakarta.apache.org"); assertEquals(80, url.getPort()); assertEquals("http", url.getScheme()); url = new HttpsURL("https://jakarta.apache.org"); assertEquals(443, url.getPort()); assertEquals("https", url.getScheme()); } /** * Tests the URI(URI, String) constructor. This tests URIs ability to * resolve relative URIs. */ public void testRelativeURIConstructor() { URI baseURI = null; try { baseURI = new URI("http://a/b/c/d;p?q", false); } catch ( URIException e ) { fail( "unable to create base URI: " + e ); } // the following is an array of arrays in the following order // relative URI, scheme, host(authority), path, query, fragment, abs. URI // // these examples were taken from rfc 2396 String[][] testRelativeURIs = { { "g:h", "g", null, "h", null, null, "g:h" }, { "g", "http", "a", "/b/c/g", null, null, "http://a/b/c/g" }, { "./g", "http", "a", "/b/c/g", null, null, "http://a/b/c/g" }, { "g/", "http", "a", "/b/c/g/", null, null, "http://a/b/c/g/" }, { "/g", "http", "a", "/g", null, null, "http://a/g" }, { "//g", "http", "g", null, null, null, "http://g" }, { "?y", "http", "a", "/b/c/d;p", "y", null, "http://a/b/c/d;p?y" }, { "g?y", "http", "a", "/b/c/g", "y", null, "http://a/b/c/g?y" }, { "#s", "http", "a", "/b/c/d;p", "q", "s", "http://a/b/c/d;p?q#s" }, { "#", "http", "a", "/b/c/d;p", "q", "", "http://a/b/c/d;p?q#" }, { "", "http", "a", "/b/c/d;p", "q", null, "http://a/b/c/d;p?q" }, { "g#s", "http", "a", "/b/c/g", null, "s", "http://a/b/c/g#s" }, { "g?y#s","http", "a", "/b/c/g", "y", "s", "http://a/b/c/g?y#s" }, { ";x", "http", "a", "/b/c/;x", null, null, "http://a/b/c/;x" }, { "g;x", "http", "a", "/b/c/g;x", null, null, "http://a/b/c/g;x" }, { "g;x?y#s", "http", "a", "/b/c/g;x", "y", "s", "http://a/b/c/g;x?y#s" }, { ".", "http", "a", "/b/c/", null, null, "http://a/b/c/" }, { "./", "http", "a", "/b/c/", null, null, "http://a/b/c/" }, { "..", "http", "a", "/b/", null, null, "http://a/b/" }, { "../", "http", "a", "/b/", null, null, "http://a/b/" }, { "../g", "http", "a", "/b/g", null, null, "http://a/b/g" }, { "../..", "http", "a", "/", null, null, "http://a/" }, { "../../", "http", "a", "/", null, null, "http://a/" }, { "../../g", "http", "a", "/g", null, null, "http://a/g" }, { "../../../g", "http", "a", "/g", null, null, "http://a/g" }, { "../../../../g", "http", "a", "/g", null, null, "http://a/g" }, { "/./g", "http", "a", "/g", null, null, "http://a/g" }, { "/../g", "http", "a", "/g", null, null, "http://a/g" }, { "g.", "http", "a", "/b/c/g.", null, null, "http://a/b/c/g." }, { ".g", "http", "a", "/b/c/.g", null, null, "http://a/b/c/.g" }, { "g..", "http", "a", "/b/c/g..", null, null, "http://a/b/c/g.." }, { "..g", "http", "a", "/b/c/..g", null, null, "http://a/b/c/..g" }, { "./../g", "http", "a", "/b/g", null, null, "http://a/b/g" }, { "./g/.", "http", "a", "/b/c/g/", null, null, "http://a/b/c/g/" }, { "g/./h", "http", "a", "/b/c/g/h", null, null, "http://a/b/c/g/h" }, { "g/../h", "http", "a", "/b/c/h", null, null, "http://a/b/c/h" }, { "g;x=1/./y", "http", "a", "/b/c/g;x=1/y", null, null, "http://a/b/c/g;x=1/y" }, { "g;x=1/../y", "http", "a", "/b/c/y", null, null, "http://a/b/c/y" }, { "g?y/./x", "http", "a", "/b/c/g", "y/./x", null, "http://a/b/c/g?y/./x" }, { "g?y/../x", "http", "a", "/b/c/g", "y/../x", null, "http://a/b/c/g?y/../x" }, { "g#s/./x", "http", "a", "/b/c/g", null, "s/./x", "http://a/b/c/g#s/./x" }, { "g#s/../x", "http", "a", "/b/c/g", null, "s/../x", "http://a/b/c/g#s/../x" }, { ":g", "http", "a", "/b/c/:g", null, null, "http://a/b/c/:g" }, // see issue #35148 { "//a/b/c", "http", "a", "/b/c", null, null, "http://a/b/c" } // see HTTPCLIENT-580 }; for (int i = 0; i < testRelativeURIs.length; i++) { URI testURI = null; try { testURI = new URI( baseURI, testRelativeURIs[i][0], false ); } catch ( URIException e ) { e.printStackTrace(); fail( "unable to create URI with relative value(" + testRelativeURIs[i][0] + "): " + e ); } try { assertEquals("array index "+i, testRelativeURIs[i][1], testURI.getScheme()); assertEquals("array index "+i, testRelativeURIs[i][2], testURI.getAuthority()); assertEquals("array index "+i, testRelativeURIs[i][3], testURI.getPath()); assertEquals("array index "+i, testRelativeURIs[i][4], testURI.getQuery()); assertEquals("array index "+i, testRelativeURIs[i][5], testURI.getFragment()); assertEquals("array index "+i, testRelativeURIs[i][6], testURI.getURIReference()); } catch ( URIException e ) { fail( "error getting URI property: " + e ); } } } public void testTestURIAuthorityString() throws Exception { URI url = new URI("ftp", "user:password", "localhost", -1, "/"); assertEquals("ftp://user:password@localhost/", url.toString()); assertEquals("user:password@localhost", url.getAuthority()); } public void testTestHttpUrlAuthorityString() throws Exception { HttpURL url = new HttpURL("localhost", -1, "/"); assertEquals("http://localhost/", url.toString()); url.setRawUserinfo("user".toCharArray(), "password".toCharArray()); assertEquals("http://localhost/", url.toString()); assertEquals("user:password@localhost", url.getAuthority()); url = new HttpURL("user#@", "pass#@", "localhost", 8080, "/"); assertEquals("http://localhost:8080/", url.toString()); assertEquals("user#@:pass#@", url.getUserinfo()); assertEquals("user%23%40:pass%23%40", url.getEscapedUserinfo()); url = new HttpURL("user%23%40:pass%23%40", "localhost", 8080, "/"); assertEquals("http://localhost:8080/", url.toString()); assertEquals("user#@:pass#@", url.getUserinfo()); assertEquals("user%23%40:pass%23%40", url.getEscapedUserinfo()); url = new HttpURL("localhost", 8080, "/"); assertEquals("http://localhost:8080/", url.toString()); url.setRawUserinfo("user".toCharArray(), "password".toCharArray()); assertEquals("http://localhost:8080/", url.toString()); assertEquals("user:password@localhost:8080", url.getAuthority()); } public void testTestHttpsUrlAuthorityString() throws Exception { HttpsURL url = new HttpsURL("localhost", -1, "/"); assertEquals("https://localhost/", url.toString()); url.setRawUserinfo("user".toCharArray(), "password".toCharArray()); assertEquals("https://localhost/", url.toString()); assertEquals("user:password@localhost", url.getAuthority()); url = new HttpsURL("user#@", "pass#@", "localhost", 8080, "/"); assertEquals("https://localhost:8080/", url.toString()); assertEquals("user#@:pass#@", url.getUserinfo()); assertEquals("user%23%40:pass%23%40", url.getEscapedUserinfo()); url = new HttpsURL("user%23%40:pass%23%40", "localhost", 8080, "/"); assertEquals("https://localhost:8080/", url.toString()); assertEquals("user#@:pass#@", url.getUserinfo()); assertEquals("user%23%40:pass%23%40", url.getEscapedUserinfo()); url = new HttpsURL("localhost", 8080, "/"); assertEquals("https://localhost:8080/", url.toString()); url.setRawUserinfo("user".toCharArray(), "password".toCharArray()); assertEquals("https://localhost:8080/", url.toString()); assertEquals("user:password@localhost:8080", url.getAuthority()); } public void testURIEscaping() throws Exception { String escaped = "http://some.host.com/%41.html"; String unescaped = "http://some.host.com/A.html"; URI u1 = new URI(escaped, true); GetMethod method = new GetMethod(); method.setURI(u1); URI u2 = method.getURI(); assertEquals(escaped, u1.toString()); assertEquals(escaped, new String(u1.getRawURI())); assertEquals(unescaped, u1.getURI()); assertEquals(escaped, u2.toString()); assertEquals(escaped, new String(u2.getRawURI())); assertEquals(unescaped, u2.getURI()); } public void testBug578() throws Exception { HttpURL url = new HttpURL("http://localhost/test+test"); assertEquals("/test+test", url.getPath()); } public void testVariousCharacters() throws Exception { verifyInvalidURI("http://authority:123/path/path?query&name=val ue"); verifyInvalidURI("http://authority:123/path/path?query&na me=value"); verifyInvalidURI("http://authority:123/path/path?qu ery&name=value"); verifyInvalidURI("http://authority:123/path/pa th?query&name=value"); verifyInvalidURI("http://authority:123/pa th/path?query&name=value"); verifyInvalidURI("http://authority:12 3/path/path?query&name=value"); verifyInvalidURI("http://autho rity:123/path/path?query&name=value"); verifyInvalidURI("htt p://authority:123/path/path?query&name=value"); } private void verifyInvalidURI(String uri) { try { new URI(uri, true); fail("should have thrown URIException"); } catch(URIException e) { /* expected */ } } /** * Verify proper handling of relative URIs which have a scheme. * See bug http://issues.apache.org/jira/browse/HTTPCLIENT-587 * * @throws Exception */ public void testRelativeWithScheme() throws Exception { URI base = new URI("http://www.example.com/some/path", true); URI rel1 = new URI("http:", true); URI rel2 = new URI("http:foo", true); URI rel3 = new URI("http:../../bar", true); URI derel1 = new URI(base, rel1); assertEquals("http://www.example.com/some/path",derel1.toString()); URI derel2 = new URI(base, rel2); assertEquals("http://www.example.com/some/foo",derel2.toString()); URI derel3 = new URI(base,rel3); assertEquals("http://www.example.com/bar",derel3.toString()); } /** * Verify proper handling of relative URIs with embedded double-slashes, * like "foo//bar//baz". * See bug http://issues.apache.org/jira/browse/HTTPCLIENT-588 * * @throws Exception */ public void testRelativeWithDoubleSlash() throws Exception { URI rel = new URI("foo//bar//baz",true); assertEquals("foo//bar//baz",rel.toString()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestURIUtil.java100644 0 0 14004 10661532626 24770 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestURIUtil.java,v 1.6 2004/02/22 18:08:50 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.httpclient.util.URIUtil; /** * * Unit tests for {@link URIUtil}. These tests care currently quite limited * and should be expanded to test more functionality. * * @author Marc A. Saegesser * @version $Id: TestURIUtil.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestURIUtil extends TestCase { // ----------------------------------------------------- Instance Variables URITestCase pathTests[] = {new URITestCase("http://www.server.com/path1/path2", "/path1/path2"), new URITestCase("http://www.server.com/path1/path2/", "/path1/path2/"), new URITestCase("http://www.server.com/path1/path2?query=string", "/path1/path2"), new URITestCase("http://www.server.com/path1/path2/?query=string", "/path1/path2/"), new URITestCase("www.noscheme.com/path1/path2", "/path1/path2"), new URITestCase("www.noscheme.com/path1/path2#anchor?query=string", "/path1/path2"), new URITestCase("/noscheme/nohost/path", "/noscheme/nohost/path"), new URITestCase("http://www.server.com", "/"), new URITestCase("https://www.server.com:443/ssl/path", "/ssl/path"), new URITestCase("http://www.server.com:8080/path/with/port", "/path/with/port"), new URITestCase("http://www.server.com/path1/path2?query1=string?1&query2=string2", "/path1/path2")}; URITestCase queryTests[] = {new URITestCase("http://www.server.com/path1/path2", null), new URITestCase("http://www.server.com/path1/path2?query=string", "query=string"), new URITestCase("http://www.server.com/path1/path2/?query=string", "query=string"), new URITestCase("www.noscheme.com/path1/path2#anchor?query=string", "query=string"), new URITestCase("/noscheme/nohost/path?query1=string1&query2=string2", "query1=string1&query2=string2"), new URITestCase("https://www.server.com:443/ssl/path?query1=string1&query2=string2", "query1=string1&query2=string2"), new URITestCase("http://www.server.com:8080/path/with/port?query1=string1&query2=string2", "query1=string1&query2=string2"), new URITestCase("http://www.server.com/path1/path2?query1=string?1&query2=string2", "query1=string?1&query2=string2")}; // ------------------------------------------------------------ Constructor public TestURIUtil(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestURIUtil.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestURIUtil.class); } // ----------------------------------------------------------- Test Methods public void testGetPath() { String testValue = ""; String expectedResult = ""; for(int i=0;i. * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import org.apache.commons.httpclient.util.URIUtil; import junit.framework.*; /** * Tests the util.URIUtil class. * * @author Ortwin Glck * * @since 2.0 */ public class TestURIUtil2 extends TestCase { public TestURIUtil2(String s) { super(s); } public static Test suite() { return new TestSuite(TestURIUtil.class); } public void testEncodeWithinQuery() { String unescaped1= "abc123+ %_?=&#."; try { String stringRet = URIUtil.encodeWithinQuery(unescaped1); assertEquals("abc123%2B%20%25_%3F%3D%26%23.%C3%A4", stringRet); stringRet = URIUtil.decode(stringRet); assertEquals(unescaped1, stringRet); } catch(Exception e) { System.err.println("Exception thrown: "+e); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/TestVirtualHost.java100644 0 0 21257 10661532626 25767 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/TestVirtualHost.java,v 1.2 2004/10/31 14:42:59 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.RequestLine; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * HTTP protocol versioning tests. * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class TestVirtualHost extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestVirtualHost(final String testName) throws IOException { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestVirtualHost.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestVirtualHost.class); } private class VirtualService implements HttpService { public VirtualService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); Header hostheader = request.getFirstHeader("Host"); if (hostheader == null) { response.setStatusLine(httpversion, HttpStatus.SC_BAD_REQUEST); response.setBodyString("Host header missing"); } else { response.setStatusLine(httpversion, HttpStatus.SC_OK); response.setBodyString(hostheader.getValue()); } return true; } } public void testVirtualHostHeader() throws IOException { this.server.setHttpService(new VirtualService()); GetMethod httpget = new GetMethod("/test/"); HostConfiguration hostconf = new HostConfiguration(); hostconf.setHost(this.server.getLocalAddress(), this.server.getLocalPort(), "http"); hostconf.getParams().setVirtualHost("somehost"); try { this.client.executeMethod(hostconf, httpget); String hostheader = "somehost:" + this.server.getLocalPort(); assertEquals(hostheader, httpget.getResponseBodyAsString()); } finally { httpget.releaseConnection(); } } public void testNoVirtualHostHeader() throws IOException { this.server.setHttpService(new VirtualService()); GetMethod httpget = new GetMethod("/test/"); HostConfiguration hostconf = new HostConfiguration(); hostconf.setHost(this.server.getLocalAddress(), this.server.getLocalPort(), "http"); hostconf.getParams().setVirtualHost(null); try { this.client.executeMethod(hostconf, httpget); String hostheader = this.server.getLocalAddress() + ":" + this.server.getLocalPort(); assertEquals(hostheader, httpget.getResponseBodyAsString()); } finally { httpget.releaseConnection(); } } private class VirtualHostService implements HttpService { public VirtualHostService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine reqline = request.getRequestLine(); HttpVersion ver = reqline.getHttpVersion(); Header header = request.getFirstHeader("Host"); if (header == null) { response.setStatusLine(ver, HttpStatus.SC_BAD_REQUEST); return true; } String host = header.getValue(); if (host.equalsIgnoreCase("whatever.com")) { response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY); response.setHeader(new Header("Location", "testhttp://www.whatever.com/")); return true; } else if (host.equalsIgnoreCase("www.whatever.com")) { response.setStatusLine(ver, HttpStatus.SC_MOVED_TEMPORARILY); response.setHeader(new Header("Location", "testhttp://www.whatever.co.nz/")); return true; } else if (host.equalsIgnoreCase("www.whatever.co.nz")) { response.setStatusLine(ver, HttpStatus.SC_OK); return true; } else { response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND); return true; } } } private class VirtualSocketFactory implements ProtocolSocketFactory { private final String hostname; private final int port; public VirtualSocketFactory(final String hostname, int port) { super(); this.hostname = hostname; this.port = port; } public Socket createSocket( final String host, int port, final InetAddress localAddress, int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { return new Socket(this.hostname, this.port); } public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException, UnknownHostException { return new Socket(this.hostname, this.port); } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return new Socket(this.hostname, this.port); } } public void testRedirectWithVirtualHost() throws IOException { String host = this.server.getLocalAddress(); int port = this.server.getLocalPort(); Protocol testhttp = new Protocol("http", new VirtualSocketFactory(host, port), port); Protocol.registerProtocol("testhttp", testhttp); try { this.server.setHttpService(new VirtualHostService()); this.client.getHostConfiguration().setHost(host, port, "testhttp"); this.client.getHostConfiguration().getParams().setVirtualHost("whatever.com"); GetMethod httpget = new GetMethod("/"); httpget.setFollowRedirects(true); try { this.client.executeMethod(httpget); assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("http://www.whatever.co.nz/", httpget.getURI().toString()); } finally { httpget.releaseConnection(); } } finally { Protocol.unregisterProtocol("testhttp"); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/auth/TestAuthAll.java100644 0 0 4366 10661532626 25760 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestAuthAll.java,v 1.1 2004/10/31 13:46:54 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient.auth; import junit.framework.*; /** * @author Oleg Kalnichevski * * @version $Id: TestAuthAll.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestAuthAll extends TestCase { public TestAuthAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestChallengeParser.suite()); suite.addTest(TestChallengeProcessor.suite()); suite.addTest(TestBasicAuth.suite()); suite.addTest(TestDigestAuth.suite()); suite.addTest(TestNTLMAuth.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = { TestAuthAll.class.getName() }; junit.textui.TestRunner.main(testCaseName); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/auth/TestBasicAuth.java100644 0 0 62061 10661532626 26305 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestBasicAuth.java,v 1.9 2004/11/20 17:56:40 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import java.io.IOException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.EchoService; import org.apache.commons.httpclient.FeedbackService; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClientTestBase; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.ProxyTestDecorator; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.server.AuthRequestHandler; import org.apache.commons.httpclient.server.HttpRequestHandlerChain; import org.apache.commons.httpclient.server.HttpServiceHandler; import org.apache.commons.httpclient.util.EncodingUtil; /** * Basic authentication test cases. * * @author Oleg Kalnichevski * * @version $Id: TestBasicAuth.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestBasicAuth extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestBasicAuth(final String testName) throws IOException { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestBasicAuth.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { TestSuite suite = new TestSuite(TestBasicAuth.class); ProxyTestDecorator.addTests(suite); return suite; } public void testBasicAuthenticationWithNoCreds() throws IOException { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode()); AuthState authstate = httpget.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); } finally { httpget.releaseConnection(); } } public void testBasicAuthenticationWithNoCredsRetry() throws IOException { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode()); AuthState authstate = httpget.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); } finally { httpget.releaseConnection(); } // now try with credentials httpget = new GetMethod("/test/"); try { this.client.getState().setCredentials(AuthScope.ANY, creds); this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); } finally { httpget.releaseConnection(); } } public void testBasicAuthenticationWithNoRealm() { String challenge = "Basic"; try { AuthScheme authscheme = new BasicScheme(); authscheme.processChallenge(challenge); fail("Should have thrown MalformedChallengeException"); } catch(MalformedChallengeException e) { // expected } } public void testBasicAuthenticationWith88591Chars() throws Exception { int[] germanChars = { 0xE4, 0x2D, 0xF6, 0x2D, 0xFc }; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < germanChars.length; i++) { buffer.append((char)germanChars[i]); } UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("dh", buffer.toString()); assertEquals("Basic ZGg65C32Lfw=", BasicScheme.authenticate(credentials, "ISO-8859-1")); } public void testBasicAuthenticationWithDefaultCreds() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, creds); this.client.setState(state); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); Header auth = httpget.getRequestHeader("Authorization"); assertNotNull(auth); String expected = "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass"))); assertEquals(expected, auth.getValue()); AuthState authstate = httpget.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); } public void testBasicAuthentication() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); HttpState state = new HttpState(); AuthScope authscope = new AuthScope( this.server.getLocalAddress(), this.server.getLocalPort(), "test"); state.setCredentials(authscope, creds); this.client.setState(state); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); Header auth = httpget.getRequestHeader("Authorization"); assertNotNull(auth); String expected = "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass"))); assertEquals(expected, auth.getValue()); AuthState authstate = httpget.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); } public void testBasicAuthenticationWithInvalidCredentials() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); HttpState state = new HttpState(); AuthScope authscope = new AuthScope( this.server.getLocalAddress(), this.server.getLocalPort(), "test"); state.setCredentials(authscope, new UsernamePasswordCredentials("test", "stuff")); this.client.setState(state); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode()); AuthState authstate = httpget.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); } public void testBasicAuthenticationWithMutlipleRealms1() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); HttpState state = new HttpState(); AuthScope realm1 = new AuthScope( this.server.getLocalAddress(), this.server.getLocalPort(), "test"); AuthScope realm2 = new AuthScope( this.server.getLocalAddress(), this.server.getLocalPort(), "test2"); state.setCredentials(realm1, new UsernamePasswordCredentials("testuser","testpass")); state.setCredentials(realm2, new UsernamePasswordCredentials("testuser2","testpass2")); this.client.setState(state); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); Header auth = httpget.getRequestHeader("Authorization"); assertNotNull(auth); String expected = "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass"))); assertEquals(expected, auth.getValue()); AuthState authstate = httpget.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); } public void testBasicAuthenticationWithMutlipleRealms2() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser2", "testpass2"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test2")); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); HttpState state = new HttpState(); AuthScope realm1 = new AuthScope( this.server.getLocalAddress(), this.server.getLocalPort(), "test"); AuthScope realm2 = new AuthScope( this.server.getLocalAddress(), this.server.getLocalPort(), "test2"); state.setCredentials(realm1, new UsernamePasswordCredentials("testuser","testpass")); state.setCredentials(realm2, new UsernamePasswordCredentials("testuser2","testpass2")); this.client.setState(state); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test2/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); Header auth = httpget.getRequestHeader("Authorization"); assertNotNull(auth); String expected = "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser2:testpass2"))); assertEquals(expected, auth.getValue()); AuthState authstate = httpget.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test2", authstate.getRealm()); } public void testPreemptiveAuthorizationTrueWithCreds() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, creds); this.client.setState(state); this.client.getParams().setAuthenticationPreemptive(true); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); Header auth = httpget.getRequestHeader("Authorization"); assertNotNull(auth); String expected = "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass"))); assertEquals(expected, auth.getValue()); AuthState authstate = httpget.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertNull(authstate.getRealm()); assertTrue(authstate.isPreemptive()); } public void testPreemptiveAuthorizationTrueWithoutCreds() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); HttpState state = new HttpState(); this.client.setState(state); this.client.getParams().setAuthenticationPreemptive(true); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode()); Header auth = httpget.getRequestHeader("Authorization"); assertNull(auth); AuthState authstate = httpget.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertNotNull(authstate.getRealm()); assertTrue(authstate.isPreemptive()); } public void testCustomAuthorizationHeader() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); String authResponse = "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass"))); httpget.addRequestHeader(new Header("Authorization", authResponse)); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); } public void testHeadBasicAuthentication() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); HttpState state = new HttpState(); AuthScope authscope = new AuthScope( this.server.getLocalAddress(), this.server.getLocalPort(), "test"); state.setCredentials(authscope, creds); this.client.setState(state); this.server.setRequestHandler(handlerchain); HeadMethod head = new HeadMethod("/test/"); try { this.client.executeMethod(head); } finally { head.releaseConnection(); } assertNotNull(head.getStatusLine()); assertEquals(HttpStatus.SC_OK, head.getStatusLine().getStatusCode()); Header auth = head.getRequestHeader("Authorization"); assertNotNull(auth); String expected = "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass"))); assertEquals(expected, auth.getValue()); AuthState authstate = head.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); } public void testPostBasicAuthentication() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new EchoService())); HttpState state = new HttpState(); AuthScope authscope = new AuthScope( this.server.getLocalAddress(), this.server.getLocalPort(), "test"); state.setCredentials(authscope, creds); this.client.setState(state); this.server.setRequestHandler(handlerchain); PostMethod post = new PostMethod("/test/"); post.setRequestEntity(new StringRequestEntity("Test body", null, null)); try { this.client.executeMethod(post); assertEquals("Test body", post.getResponseBodyAsString()); } finally { post.releaseConnection(); } assertNotNull(post.getStatusLine()); assertEquals(HttpStatus.SC_OK, post.getStatusLine().getStatusCode()); Header auth = post.getRequestHeader("Authorization"); assertNotNull(auth); String expected = "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass"))); assertEquals(expected, auth.getValue()); AuthState authstate = post.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); } public void testPutBasicAuthentication() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new EchoService())); HttpState state = new HttpState(); AuthScope authscope = new AuthScope( this.server.getLocalAddress(), this.server.getLocalPort(), "test"); state.setCredentials(authscope, creds); this.client.setState(state); this.server.setRequestHandler(handlerchain); PutMethod put = new PutMethod("/test/"); put.setRequestEntity(new StringRequestEntity("Test body", null, null)); try { this.client.executeMethod(put); assertEquals("Test body", put.getResponseBodyAsString()); } finally { put.releaseConnection(); } assertNotNull(put.getStatusLine()); assertEquals(HttpStatus.SC_OK, put.getStatusLine().getStatusCode()); Header auth = put.getRequestHeader("Authorization"); assertNotNull(auth); String expected = "Basic " + EncodingUtil.getAsciiString( Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass"))); assertEquals(expected, auth.getValue()); AuthState authstate = put.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); } public void testPreemptiveAuthorizationFailure() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); UsernamePasswordCredentials wrongcreds = new UsernamePasswordCredentials("testuser", "garbage"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, wrongcreds); this.client.setState(state); this.client.getParams().setAuthenticationPreemptive(true); this.server.setRequestHandler(handlerchain); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode()); AuthState authstate = httpget.getHostAuthState(); assertNotNull(authstate.getAuthScheme()); assertTrue(authstate.getAuthScheme() instanceof BasicScheme); assertEquals("test", authstate.getRealm()); assertTrue(authstate.isPreemptive()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/auth/TestChallengeParser.java100644 0 0 6557 10661532626 27471 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestChallengeParser.java,v 1.1 2004/03/25 20:37:20 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.auth; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.util.Map; import org.apache.commons.httpclient.auth.AuthChallengeParser; import org.apache.commons.httpclient.auth.MalformedChallengeException; /** * Unit tests for {@link AuthChallengeParser}. * * @author Oleg Kalnichevski */ public class TestChallengeParser extends TestCase { // ------------------------------------------------------------ Constructor public TestChallengeParser(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestChallengeParser.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestChallengeParser.class); } public void testParsingChallenge() { String challenge = "Basic realm=\"realm1\", test, test1 = stuff, test2 = \"stuff, stuff\", test3=\"crap"; String scheme = null; Map elements = null; try { scheme = AuthChallengeParser.extractScheme(challenge); elements = AuthChallengeParser.extractParams(challenge); } catch (MalformedChallengeException e) { fail("Unexpected exception: " + e.toString()); } assertEquals("basic", scheme); assertEquals("realm1", elements.get("realm")); assertEquals(null, elements.get("test")); assertEquals("stuff", elements.get("test1")); assertEquals("stuff, stuff", elements.get("test2")); assertEquals("\"crap", elements.get("test3")); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/auth/TestChallengeProcessor.java100644 0 0 15326 10661532626 30226 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestChallengeProcessor.java,v 1.1 2004/03/25 20:37:20 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.auth; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.httpclient.params.DefaultHttpParams; import org.apache.commons.httpclient.params.HttpParams; /** * Unit tests for {@link testParsingChallenge}. * * @author Oleg Kalnichevski */ public class TestChallengeProcessor extends TestCase { // ------------------------------------------------------------ Constructor public TestChallengeProcessor(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestChallengeProcessor.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestChallengeProcessor.class); } public void testChallengeSelection() throws Exception { List authPrefs = new ArrayList(3); authPrefs.add(AuthPolicy.NTLM); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); HttpParams httpparams = new DefaultHttpParams(); httpparams.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); AuthChallengeProcessor processor = new AuthChallengeProcessor(httpparams); Map map = new HashMap(); map.put("unknown", "unknown realm=\"whatever\""); map.put("basic", "basic realm=\"whatever\""); AuthScheme authscheme = processor.selectAuthScheme(map); assertTrue(authscheme instanceof BasicScheme); } public void testInvalidChallenge() throws Exception { List authPrefs = new ArrayList(3); authPrefs.add("unsupported1"); authPrefs.add("unsupported2"); HttpParams httpparams = new DefaultHttpParams(); httpparams.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); AuthChallengeProcessor processor = new AuthChallengeProcessor(httpparams); Map map = new HashMap(); map.put("unsupported1", "unsupported1 realm=\"whatever\""); map.put("unsupported2", "unsupported2 realm=\"whatever\""); try { AuthScheme authscheme = processor.selectAuthScheme(map); fail("AuthChallengeException should have been thrown"); } catch (AuthChallengeException e) { //ignore } } public void testUnsupportedChallenge() throws Exception { List authPrefs = new ArrayList(3); authPrefs.add(AuthPolicy.NTLM); authPrefs.add(AuthPolicy.BASIC); authPrefs.add(AuthPolicy.DIGEST); HttpParams httpparams = new DefaultHttpParams(); httpparams.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); AuthChallengeProcessor processor = new AuthChallengeProcessor(httpparams); Map map = new HashMap(); map.put("unsupported1", "unsupported1 realm=\"whatever\""); map.put("unsupported2", "unsupported2 realm=\"whatever\""); try { AuthScheme authscheme = processor.selectAuthScheme(map); fail("AuthChallengeException should have been thrown"); } catch (AuthChallengeException e) { //expected } } public void testChallengeProcessing() throws Exception { HttpParams httpparams = new DefaultHttpParams(); AuthChallengeProcessor processor = new AuthChallengeProcessor(httpparams); Map map = new HashMap(); map.put("basic", "basic realm=\"whatever\", param=\"value\""); AuthState authstate = new AuthState(); AuthScheme authscheme = processor.processChallenge(authstate, map); assertTrue(authscheme instanceof BasicScheme); assertEquals("whatever", authscheme.getRealm()); assertEquals(authscheme, authstate.getAuthScheme()); assertEquals("value", authscheme.getParameter("param")); } public void testInvalidChallengeProcessing() throws Exception { HttpParams httpparams = new DefaultHttpParams(); AuthChallengeProcessor processor = new AuthChallengeProcessor(httpparams); Map map = new HashMap(); map.put("basic", "basic realm=\"whatever\", param=\"value\""); AuthState authstate = new AuthState(); AuthScheme authscheme = processor.processChallenge(authstate, map); assertTrue(authscheme instanceof BasicScheme); assertEquals("whatever", authscheme.getRealm()); assertEquals(authscheme, authstate.getAuthScheme()); assertEquals("value", authscheme.getParameter("param")); Map map2 = new HashMap(); map2.put("ntlm", "NTLM"); try { // Basic authentication scheme expected authscheme = processor.processChallenge(authstate, map2); fail("AuthenticationException should have been thrown"); } catch (AuthenticationException e) { //expected } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/auth/TestDigestAuth.java100644 0 0 36174 10661532626 26511 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestDigestAuth.java,v 1.2 2004/11/07 12:31:42 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import java.io.IOException; import java.util.Map; import org.apache.commons.httpclient.FakeHttpMethod; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.RequestLine; import org.apache.commons.httpclient.server.SimpleHttpServer; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test Methods for DigestScheme Authentication. * * @author Rodney Waldhoff * @author Jeff Dever * @author Oleg Kalnichevski */ public class TestDigestAuth extends TestCase { // ------------------------------------------------------------ Constructor public TestDigestAuth(String testName) { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestDigestAuth.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestDigestAuth.class); } public void testDigestAuthenticationWithNoRealm() throws Exception { String challenge = "Digest"; try { AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(challenge); fail("Should have thrown MalformedChallengeException"); } catch(MalformedChallengeException e) { // expected } } public void testDigestAuthenticationWithNoRealm2() throws Exception { String challenge = "Digest "; try { AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(challenge); fail("Should have thrown MalformedChallengeException"); } catch(MalformedChallengeException e) { // expected } } public void testDigestAuthenticationWithDefaultCreds() throws Exception { String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\""; FakeHttpMethod method = new FakeHttpMethod("/"); UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password"); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(challenge); String response = authscheme.authenticate(cred, method); Map table = AuthChallengeParser.extractParams(response); assertEquals("username", table.get("username")); assertEquals("realm1", table.get("realm")); assertEquals("/", table.get("uri")); assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response")); } public void testDigestAuthentication() throws Exception { String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\""; UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password"); FakeHttpMethod method = new FakeHttpMethod("/"); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(challenge); String response = authscheme.authenticate(cred, method); Map table = AuthChallengeParser.extractParams(response); assertEquals("username", table.get("username")); assertEquals("realm1", table.get("realm")); assertEquals("/", table.get("uri")); assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response")); } public void testDigestAuthenticationWithQueryStringInDigestURI() throws Exception { String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\""; UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password"); FakeHttpMethod method = new FakeHttpMethod("/"); method.setQueryString("param=value"); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(challenge); String response = authscheme.authenticate(cred, method); Map table = AuthChallengeParser.extractParams(response); assertEquals("username", table.get("username")); assertEquals("realm1", table.get("realm")); assertEquals("/?param=value", table.get("uri")); assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); assertEquals("a847f58f5fef0bc087bcb9c3eb30e042", table.get("response")); } public void testDigestAuthenticationWithMultipleRealms() throws Exception { String challenge1 = "Digest realm=\"realm1\", nonce=\"abcde\""; String challenge2 = "Digest realm=\"realm2\", nonce=\"123546\""; UsernamePasswordCredentials cred = new UsernamePasswordCredentials("username","password"); UsernamePasswordCredentials cred2 = new UsernamePasswordCredentials("uname2","password2"); FakeHttpMethod method = new FakeHttpMethod("/"); AuthScheme authscheme1 = new DigestScheme(); authscheme1.processChallenge(challenge1); String response1 = authscheme1.authenticate(cred, method); Map table = AuthChallengeParser.extractParams(response1); assertEquals("username", table.get("username")); assertEquals("realm1", table.get("realm")); assertEquals("/", table.get("uri")); assertEquals("abcde", table.get("nonce")); assertEquals("786f500303eac1478f3c2865e676ed68", table.get("response")); AuthScheme authscheme2 = new DigestScheme(); authscheme2.processChallenge(challenge2); String response2 = authscheme2.authenticate(cred2, method); table = AuthChallengeParser.extractParams(response2); assertEquals("uname2", table.get("username")); assertEquals("realm2", table.get("realm")); assertEquals("/", table.get("uri")); assertEquals("123546", table.get("nonce")); assertEquals("0283edd9ef06a38b378b3b74661391e9", table.get("response")); } /** * Test digest authentication using the MD5-sess algorithm. */ public void testDigestAuthenticationMD5Sess() throws Exception { // Example using Digest auth with MD5-sess String realm="realm"; String username="username"; String password="password"; String nonce="e273f1776275974f1a120d8b92c5b3cb"; String challenge="Digest realm=\"" + realm + "\", " + "nonce=\"" + nonce + "\", " + "opaque=\"SomeString\", " + "stale=false, " + "algorithm=MD5-sess, " + "qop=\"auth,auth-int\""; // we pass both but expect auth to be used UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password); FakeHttpMethod method = new FakeHttpMethod("/"); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(challenge); String response = authscheme.authenticate(cred, method); assertTrue(response.indexOf("nc=00000001") > 0); // test for quotes assertTrue(response.indexOf("qop=auth") > 0); // test for quotes Map table = AuthChallengeParser.extractParams(response); assertEquals(username, table.get("username")); assertEquals(realm, table.get("realm")); assertEquals("MD5-sess", table.get("algorithm")); assertEquals("/", table.get("uri")); assertEquals(nonce, table.get("nonce")); assertEquals(1, Integer.parseInt((String) table.get("nc"),16)); assertTrue(null != table.get("cnonce")); assertEquals("SomeString", table.get("opaque")); assertEquals("auth", table.get("qop")); //@TODO: add better check assertTrue(null != table.get("response")); } /** * Test digest authentication using the MD5-sess algorithm. */ public void testDigestAuthenticationMD5SessNoQop() throws Exception { // Example using Digest auth with MD5-sess String realm="realm"; String username="username"; String password="password"; String nonce="e273f1776275974f1a120d8b92c5b3cb"; String challenge="Digest realm=\"" + realm + "\", " + "nonce=\"" + nonce + "\", " + "opaque=\"SomeString\", " + "stale=false, " + "algorithm=MD5-sess"; UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password); FakeHttpMethod method = new FakeHttpMethod("/"); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(challenge); String response = authscheme.authenticate(cred, method); Map table = AuthChallengeParser.extractParams(response); assertEquals(username, table.get("username")); assertEquals(realm, table.get("realm")); assertEquals("MD5-sess", table.get("algorithm")); assertEquals("/", table.get("uri")); assertEquals(nonce, table.get("nonce")); assertTrue(null == table.get("nc")); assertEquals("SomeString", table.get("opaque")); assertTrue(null == table.get("qop")); //@TODO: add better check assertTrue(null != table.get("response")); } /** * Test digest authentication with invalud qop value */ public void testDigestAuthenticationMD5SessInvalidQop() throws Exception { // Example using Digest auth with MD5-sess String realm="realm"; String username="username"; String password="password"; String nonce="e273f1776275974f1a120d8b92c5b3cb"; String challenge="Digest realm=\"" + realm + "\", " + "nonce=\"" + nonce + "\", " + "opaque=\"SomeString\", " + "stale=false, " + "algorithm=MD5-sess, " + "qop=\"jakarta\""; // jakarta is an invalid qop value UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password); try { AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(challenge); fail("MalformedChallengeException exception expected due to invalid qop value"); } catch(MalformedChallengeException e) { } } private class StaleNonceService implements HttpService { public StaleNonceService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine requestLine = request.getRequestLine(); HttpVersion ver = requestLine.getHttpVersion(); Header auth = request.getFirstHeader("Authorization"); if (auth == null) { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "Digest realm=\"realm1\", nonce=\"ABC123\"")); response.setBodyString("Authorization required"); return true; } else { Map table = AuthChallengeParser.extractParams(auth.getValue()); String nonce = (String)table.get("nonce"); if (nonce.equals("ABC123")) { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "Digest realm=\"realm1\", nonce=\"321CBA\", stale=\"true\"")); response.setBodyString("Authorization required"); return true; } else { response.setStatusLine(ver, HttpStatus.SC_OK); response.setBodyString("Authorization successful"); return true; } } } } public void testDigestAuthenticationWithStaleNonce() throws Exception { // configure the server SimpleHttpServer server = new SimpleHttpServer(); // use arbitrary port server.setTestname(getName()); server.setHttpService(new StaleNonceService()); // configure the client HttpClient client = new HttpClient(); client.getHostConfiguration().setHost( server.getLocalAddress(), server.getLocalPort(), Protocol.getProtocol("http")); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username","password")); FakeHttpMethod httpget = new FakeHttpMethod("/"); try { client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); Map table = AuthChallengeParser.extractParams( httpget.getRequestHeader("Authorization").getValue()); assertEquals("username", table.get("username")); assertEquals("realm1", table.get("realm")); assertEquals("/", table.get("uri")); assertEquals("321CBA", table.get("nonce")); assertEquals("7f5948eefa115296e9279225041527b3", table.get("response")); server.destroy(); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/auth/TestNTLMAuth.java100644 0 0 23713 10661532626 26037 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/auth/TestNTLMAuth.java,v 1.2 2004/11/07 12:31:42 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.auth; import java.io.IOException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.FakeHttpMethod; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClientTestBase; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.NTCredentials; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.RequestLine; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * Test Methods for NTLM Authentication. * * @author Rodney Waldhoff * @author Jeff Dever * @version $Id: TestNTLMAuth.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestNTLMAuth extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestNTLMAuth(String testName) throws IOException { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestNTLMAuth.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestNTLMAuth.class); } // --------------------------------- public void testNTLMAuthenticationResponse1() throws Exception { String challenge = "NTLM"; String expected = "NTLM TlRMTVNTUAABAAAABlIAAAYABgAkAAAABAAEACAAAABIT" + "1NURE9NQUlO"; NTCredentials cred = new NTCredentials("username","password", "host", "domain"); FakeHttpMethod method = new FakeHttpMethod(); AuthScheme authscheme = new NTLMScheme(challenge); authscheme.processChallenge(challenge); String response = authscheme.authenticate(cred, method); assertEquals(expected, response); assertFalse(authscheme.isComplete()); } public void testNTLMAuthenticationResponse2() throws Exception { String challenge = "NTLM TlRMTVNTUAACAAAACgAKADAAAAAGgoEAPc4kP4LtCV8AAAAAAAAAAJ4AngA" + "6AAAASU5UUkFFUEhPWAIAFABJAE4AVABSAEEARQBQAEgATwBYAAEAEgBCAE8AQQB" + "SAEQAUgBPAE8ATQAEACgAaQBuAHQAcgBhAGUAcABoAG8AeAAuAGUAcABoAG8AeAA" + "uAGMAbwBtAAMAPABCAG8AYQByAGQAcgBvAG8AbQAuAGkAbgB0AHIAYQBlAHAAaAB" + "vAHgALgBlAHAAaABvAHgALgBjAG8AbQAAAAAA"; String expected = "NTLM TlRMTVNTUAADAAAAGAAYAFIAAAAAAAAAagAAAAYABgB" + "AAAAACAAIAEYAAAAEAAQATgAAAAAAAABqAAAABlIAAERPTUFJTlVTRVJOQU1FSE" + "9TVAaC+vLxUEHnUtpItj9Dp4kzwQfd61Lztg=="; NTCredentials cred = new NTCredentials("username","password", "host", "domain"); FakeHttpMethod method = new FakeHttpMethod(); AuthScheme authscheme = new NTLMScheme(challenge); authscheme.processChallenge(challenge); String response = authscheme.authenticate(cred, method); assertEquals(expected, response); assertTrue(authscheme.isComplete()); } private class NTLMAuthService implements HttpService { public NTLMAuthService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine requestLine = request.getRequestLine(); HttpVersion ver = requestLine.getHttpVersion(); Header auth = request.getFirstHeader("Authorization"); if (auth == null) { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "NTLM")); response.setBodyString("Authorization required"); return true; } else { String authstr = auth.getValue(); if (authstr.equals("NTLM TlRMTVNTUAABAAAABlIAAAYABgAkAAAABAAEACAAAABIT1NURE9NQUlO")) { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA==")); response.setBodyString("Authorization required"); return true; } if (authstr.equals("NTLM TlRMTVNTUAADAAAAGAAYAFIAAAAAAAAAagAAAAYABgBAAAAACAAIAEYAAAAEAAQATgAAAAAAAABqAAAABlIAAERPTUFJTlVTRVJOQU1FSE9TVJxndWIt46bHm11TPrt5Z6wrz7ziq04yRA==")) { response.setStatusLine(ver, HttpStatus.SC_OK); response.setBodyString("Authorization successful"); return true; } else { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "NTLM")); response.setBodyString("Authorization required"); return true; } } } } public void testNTLMAuthenticationRetry() throws Exception { this.server.setHttpService(new NTLMAuthService()); // configure the client this.client.getHostConfiguration().setHost( server.getLocalAddress(), server.getLocalPort(), Protocol.getProtocol("http")); this.client.getState().setCredentials(AuthScope.ANY, new NTCredentials("username", "password", "host", "domain")); FakeHttpMethod httpget = new FakeHttpMethod("/"); try { client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNull(httpget.getResponseHeader("WWW-Authenticate")); assertEquals(200, httpget.getStatusCode()); } private class PreemptiveNTLMAuthService implements HttpService { public PreemptiveNTLMAuthService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { RequestLine requestLine = request.getRequestLine(); HttpVersion ver = requestLine.getHttpVersion(); Header auth = request.getFirstHeader("Authorization"); if (auth == null) { response.setStatusLine(ver, HttpStatus.SC_BAD_REQUEST); response.setBodyString("Authorization header missing"); return true; } else { String authstr = auth.getValue(); if (authstr.indexOf("NTLM") != -1) { response.setStatusLine(ver, HttpStatus.SC_OK); return true; } else if (authstr.indexOf("Basic") != -1) { response.setStatusLine(ver, HttpStatus.SC_UNAUTHORIZED); response.addHeader(new Header("WWW-Authenticate", "Negotiate")); response.addHeader(new Header("WWW-Authenticate", "NTLM")); response.setBodyString("Authorization required"); return true; } else { response.setStatusLine(ver, HttpStatus.SC_BAD_REQUEST); response.setBodyString("Unknown auth type: " + authstr); return true; } } } } /** * Make sure preemptive authorization works when the server requires NLM. * @throws Exception */ public void testPreemptiveAuthorization() throws Exception { NTCredentials creds = new NTCredentials("testuser", "testpass", "host", "domain"); HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, creds); this.client.setState(state); this.client.getParams().setAuthenticationPreemptive(true); this.server.setHttpService(new PreemptiveNTLMAuthService()); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookie.java100644 0 0 13111 10661532626 26153 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookie.java,v 1.2 2004/04/25 12:25:09 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; /** * Test cases for Cookie * * @author BC Holmes * @author Rod Waldhoff * @author dIon Gillard * @author John Evans * @author Marc A. Saegesser * @author Oleg Kalnichevski * @version $Revision: 480424 $ */ public class TestCookie extends TestCookieBase { // ------------------------------------------------------------ Constructor public TestCookie(String name) { super(name); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestCookie.class); } /** * Tests default constructor. */ public void testDefaultConstuctor() { Cookie dummy = new Cookie(); assertEquals( "noname=", dummy.toExternalForm() ); } public void testComparator() throws Exception { Header setCookie = null; Cookie[] parsed = null; Vector cookies = new Vector(); // Cookie 0 setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons;Domain=.apache.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT"); CookieSpec cookiespec = new CookieSpecBase(); parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/httpclient", true, setCookie); cookies.add(parsed[0]); // Cookie 1 setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons/bif;Domain=.apache.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT"); parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/bif/httpclient", true, setCookie); cookies.add(parsed[0]); // Cookie 2 setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons;Domain=.baz.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT"); parsed = cookieParse(cookiespec, ".baz.org", 80, "/commons/httpclient", true, setCookie); cookies.add(parsed[0]); // Cookie 3 setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons/bif;Domain=.baz.org;Expires=Thu, 01-Jan-1970 00:00:10 GMT"); parsed = cookieParse(cookiespec, ".baz.org", 80, "/commons/bif/httpclient", true, setCookie); cookies.add(parsed[0]); // Cookie 4 setCookie = new Header("Set-Cookie","cookie-name=cookie-value;Path=/commons;Domain=.baz.com;Expires=Thu, 01-Jan-1970 00:00:10 GMT"); parsed = cookieParse(cookiespec, ".baz.com", 80, "/commons/httpclient", true, setCookie); cookies.add(parsed[0]); // The order should be: // 1, 0, 3, 2, 4 parsed = (Cookie[])cookies.toArray(new Cookie[0]); SortedSet set = new TreeSet(parsed[0]); int pass = 0; for (Iterator itr = set.iterator(); itr.hasNext();) { Cookie cookie = (Cookie)itr.next(); switch (pass) { case 0: assertTrue("0th cookie should be cookie[1]", cookie == parsed[1]); break; case 1: assertTrue("1st cookie should be cookie[0]", cookie == parsed[0]); break; case 2: assertTrue("2nd cookie should be cookie[3]", cookie == parsed[3]); break; case 3: assertTrue("3rd cookie should be cookie[2]", cookie == parsed[2]); break; case 4: assertTrue("4th cookie should be cookie[4]", cookie == parsed[4]); break; default: fail("This should never happen."); } pass++; } try { parsed[0].compare("foo", "bar"); fail("Should have thrown an exception trying to compare non-cookies"); } catch (ClassCastException ex) { // expected } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookie2.java100644 0 0 11472 10661532627 26246 0ustar 0 0 /* * $Header: /cvsroot/httpc-cookie2/httpc-cookie2/httpcookie2SVN-patch.082805-2100.diff,v 1.1 2005/08/29 05:01:58 sjain700 Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.*; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; /** * Test cases for {@link Cookie2}. * * @author Samit Jain (jain.samit@gmail.com) */ public class TestCookie2 extends TestCookieBase { // ------------------------------------------------------------ Constructor public TestCookie2(String name) { super(name); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestCookie2.class); } /** * Tests default constructor. */ public void testDefaultConstuctor() { Cookie2 dummy = new Cookie2(); // check cookie properties (default values) assertNull(dummy.getPorts()); assertFalse(dummy.getSecure()); assertFalse(dummy.isExpired()); assertFalse(dummy.isDomainAttributeSpecified()); assertFalse(dummy.isPathAttributeSpecified()); assertFalse(dummy.isPortAttributeSpecified()); assertFalse(dummy.isVersionAttributeSpecified()); assertFalse(dummy.isPersistent()); Cookie2 dummy2 = new Cookie2(); assertEquals(dummy, dummy2); } public void testComparator() throws Exception { Header setCookie2 = null; Cookie[] parsed = null; List cookies = new LinkedList(); CookieSpec cookiespec = new RFC2965Spec(); // Cookie 0 setCookie2 = new Header("Set-Cookie2","cookie-name=Cookie0; Version=1"); parsed = cookieParse(cookiespec, "domain.com", 80, "/path/path1", true, setCookie2); cookies.add(parsed[0]); // Cookie 1 setCookie2 = new Header("Set-Cookie2","cookie-name=Cookie1; Version=1"); parsed = cookieParse(cookiespec, "domain.com", 80, "/path", true, setCookie2); cookies.add(parsed[0]); // Cookie 2 setCookie2 = new Header("Set-Cookie2","cookie-name=Cookie2; Version=1"); parsed = cookieParse(cookiespec, "domain.com", 80, "/", true, setCookie2); cookies.add(parsed[0]); // Cookie 3 setCookie2 = new Header("Set-Cookie2","cookie-name=Cookie3; Version=1"); parsed = cookieParse(cookiespec, "domain.com", 80, "/path/path1/path2", true, setCookie2); cookies.add(parsed[0]); // Cookie 4 setCookie2 = new Header("Set-Cookie2","cookie-name=Cookie4; Version=1"); parsed = cookieParse(cookiespec, "domain.com", 80, "/path/path1/path2/path3", true, setCookie2); cookies.add(parsed[0]); // The ascending order should be: // 2, 1, 0, 3, 4 int[] expectedOrder = new int[] {2, 1, 0, 3, 4}; Set sortedCookies = new TreeSet(parsed[0]); sortedCookies.addAll(cookies); int pass = 0; for (Iterator itr = sortedCookies.iterator(); itr.hasNext(); ++pass) { Cookie2 cookie = (Cookie2) itr.next(); assertTrue("sortedCookies[" + pass + "] should be cookies[" + expectedOrder[pass] + "]", cookie == cookies.get(expectedOrder[pass])); } try { parsed[0].compare(parsed[0], "foo"); fail("Should have thrown an exception trying to compare non-cookies"); } catch (ClassCastException expected) {} } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookieAll.java100644 0 0 5115 10661532626 26571 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieAll.java,v 1.3 2004/12/24 20:36:13 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient.cookie; import junit.framework.*; /** * @author oleg Kalnichevski * * @version $Id: TestCookieAll.java 480424 2006-11-29 05:56:49Z bayard $ */ public class TestCookieAll extends TestCase { public TestCookieAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestCookie.suite()); suite.addTest(TestCookie2.suite()); suite.addTest(TestCookieCompatibilitySpec.suite()); suite.addTest(TestCookieRFC2109Spec.suite()); suite.addTest(TestCookieRFC2965Spec.suite()); suite.addTest(TestCookieNetscapeDraft.suite()); suite.addTest(TestCookieIgnoreSpec.suite()); suite.addTest(TestCookiePolicy.suite()); suite.addTest(TestDateParser.suite()); suite.addTest(TestCookiePathComparator.suite()); suite.addTest(TestCookieVersionSupport.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = { TestCookieAll.class.getName() }; junit.textui.TestRunner.main(testCaseName); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookieBase.java100644 0 0 4704 10661532626 26736 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieBase.java,v 1.1 2004/04/24 19:39:24 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import junit.framework.TestCase; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; /** * Test cases for Cookie * * @author Oleg Kalnichevski * @version $Revision: 480424 $ */ public class TestCookieBase extends TestCase { // ------------------------------------------------------------ Constructor public TestCookieBase(String name) { super(name); } public static Cookie[] cookieParse( final CookieSpec parser, String host, int port, String path, boolean isSecure, Header setHeader) throws MalformedCookieException { Cookie[] cookies = parser.parse(host, port, path, isSecure, setHeader); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { parser.validate(host, port, path, isSecure, cookies[i]); } } return cookies; } } ././@LongLink100644 0 0 146 10661532634 10262 Lustar 0 0 commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookieCompatibilitySpec.javacommons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookieCompatibilitySpec.jav100644 0 0 134376 10661532630 31413 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieCompatibilitySpec.java,v 1.7 2004/09/14 20:11:32 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.Collection; import java.util.Date; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.params.DefaultHttpParamsFactory; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.params.HttpParams; /** * Test cases for Cookie * * @author BC Holmes * @author Rod Waldhoff * @author dIon Gillard * @author John Evans * @author Marc A. Saegesser * @author Oleg Kalnichevski * @version $Revision: 480424 $ */ public class TestCookieCompatibilitySpec extends TestCookieBase { // ------------------------------------------------------------ Constructor public TestCookieCompatibilitySpec(String name) { super(name); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestCookieCompatibilitySpec.class); } public void testParseAttributeInvalidAttrib() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); try { cookiespec.parseAttribute(null, null); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testParseAttributeInvalidCookie() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); try { cookiespec.parseAttribute(new NameValuePair("name", "value"), null); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testParseAttributeNullPath() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); cookiespec.parseAttribute(new NameValuePair("path", null), cookie); assertEquals("/", cookie.getPath()); } public void testParseAttributeBlankPath() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); cookiespec.parseAttribute(new NameValuePair("path", " "), cookie); assertEquals("/", cookie.getPath()); } public void testParseAttributeNullDomain() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.parseAttribute(new NameValuePair("domain", null), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } public void testParseAttributeBlankDomain() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.parseAttribute(new NameValuePair("domain", " "), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } public void testParseAttributeNullMaxAge() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.parseAttribute(new NameValuePair("max-age", null), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } public void testParseAttributeInvalidMaxAge() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.parseAttribute(new NameValuePair("max-age", "crap"), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } public void testParseAttributeNullExpires() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.parseAttribute(new NameValuePair("expires", null), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } public void testParseAttributeUnknownValue() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); cookiespec.parseAttribute(new NameValuePair("nonsense", null), cookie); } public void testValidateNullHost() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.validate(null, 80, "/", false, cookie); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testValidateBlankHost() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.validate(" ", 80, "/", false, cookie); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testValidateNullPath() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.validate("host", 80, null, false, cookie); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testValidateBlankPath() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie("host", "name", "value", "/", null, false); cookiespec.validate("host", 80, " ", false, cookie); } public void testValidateInvalidPort() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.validate("host", -80, "/", false, cookie); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testValidateInvalidCookieVersion() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); cookie.setVersion(-1); try { cookiespec.validate("host", 80, "/", false, cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } /** * Tests whether domain attribute check is case-insensitive. */ public void testDomainCaseInsensitivity() throws Exception { Header header = new Header("Set-Cookie", "name=value; path=/; domain=.whatever.com"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "www.WhatEver.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); assertEquals(".whatever.com", parsed[0].getDomain()); } /** * Test basic parse (with various spacings */ public void testParse1() throws Exception { String headerValue = "custno = 12345; comment=test; version=1," + " name=John; version=1; max-age=600; secure; domain=.apache.org"; Header header = new Header("set-cookie", headerValue); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] cookies = cookieParse(cookiespec, "www.apache.org", 80, "/", false, header); assertEquals(2, cookies.length); assertEquals("custno", cookies[0].getName()); assertEquals("12345", cookies[0].getValue()); assertEquals("test", cookies[0].getComment()); assertEquals(0, cookies[0].getVersion()); assertEquals("www.apache.org", cookies[0].getDomain()); assertEquals("/", cookies[0].getPath()); assertFalse(cookies[0].getSecure()); assertEquals("name", cookies[1].getName()); assertEquals("John", cookies[1].getValue()); assertEquals(null, cookies[1].getComment()); assertEquals(0, cookies[1].getVersion()); assertEquals(".apache.org", cookies[1].getDomain()); assertEquals("/", cookies[1].getPath()); assertTrue(cookies[1].getSecure()); } /** * Test no spaces */ public void testParse2() throws Exception { String headerValue = "custno=12345;comment=test; version=1," + "name=John;version=1;max-age=600;secure;domain=.apache.org"; Header header = new Header("set-cookie", headerValue); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] cookies = cookieParse(cookiespec, "www.apache.org", 80, "/", false, header); assertEquals(2, cookies.length); assertEquals("custno", cookies[0].getName()); assertEquals("12345", cookies[0].getValue()); assertEquals("test", cookies[0].getComment()); assertEquals(0, cookies[0].getVersion()); assertEquals("www.apache.org", cookies[0].getDomain()); assertEquals("/", cookies[0].getPath()); assertFalse(cookies[0].getSecure()); assertEquals("name", cookies[1].getName()); assertEquals("John", cookies[1].getValue()); assertEquals(null, cookies[1].getComment()); assertEquals(0, cookies[1].getVersion()); assertEquals(".apache.org", cookies[1].getDomain()); assertEquals("/", cookies[1].getPath()); assertTrue(cookies[1].getSecure()); } /** * Test parse with quoted text */ public void testParse3() throws Exception { String headerValue = "name=\"Doe, John\";version=1;max-age=600;secure;domain=.apache.org"; Header header = new Header("set-cookie", headerValue); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] cookies = cookieParse(cookiespec, "www.apache.org", 80, "/", false, header); assertEquals(1, cookies.length); assertEquals("name", cookies[0].getName()); assertEquals("Doe, John", cookies[0].getValue()); assertEquals(null, cookies[0].getComment()); assertEquals(0, cookies[0].getVersion()); assertEquals(".apache.org", cookies[0].getDomain()); assertEquals("/", cookies[0].getPath()); assertTrue(cookies[0].getSecure()); } // see issue #5279 public void testQuotedExpiresAttribute() throws Exception { String headerValue = "custno=12345;Expires='Thu, 01-Jan-2070 00:00:10 GMT'"; Header header = new Header("set-cookie", headerValue); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] cookies = cookieParse(cookiespec, "www.apache.org", 80, "/", true, header); assertNotNull("Expected some cookies",cookies); assertEquals("Expected 1 cookie",1,cookies.length); assertNotNull("Expected cookie to have getExpiryDate",cookies[0].getExpiryDate()); } public void testSecurityError() throws Exception { String headerValue = "custno=12345;comment=test; version=1," + "name=John;version=1;max-age=600;secure;domain=jakarta.apache.org"; Header header = new Header("set-cookie", headerValue); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] cookies = cookieParse(cookiespec, "www.apache.org", 80, "/", false, header); fail("HttpException exception should have been thrown"); } catch (HttpException e) { // expected } } public void testParseSimple() throws Exception { Header header = new Header("Set-Cookie","cookie-name=cookie-value"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/path/path", false, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value","cookie-value",parsed[0].getValue()); assertTrue("Comment",null == parsed[0].getComment()); assertTrue("ExpiryDate",null == parsed[0].getExpiryDate()); //assertTrue("isToBeDiscarded",parsed[0].isToBeDiscarded()); assertTrue("isPersistent",!parsed[0].isPersistent()); assertEquals("Domain","127.0.0.1",parsed[0].getDomain()); assertEquals("Path","/path",parsed[0].getPath()); assertTrue("Secure",!parsed[0].getSecure()); assertEquals("Version",0,parsed[0].getVersion()); } public void testParseSimple2() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/path", false, header); assertEquals("Found 1 cookie.", 1, parsed.length); assertEquals("Name", "cookie-name", parsed[0].getName()); assertEquals("Value", "cookie-value", parsed[0].getValue()); assertTrue("Comment", null == parsed[0].getComment()); assertTrue("ExpiryDate", null == parsed[0].getExpiryDate()); //assertTrue("isToBeDiscarded",parsed[0].isToBeDiscarded()); assertTrue("isPersistent", !parsed[0].isPersistent()); assertEquals("Domain", "127.0.0.1", parsed[0].getDomain()); assertEquals("Path", "/", parsed[0].getPath()); assertTrue("Secure", !parsed[0].getSecure()); assertEquals("Version", 0, parsed[0].getVersion()); } public void testParseNoName() throws Exception { Header header = new Header("Set-Cookie","=stuff; path=/"); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } public void testParseNoValue() throws Exception { Header header = new Header("Set-Cookie","cookie-name="); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value", "", parsed[0].getValue()); assertTrue("Comment",null == parsed[0].getComment()); assertTrue("ExpiryDate",null == parsed[0].getExpiryDate()); //assertTrue("isToBeDiscarded",parsed[0].isToBeDiscarded()); assertTrue("isPersistent",!parsed[0].isPersistent()); assertEquals("Domain","127.0.0.1",parsed[0].getDomain()); assertEquals("Path","/",parsed[0].getPath()); assertTrue("Secure",!parsed[0].getSecure()); assertEquals("Version",0,parsed[0].getVersion()); } public void testParseWithWhiteSpace() throws Exception { Header header = new Header("Set-Cookie"," cookie-name = cookie-value "); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value","cookie-value",parsed[0].getValue()); assertEquals("Domain","127.0.0.1",parsed[0].getDomain()); assertEquals("Path","/",parsed[0].getPath()); assertTrue("Secure",!parsed[0].getSecure()); assertTrue("ExpiryDate",null == parsed[0].getExpiryDate()); assertTrue("Comment",null == parsed[0].getComment()); } public void testParseWithQuotes() throws Exception { Header header = new Header("Set-Cookie"," cookie-name = \" cookie-value \" ;path=/"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1",80, "/", false, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value"," cookie-value ",parsed[0].getValue()); assertEquals("Domain","127.0.0.1",parsed[0].getDomain()); assertEquals("Path","/",parsed[0].getPath()); assertTrue("Secure",!parsed[0].getSecure()); assertTrue("ExpiryDate",null == parsed[0].getExpiryDate()); assertTrue("Comment",null == parsed[0].getComment()); } public void testParseWithPath() throws Exception { Header header = new Header("Set-Cookie","cookie-name=cookie-value; Path=/path/"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1",80, "/path/path", false, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value","cookie-value",parsed[0].getValue()); assertEquals("Domain","127.0.0.1",parsed[0].getDomain()); assertEquals("Path","/path/",parsed[0].getPath()); assertTrue("Secure",!parsed[0].getSecure()); assertTrue("ExpiryDate",null == parsed[0].getExpiryDate()); assertTrue("Comment",null == parsed[0].getComment()); } public void testParseWithDomain() throws Exception { Header header = new Header("Set-Cookie","cookie-name=cookie-value; Domain=127.0.0.1"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value","cookie-value",parsed[0].getValue()); assertEquals("Domain","127.0.0.1",parsed[0].getDomain()); assertEquals("Path","/",parsed[0].getPath()); assertTrue("Secure",!parsed[0].getSecure()); assertTrue("ExpiryDate",null == parsed[0].getExpiryDate()); assertTrue("Comment",null == parsed[0].getComment()); } public void testParseWithSecure() throws Exception { Header header = new Header("Set-Cookie","cookie-name=cookie-value; secure"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", true, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value","cookie-value",parsed[0].getValue()); assertEquals("Domain","127.0.0.1",parsed[0].getDomain()); assertEquals("Path","/",parsed[0].getPath()); assertTrue("Secure",parsed[0].getSecure()); assertTrue("ExpiryDate",null == parsed[0].getExpiryDate()); assertTrue("Comment",null == parsed[0].getComment()); } public void testParseWithComment() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; comment=\"This is a comment.\""); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", true, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value","cookie-value",parsed[0].getValue()); assertEquals("Domain","127.0.0.1",parsed[0].getDomain()); assertEquals("Path","/",parsed[0].getPath()); assertTrue("Secure",!parsed[0].getSecure()); assertTrue("ExpiryDate",null == parsed[0].getExpiryDate()); assertEquals("Comment","This is a comment.",parsed[0].getComment()); } public void testParseWithExpires() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value;Expires=Thu, 01-Jan-1970 00:00:10 GMT"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", true, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value","cookie-value",parsed[0].getValue()); assertEquals("Domain","127.0.0.1",parsed[0].getDomain()); assertEquals("Path","/",parsed[0].getPath()); assertTrue("Secure",!parsed[0].getSecure()); assertEquals(new Date(10000L),parsed[0].getExpiryDate()); assertTrue("Comment",null == parsed[0].getComment()); } public void testParseWithAll() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value;Version=1;Path=/commons;Domain=.apache.org;" + "Comment=This is a comment.;secure;Expires=Thu, 01-Jan-1970 00:00:10 GMT"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/httpclient", true, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value","cookie-value",parsed[0].getValue()); assertEquals("Domain",".apache.org",parsed[0].getDomain()); assertEquals("Path","/commons",parsed[0].getPath()); assertTrue("Secure",parsed[0].getSecure()); assertEquals(new Date(10000L),parsed[0].getExpiryDate()); assertEquals("Comment","This is a comment.",parsed[0].getComment()); assertEquals("Version",0,parsed[0].getVersion()); } public void testParseMultipleDifferentPaths() throws Exception { Header header = new Header("Set-Cookie", "name1=value1;Version=1;Path=/commons,name1=value2;Version=1;" + "Path=/commons/httpclient;Version=1"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/httpclient", true, header); HttpState state = new HttpState(); state.addCookies(parsed); Cookie[] cookies = state.getCookies(); assertEquals("Wrong number of cookies.",2,cookies.length); assertEquals("Name","name1",cookies[0].getName()); assertEquals("Value","value1",cookies[0].getValue()); assertEquals("Name","name1",cookies[1].getName()); assertEquals("Value","value2",cookies[1].getValue()); } public void testParseMultipleSamePaths() throws Exception { Header header = new Header("Set-Cookie", "name1=value1;Version=1;Path=/commons,name1=value2;Version=1;Path=/commons"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/httpclient", true, header); HttpState state = new HttpState(); state.addCookies(parsed); Cookie[] cookies = state.getCookies(); assertEquals("Found 1 cookies.",1,cookies.length); assertEquals("Name","name1",cookies[0].getName()); assertEquals("Value","value2",cookies[0].getValue()); } public void testParseRelativePath() throws Exception { Header header = new Header("Set-Cookie", "name1=value1;Path=whatever"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, ".apache.org", 80, "whatever", true, header); assertEquals("Found 1 cookies.",1,parsed.length); assertEquals("Name","name1",parsed[0].getName()); assertEquals("Value","value1",parsed[0].getValue()); assertEquals("Path","whatever",parsed[0].getPath()); } public void testParseWithWrongDomain() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; version=1"); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookieParse(cookiespec, "127.0.0.2", 80, "/", false, header); fail("HttpException exception should have been thrown"); } catch (HttpException e) { // expected } } public void testParseWithNullHost() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookieParse(cookiespec, null, 80, "/", false, header); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } } public void testParseWithBlankHost() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookieParse(cookiespec, " ", 80, "/", false, header); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } } public void testParseWithNullPath() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, null, false, header); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } } public void testParseWithBlankPath() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, " ", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); assertEquals("/", parsed[0].getPath()); } public void testParseWithNegativePort() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", -80, null, false, header); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } } public void testParseWithNullHostAndPath() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookieParse(cookiespec, null, 80, null, false, header); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } } public void testParseWithPathMismatch() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; path=/path/path/path"); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/path", false, header); fail("MalformedCookieException should have been thrown."); } catch (MalformedCookieException e) { // expected } } public void testParseWithPathMismatch2() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; path=/foobar"); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/foo", false, header); fail("MalformedCookieException should have been thrown."); } catch (MalformedCookieException e) { // expected } } public void testParseWithInvalidHeader1() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookiespec.parse("127.0.0.1", 80, "/foo", false, (Header)null); fail("IllegalArgumentException should have been thrown."); } catch (IllegalArgumentException e) { // expected } } public void testParseWithInvalidHeader2() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookiespec.parse("127.0.0.1", 80, "/foo", false, (String)null); fail("IllegalArgumentException should have been thrown."); } catch (IllegalArgumentException e) { // expected } } /** * Tests if cookie constructor rejects cookie name containing blanks. */ public void testCookieNameWithBlanks() throws Exception { Header setcookie = new Header("Set-Cookie", "invalid name="); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, setcookie); assertNotNull(parsed); assertEquals(1, parsed.length); } /** * Tests if cookie constructor rejects cookie name starting with $. */ public void testCookieNameStartingWithDollarSign() throws Exception { Header setcookie = new Header("Set-Cookie", "$invalid_name="); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, setcookie); assertNotNull(parsed); assertEquals(1, parsed.length); } /** * Tests if malformatted expires attribute is parsed correctly. */ public void testCookieWithComma() throws Exception { Header header = new Header("Set-Cookie", "name=value; expires=\"Thu, 01-Jan-1970 00:00:00 GMT"); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] cookies = cookiespec.parse("localhost", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException expected) { } } /** * Tests several date formats. */ public void testDateFormats() throws Exception { //comma, dashes checkDate("Thu, 01-Jan-70 00:00:10 GMT"); checkDate("Thu, 01-Jan-2070 00:00:10 GMT"); //no comma, dashes checkDate("Thu 01-Jan-70 00:00:10 GMT"); checkDate("Thu 01-Jan-2070 00:00:10 GMT"); //comma, spaces checkDate("Thu, 01 Jan 70 00:00:10 GMT"); checkDate("Thu, 01 Jan 2070 00:00:10 GMT"); //no comma, spaces checkDate("Thu 01 Jan 70 00:00:10 GMT"); checkDate("Thu 01 Jan 2070 00:00:10 GMT"); //weird stuff checkDate("Wed, 20-Nov-2002 09-38-33 GMT"); try { checkDate("this aint a date"); fail("Date check is bogous"); } catch(Exception e) { /* must fail */ } } private void checkDate(String date) throws Exception { Header header = new Header("Set-Cookie", "custno=12345;Expires='"+date+"';"); HttpParams params = new DefaultHttpParamsFactory().getDefaultParams(); CookieSpec cookiespec = new CookieSpecBase(); cookiespec.setValidDateFormats( (Collection)params.getParameter(HttpMethodParams.DATE_PATTERNS)); cookieParse(cookiespec, "localhost", 80, "/", false, header); } /** * Tests if invalid second domain level cookie gets accepted in the * browser compatibility mode. */ public void testSecondDomainLevelCookie() throws Exception { Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new CookieSpecBase(); cookiespec.validate("sourceforge.net", 80, "/", false, cookie); } public void testSecondDomainLevelCookieMatch1() throws Exception { Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new CookieSpecBase(); assertTrue(cookiespec.match("sourceforge.net", 80, "/", false, cookie)); } public void testSecondDomainLevelCookieMatch2() throws Exception { Cookie cookie = new Cookie("sourceforge.net", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new CookieSpecBase(); assertTrue(cookiespec.match("www.sourceforge.net", 80, "/", false, cookie)); } public void testSecondDomainLevelCookieMatch3() throws Exception { Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new CookieSpecBase(); assertTrue(cookiespec.match("www.sourceforge.net", 80, "/", false, cookie)); } public void testInvalidSecondDomainLevelCookieMatch1() throws Exception { Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new CookieSpecBase(); assertFalse(cookiespec.match("antisourceforge.net", 80, "/", false, cookie)); } public void testInvalidSecondDomainLevelCookieMatch2() throws Exception { Cookie cookie = new Cookie("sourceforge.net", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new CookieSpecBase(); assertFalse(cookiespec.match("antisourceforge.net", 80, "/", false, cookie)); } public void testMatchNullHost() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.match(null, 80, "/", false, cookie); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testMatchBlankHost() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.match(" ", 80, "/", false, cookie); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testMatchInvalidPort() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.match("host", -80, "/", false, cookie); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testMatchNullPath() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.match("host", 80, null, false, cookie); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testMatchBlankPath() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie("host", "name", "value", "/", null, false); assertTrue(cookiespec.match("host", 80, " ", false, cookie)); } public void testMatchNullCookie() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); try { cookiespec.match("host", 80, "/", false, (Cookie)null); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testMatchNullCookieDomain() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(null, "name", "value", "/", null, false); assertFalse(cookiespec.match("host", 80, "/", false, cookie)); } public void testMatchNullCookiePath() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie("host", "name", "value", null, null, false); assertFalse(cookiespec.match("host", 80, "/", false, cookie)); } public void testCookieMatch1() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie("host", "name", "value", "/", null, false); assertTrue(cookiespec.match("host", 80, "/", false, cookie)); } public void testCookieMatch2() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(".whatever.com", "name", "value", "/", null, false); assertTrue(cookiespec.match(".whatever.com", 80, "/", false, cookie)); } public void testCookieMatch3() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(".whatever.com", "name", "value", "/", null, false); assertTrue(cookiespec.match(".really.whatever.com", 80, "/", false, cookie)); } public void testCookieMatch4() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie("host", "name", "value", "/", null, false); assertTrue(cookiespec.match("host", 80, "/foobar", false, cookie)); } public void testCookieMismatch1() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie("host1", "name", "value", "/", null, false); assertFalse(cookiespec.match("host2", 80, "/", false, cookie)); } public void testCookieMismatch2() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(".aaaaaaaaa.com", "name", "value", "/", null, false); assertFalse(cookiespec.match(".bbbbbbbb.com", 80, "/", false, cookie)); } public void testCookieMismatch3() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie("host", "name", "value", "/foobar", null, false); assertFalse(cookiespec.match("host", 80, "/foo", false, cookie)); } public void testCookieMismatch4() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie("host", "name", "value", "/foobar", null, true); assertFalse(cookiespec.match("host", 80, "/foobar/", false, cookie)); } public void testCookieMatch5() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie("host", "name", "value", "/foobar/r", null, false); assertFalse(cookiespec.match("host", 80, "/foobar/", false, cookie)); } public void testCookieMismatch6() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie("host", "name", "value", "/foobar", null, true); assertFalse(cookiespec.match("host", 80, "/foobar", false, cookie)); } public void testMatchNullCookies() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie[] matched = cookiespec.match("host", 80, "/foobar", false, (Cookie[])null); assertNull(matched); } public void testMatchedCookiesOrder() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie[] cookies = { new Cookie("host", "nomatch", "value", "/noway", null, false), new Cookie("host", "name2", "value", "/foobar/yada", null, false), new Cookie("host", "name3", "value", "/foobar", null, false), new Cookie("host", "name1", "value", "/foobar/yada/yada", null, false)}; Cookie[] matched = cookiespec.match("host", 80, "/foobar/yada/yada", false, cookies); assertNotNull(matched); assertEquals(3, matched.length); assertEquals("name1", matched[0].getName()); assertEquals("name2", matched[1].getName()); assertEquals("name3", matched[2].getName()); } public void testInvalidMatchDomain() throws Exception { Cookie cookie = new Cookie("beta.gamma.com", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new CookieSpecBase(); cookiespec.validate("alpha.beta.gamma.com", 80, "/", false, cookie); assertTrue(cookiespec.match("alpha.beta.gamma.com", 80, "/", false, cookie)); } public void testFormatInvalidCookie() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); try { String s = cookiespec.formatCookie(null); fail("IllegalArgumentException nust have been thrown"); } catch (IllegalArgumentException expected) { } } /** * Tests generic cookie formatting. */ public void testGenericCookieFormatting() throws Exception { Header header = new Header("Set-Cookie", "name=value; path=/; domain=.mydomain.com"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header); cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]); String s = cookiespec.formatCookie(cookies[0]); assertEquals("name=value", s); } public void testGenericCookieFormattingAsHeader() throws Exception { Header header = new Header("Set-Cookie", "name=value; path=/; domain=.mydomain.com"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header); cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]); Header cookieheader = cookiespec.formatCookieHeader(cookies[0]); assertEquals("name=value", cookieheader.getValue()); } /** * Tests if null cookie values are handled correctly. */ public void testNullCookieValueFormatting() { Cookie cookie = new Cookie(".whatever.com", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new CookieSpecBase(); String s = cookiespec.formatCookie(cookie); assertEquals("name=", s); } public void testFormatInvalidCookies() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); try { String s = cookiespec.formatCookies(null); fail("IllegalArgumentException nust have been thrown"); } catch (IllegalArgumentException expected) { } } public void testFormatZeroCookies() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); try { String s = cookiespec.formatCookies(new Cookie[] {}); fail("IllegalArgumentException nust have been thrown"); } catch (IllegalArgumentException expected) { } } /** * Tests generic cookie formatting. */ public void testFormatSeveralCookies() throws Exception { Header header = new Header("Set-Cookie", "name1=value1; path=/; domain=.mydomain.com, name2 = value2 ; path=/; domain=.mydomain.com"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header); String s = cookiespec.formatCookies(cookies); assertEquals("name1=value1; name2=value2", s); } public void testFormatOneCookie() throws Exception { Header header = new Header("Set-Cookie", "name1=value1; path=/; domain=.mydomain.com;"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header); String s = cookiespec.formatCookies(cookies); assertEquals("name1=value1", s); } public void testFormatSeveralCookiesAsHeader() throws Exception { Header header = new Header("Set-Cookie", "name1=value1; path=/; domain=.mydomain.com, name2 = value2 ; path=/; domain=.mydomain.com"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header); Header cookieheader = cookiespec.formatCookieHeader(cookies); assertEquals("name1=value1; name2=value2", cookieheader.getValue()); } public void testKeepCloverHappy() throws Exception { MalformedCookieException ex1 = new MalformedCookieException(); MalformedCookieException ex2 = new MalformedCookieException("whatever"); MalformedCookieException ex3 = new MalformedCookieException("whatever", null); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookieIgnoreSpec.java100644 0 0 11136 10661532630 30132 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieIgnoreSpec.java,v 1.5 2004/10/31 14:42:59 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.io.IOException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClientTestBase; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * Test cases for ignore cookie apec * * @author Michael Becke * * @version $Revision: 480424 $ */ public class TestCookieIgnoreSpec extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestCookieIgnoreSpec(final String testName) throws IOException { super(testName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestCookieIgnoreSpec.class); } private class BasicAuthService implements HttpService { public BasicAuthService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion ver = request.getRequestLine().getHttpVersion(); response.setStatusLine(ver, HttpStatus.SC_OK); response.addHeader(new Header("Connection", "close")); response.addHeader(new Header("Set-Cookie", "custno = 12345; comment=test; version=1," + " name=John; version=1; max-age=600; secure; domain=.apache.org")); return true; } } public void testIgnoreCookies() throws Exception { this.server.setHttpService(new BasicAuthService()); GetMethod httpget = new GetMethod("/"); httpget.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); try { this.client.executeMethod(httpget); } finally { httpget.releaseConnection(); } assertEquals("Cookie parsing should have been disabled", 0, this.client.getState().getCookies().length); } public void testKeepCloverHappy() throws Exception { CookieSpec cookiespec = new IgnoreCookiesSpec(); cookiespec.parseAttribute(null, null); cookiespec.parse("host", 80, "/", false, (String)null); cookiespec.parse("host", 80, "/", false, (Header)null); cookiespec.validate("host", 80, "/", false, (Cookie)null); cookiespec.match("host", 80, "/", false, (Cookie)null); cookiespec.match("host", 80, "/", false, (Cookie [])null); cookiespec.domainMatch(null, null); cookiespec.pathMatch(null, null); cookiespec.match("host", 80, "/", false, (Cookie [])null); cookiespec.formatCookie(null); cookiespec.formatCookies(null); cookiespec.formatCookieHeader((Cookie)null); cookiespec.formatCookieHeader((Cookie [])null); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookieNetscapeDraft.java100644 0 0 26700 10661532626 30627 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieNetscapeDraft.java,v 1.2 2004/04/24 23:28:04 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; /** * Test cases for Netscape cookie draft * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class TestCookieNetscapeDraft extends TestCookieBase { // ------------------------------------------------------------ Constructor public TestCookieNetscapeDraft(String name) { super(name); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestCookieNetscapeDraft.class); } public void testParseAttributeInvalidAttrib() throws Exception { CookieSpec cookiespec = new NetscapeDraftSpec(); try { cookiespec.parseAttribute(null, null); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testParseAttributeInvalidCookie() throws Exception { CookieSpec cookiespec = new NetscapeDraftSpec(); try { cookiespec.parseAttribute(new NameValuePair("name", "value"), null); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testParseAttributeInvalidCookieExpires() throws Exception { CookieSpec cookiespec = new NetscapeDraftSpec(); Cookie cookie = new Cookie(); try { cookiespec.parseAttribute(new NameValuePair("expires", null), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } public void testParseWithNullHost() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new NetscapeDraftSpec(); try { Cookie[] parsed = cookieParse(cookiespec, null, 80, "/", false, header); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } } public void testParseWithBlankHost() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new NetscapeDraftSpec(); try { Cookie[] parsed = cookieParse(cookiespec, " ", 80, "/", false, header); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } } public void testParseWithNullPath() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new NetscapeDraftSpec(); try { Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, null, false, header); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } } public void testParseWithBlankPath() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new NetscapeDraftSpec(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, " ", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); assertEquals("/", parsed[0].getPath()); } public void testParseWithNegativePort() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new NetscapeDraftSpec(); try { Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", -80, null, false, header); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } } public void testParseWithInvalidHeader1() throws Exception { CookieSpec cookiespec = new NetscapeDraftSpec(); try { Cookie[] parsed = cookiespec.parse("127.0.0.1", 80, "/foo", false, (String)null); fail("IllegalArgumentException should have been thrown."); } catch (IllegalArgumentException e) { // expected } } public void testParseAbsPath() throws Exception { Header header = new Header("Set-Cookie", "name1=value1;Path=/path/"); CookieSpec cookiespec = new NetscapeDraftSpec(); Cookie[] parsed = cookieParse(cookiespec, "host", 80, "/path/", true, header); assertEquals("Found 1 cookies.",1,parsed.length); assertEquals("Name","name1",parsed[0].getName()); assertEquals("Value","value1",parsed[0].getValue()); assertEquals("Domain","host",parsed[0].getDomain()); assertEquals("Path","/path/",parsed[0].getPath()); } public void testParseAbsPath2() throws Exception { Header header = new Header("Set-Cookie", "name1=value1;Path=/"); CookieSpec cookiespec = new NetscapeDraftSpec(); Cookie[] parsed = cookieParse(cookiespec, "host", 80, "/", true, header); assertEquals("Found 1 cookies.",1,parsed.length); assertEquals("Name","name1",parsed[0].getName()); assertEquals("Value","value1",parsed[0].getValue()); assertEquals("Domain","host",parsed[0].getDomain()); assertEquals("Path","/",parsed[0].getPath()); } public void testParseRelativePath() throws Exception { Header header = new Header("Set-Cookie", "name1=value1;Path=whatever"); CookieSpec cookiespec = new NetscapeDraftSpec(); Cookie[] parsed = cookieParse(cookiespec, "host", 80, "whatever", true, header); assertEquals("Found 1 cookies.",1,parsed.length); assertEquals("Name","name1",parsed[0].getName()); assertEquals("Value","value1",parsed[0].getValue()); assertEquals("Domain","host",parsed[0].getDomain()); assertEquals("Path","whatever",parsed[0].getPath()); } public void testParseWithIllegalNetscapeDomain1() throws Exception { Header header = new Header("Set-Cookie","cookie-name=cookie-value; domain=.com"); CookieSpec cookiespec = new NetscapeDraftSpec(); try { Cookie[] parsed = cookieParse(cookiespec, "a.com", 80, "/", false, header); fail("HttpException exception should have been thrown"); } catch (HttpException e) { // expected } } public void testParseWithWrongNetscapeDomain2() throws Exception { Header header = new Header("Set-Cookie","cookie-name=cookie-value; domain=.y.z"); CookieSpec cookiespec = new NetscapeDraftSpec(); try { Cookie[] parsed = cookieParse(cookiespec, "x.y.z", 80, "/", false, header); fail("HttpException exception should have been thrown"); } catch (HttpException e) { // expected } } /** * Tests Netscape specific cookie formatting. */ public void testNetscapeCookieFormatting() throws Exception { Header header = new Header( "Set-Cookie", "name=value; path=/; domain=.mydomain.com"); CookieSpec cookiespec = new NetscapeDraftSpec(); Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header ); cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]); String s = cookiespec.formatCookie(cookies[0]); assertEquals("name=value", s); } /** * Tests Netscape specific expire attribute parsing. */ public void testNetscapeCookieExpireAttribute() throws Exception { CookieSpec cookiespec = new NetscapeDraftSpec(); Header header = new Header("Set-Cookie", "name=value; path=/; domain=.mydomain.com; expires=Thu, 01-Jan-2070 00:00:10 GMT; comment=no_comment"); Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header ); cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]); header = new Header("Set-Cookie", "name=value; path=/; domain=.mydomain.com; expires=Thu 01-Jan-2070 00:00:10 GMT; comment=no_comment"); try { cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header ); cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } /** * Tests Netscape specific expire attribute without a time zone. */ public void testNetscapeCookieExpireAttributeNoTimeZone() throws Exception { CookieSpec cookiespec = new NetscapeDraftSpec(); Header header = new Header("Set-Cookie", "name=value; expires=Thu, 01-Jan-2006 00:00:00 "); try { cookiespec.parse("myhost.mydomain.com", 80, "/", false, header ); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } /** * Tests if cookie values with embedded comma are handled correctly. */ public void testCookieWithComma() throws Exception { Header header = new Header("Set-Cookie", "a=b,c"); CookieSpec cookiespec = new NetscapeDraftSpec(); Cookie[] cookies = cookiespec.parse("localhost", 80, "/", false, header); assertEquals("number of cookies", 1, cookies.length); assertEquals("a", cookies[0].getName()); assertEquals("b,c", cookies[0].getValue()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookiePathComparator.java100644 0 0 10503 10661532626 31022 0ustar 0 0 /* * $HeaderURL$ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.Comparator; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.Cookie; /** * Test cases for {@link CookiePathComparator}. */ public class TestCookiePathComparator extends TestCookieBase { // ------------------------------------------------------------ Constructor public TestCookiePathComparator(String name) { super(name); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestCookiePathComparator.class); } public void testUnequality1() { Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/a/b/", null, false); Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/a/", null, false); Comparator comparator = new CookiePathComparator(); assertTrue(comparator.compare(cookie1, cookie2) < 0); assertTrue(comparator.compare(cookie2, cookie1) > 0); } public void testUnequality2() { Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/a/b", null, false); Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/a", null, false); Comparator comparator = new CookiePathComparator(); assertTrue(comparator.compare(cookie1, cookie2) < 0); assertTrue(comparator.compare(cookie2, cookie1) > 0); } public void testEquality1() { Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/a", null, false); Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/a", null, false); Comparator comparator = new CookiePathComparator(); assertTrue(comparator.compare(cookie1, cookie2) == 0); assertTrue(comparator.compare(cookie2, cookie1) == 0); } public void testEquality2() { Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/a/", null, false); Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/a", null, false); Comparator comparator = new CookiePathComparator(); assertTrue(comparator.compare(cookie1, cookie2) == 0); assertTrue(comparator.compare(cookie2, cookie1) == 0); } public void testEquality3() { Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", null, null, false); Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/", null, false); Comparator comparator = new CookiePathComparator(); assertTrue(comparator.compare(cookie1, cookie2) == 0); assertTrue(comparator.compare(cookie2, cookie1) == 0); } public void testEquality4() { Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/this", null, false); Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/that", null, false); Comparator comparator = new CookiePathComparator(); assertTrue(comparator.compare(cookie1, cookie2) == 0); assertTrue(comparator.compare(cookie2, cookie1) == 0); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookiePolicy.java100644 0 0 7014 10661532626 27320 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookiePolicy.java,v 1.2 2004/09/14 20:11:32 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import junit.framework.Test; import junit.framework.TestSuite; /** * Test cases for Cookie Policy * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class TestCookiePolicy extends TestCookieBase { // ------------------------------------------------------------ Constructor public TestCookiePolicy(String name) { super(name); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestCookiePolicy.class); } public void testRegisterNullPolicyId() { try { CookiePolicy.registerCookieSpec(null, null); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testRegisterNullPolicy() { try { CookiePolicy.registerCookieSpec("whatever", null); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testUnregisterNullPolicy() { try { CookiePolicy.unregisterCookieSpec(null); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testGetPolicyNullId() { try { CookiePolicy.getCookieSpec(null); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testRegisterUnregister() { CookiePolicy.registerCookieSpec("whatever", CookieSpecBase.class); CookiePolicy.unregisterCookieSpec("whatever"); try { CookiePolicy.getCookieSpec("whatever"); fail("IllegalStateException must have been thrown"); } catch (IllegalStateException expected) { } } public void testGetDefaultPolicy() { assertNotNull(CookiePolicy.getDefaultSpec()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookieRFC2109Spec.java100644 0 0 37650 10661532626 27653 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestCookieRFC2109Spec.java,v 1.3 2004/06/05 16:49:20 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.NameValuePair; /** * Test cases for RFC2109 cookie spec * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class TestCookieRFC2109Spec extends TestCookieBase { // ------------------------------------------------------------ Constructor public TestCookieRFC2109Spec(String name) { super(name); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestCookieRFC2109Spec.class); } public void testParseAttributeInvalidAttrib() throws Exception { CookieSpec cookiespec = new RFC2109Spec(); try { cookiespec.parseAttribute(null, null); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testParseAttributeInvalidCookie() throws Exception { CookieSpec cookiespec = new RFC2109Spec(); try { cookiespec.parseAttribute(new NameValuePair("name", "value"), null); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } } public void testParseAttributeNullPath() throws Exception { CookieSpec cookiespec = new RFC2109Spec(); try { Cookie cookie = new Cookie(); cookiespec.parseAttribute(new NameValuePair("path", null), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } public void testParseAttributeBlankPath() throws Exception { CookieSpec cookiespec = new RFC2109Spec(); try { Cookie cookie = new Cookie(); cookiespec.parseAttribute(new NameValuePair("path", " "), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } public void testParseAttributeNullVersion() throws Exception { CookieSpec cookiespec = new RFC2109Spec(); try { Cookie cookie = new Cookie(); cookiespec.parseAttribute(new NameValuePair("version", null), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } public void testParseAttributeInvalidVersion() throws Exception { CookieSpec cookiespec = new RFC2109Spec(); try { Cookie cookie = new Cookie(); cookiespec.parseAttribute(new NameValuePair("version", "nonsense"), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } } public void testParseVersion() throws Exception { Header header = new Header("Set-Cookie","cookie-name=cookie-value; version=1"); CookieSpec cookiespec = new RFC2109Spec(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value","cookie-value",parsed[0].getValue()); assertEquals("Version",1,parsed[0].getVersion()); } /** * Test domain equals host */ public void testParseDomainEqualsHost() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=www.b.com; version=1"); CookieSpec cookiespec = new RFC2109Spec(); Cookie[] parsed = cookieParse(cookiespec, "www.b.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); assertEquals("www.b.com", parsed[0].getDomain()); } /** * Domain does not start with a dot */ public void testParseWithIllegalDomain1() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=a.b.com; version=1"); CookieSpec cookiespec = new RFC2109Spec(); try { Cookie[] parsed = cookieParse(cookiespec, "www.a.b.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException e) { // expected } } /** * Domain must have alt least one embedded dot */ public void testParseWithIllegalDomain2() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=.com; version=1"); CookieSpec cookiespec = new RFC2109Spec(); try { Cookie[] parsed = cookieParse(cookiespec, "b.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException e) { // expected } } /** * Domain must have alt least one embedded dot */ public void testParseWithIllegalDomain3() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=.com.; version=1"); CookieSpec cookiespec = new RFC2109Spec(); try { Cookie[] parsed = cookieParse(cookiespec, "b.com", 80, "/", false, header); fail("HttpException exception should have been thrown"); } catch (MalformedCookieException e) { // expected } } /** * Host minus domain may not contain any dots */ public void testParseWithIllegalDomain4() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=.c.com; version=1"); CookieSpec cookiespec = new RFC2109Spec(); try { Cookie[] parsed = cookieParse(cookiespec, "a.b.c.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException e) { // expected } } /** * Tests if that invalid second domain level cookie gets * rejected in the strict mode, but gets accepted in the * browser compatibility mode. */ public void testSecondDomainLevelCookie() throws Exception { Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new RFC2109Spec(); try { cookiespec.validate("sourceforge.net", 80, "/", false, cookie); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException e) { // Expected } } public void testSecondDomainLevelCookieMatch() throws Exception { Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new RFC2109Spec(); assertFalse(cookiespec.match("sourceforge.net", 80, "/", false, cookie)); } public void testParseWithWrongPath() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/not/just/root"); CookieSpec cookiespec = new RFC2109Spec(); try { Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header); fail("HttpException exception should have been thrown"); } catch (MalformedCookieException e) { // expected } } /** * Tests if cookie constructor rejects cookie name containing blanks. */ public void testCookieNameWithBlanks() throws Exception { Header setcookie = new Header("Set-Cookie", "invalid name="); CookieSpec cookiespec = new RFC2109Spec(); try { Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, setcookie); fail("MalformedCookieException exception should have been thrown"); } catch (MalformedCookieException e) { // expected } } /** * Tests if cookie constructor rejects cookie name starting with $. */ public void testCookieNameStartingWithDollarSign() throws Exception { Header setcookie = new Header("Set-Cookie", "$invalid_name="); CookieSpec cookiespec = new RFC2109Spec(); try { Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/", false, setcookie); fail("MalformedCookieException exception should have been thrown"); } catch (MalformedCookieException e) { // expected } } /** * Tests if default cookie validator rejects cookies originating from a host without domain * where domain attribute does not match the host of origin */ public void testInvalidDomainWithSimpleHostName() throws Exception { CookieSpec cookiespec = new RFC2109Spec(); Header header = new Header("Set-Cookie", "name=\"value\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\""); Cookie[]cookies = cookiespec.parse("host", 80, "/", false, header ); try { cookiespec.validate("host", 80, "/", false, cookies[0]); fail("MalformedCookieException must have thrown"); } catch(MalformedCookieException expected) { } header = new Header("Set-Cookie", "name=\"value\"; version=\"1\"; path=\"/\"; domain=\"host1\""); cookies = cookiespec.parse("host2", 80, "/", false, header ); try { cookiespec.validate("host2", 80, "/", false, cookies[0]); fail("MalformedCookieException must have thrown"); } catch(MalformedCookieException expected) { } } /** * Tests if cookie values with embedded comma are handled correctly. */ public void testCookieWithComma() throws Exception { Header header = new Header("Set-Cookie", "a=b,c"); CookieSpec cookiespec = new RFC2109Spec(); Cookie[] cookies = cookiespec.parse("localhost", 80, "/", false, header); assertEquals("number of cookies", 2, cookies.length); assertEquals("a", cookies[0].getName()); assertEquals("b", cookies[0].getValue()); assertEquals("c", cookies[1].getName()); assertEquals(null, cookies[1].getValue()); } public void testFormatInvalidCookies() throws Exception { CookieSpec cookiespec = new RFC2109Spec(); try { String s = cookiespec.formatCookie(null); fail("IllegalArgumentException nust have been thrown"); } catch (IllegalArgumentException expected) { } } /** * Tests RFC 2109 compiant cookie formatting. */ public void testRFC2109CookieFormatting() throws Exception { CookieSpec cookiespec = new RFC2109Spec(); Header header = new Header("Set-Cookie", "name=\"value\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\""); Cookie[] cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header ); cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]); String s1 = cookiespec.formatCookie(cookies[0]); assertEquals(s1, "$Version=\"1\"; name=\"value\"; $Path=\"/\"; $Domain=\".mydomain.com\""); header = new Header( "Set-Cookie", "name=value; path=/; domain=.mydomain.com"); cookies = cookiespec.parse("myhost.mydomain.com", 80, "/", false, header ); cookiespec.validate("myhost.mydomain.com", 80, "/", false, cookies[0]); String s2 = cookiespec.formatCookie(cookies[0]); assertEquals(s2, "$Version=0; name=value; $Path=/; $Domain=.mydomain.com"); } public void testRFC2109CookiesFormatting() throws Exception { CookieSpec cookiespec = new RFC2109Spec(); Header header = new Header("Set-Cookie", "name1=value1; path=/; domain=.mydomain.com, " + "name2=\"value2\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\""); Cookie[] cookies = cookieParse(cookiespec, "myhost.mydomain.com", 80, "/", false, header); assertNotNull(cookies); assertEquals(2, cookies.length); String s1 = cookiespec.formatCookies(cookies); assertEquals(s1, "$Version=0; name1=value1; $Path=/; $Domain=.mydomain.com; " + "name2=value2; $Path=/; $Domain=.mydomain.com"); header = new Header("Set-Cookie", "name1=value1; version=1; path=/; domain=.mydomain.com, " + "name2=\"value2\"; version=\"1\"; path=\"/\"; domain=\".mydomain.com\""); cookies = cookieParse(cookiespec, "myhost.mydomain.com", 80, "/", false, header); assertNotNull(cookies); assertEquals(2, cookies.length); String s2 = cookiespec.formatCookies(cookies); assertEquals(s2, "$Version=\"1\"; name1=\"value1\"; $Path=\"/\"; $Domain=\".mydomain.com\"; " + "name2=\"value2\"; $Path=\"/\"; $Domain=\".mydomain.com\""); } /** * Tests if null cookie values are handled correctly. */ public void testNullCookieValueFormatting() { Cookie cookie = new Cookie(".whatever.com", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new RFC2109Spec(); String s = cookiespec.formatCookie(cookie); assertEquals("$Version=0; name=; $Path=/; $Domain=.whatever.com", s); cookie.setVersion(1); s = cookiespec.formatCookie(cookie); assertEquals("$Version=\"1\"; name=\"\"; $Path=\"/\"; $Domain=\".whatever.com\"", s); } public void testCookieNullDomainNullPathFormatting() { Cookie cookie = new Cookie(null, "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new RFC2109Spec(); String s = cookiespec.formatCookie(cookie); assertEquals("$Version=0; name=; $Path=/", s); cookie.setDomainAttributeSpecified(false); cookie.setPathAttributeSpecified(false); s = cookiespec.formatCookie(cookie); assertEquals("$Version=0; name=", s); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookieRFC2965Spec.java100644 0 0 110371 10661532626 27675 0ustar 0 0 /* * $Header: $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import java.util.Date; /** * Test cases for RFC2965 cookie spec * * @author jain.samit@gmail.com (Samit Jain) */ public class TestCookieRFC2965Spec extends TestCookieBase { // ------------------------------------------------------------ Constructor public TestCookieRFC2965Spec(String name) { super(name); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestCookieRFC2965Spec.class); } // ------------------------------------------------------- Test Cookie Parsing /** * Test parse with invalid params. */ public void testParseInvalidParams() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); try { // invalid header cookiespec.parse("www.domain.com", 80, "/", false, (Header) null /* header */); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) {} Header header = new Header("Set-Cookie2", "name=value;Version=1"); try { // invalid request host cookiespec.parse(null /* host */, 80, "/", false, header); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) {} try { // invalid request port cookiespec.parse("www.domain.com", -32 /* port */, "/", false, header); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) {} try { // invalid request path cookiespec.parse("www.domain.com", 80, null /* path */, false, header); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) {} } /** * Test parsing cookie "Path" attribute. */ public void testParsePath() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Path=/;Version=1;Path="); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); // only the first occurence of path attribute is considered, others ignored Cookie2 cookie = (Cookie2) parsed[0]; assertEquals("/", cookie.getPath()); assertTrue(cookie.isPathAttributeSpecified()); } public void testParsePathDefault() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // Path is OPTIONAL, defaults to the request path Header header = new Header("Set-Cookie2", "name=value;Version=1"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/path" /* request path */, false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertEquals("/path", cookie.getPath()); assertFalse(cookie.isPathAttributeSpecified()); } public void testParseNullPath() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Path=;Version=1"); try { cookiespec.parse("www.domain.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } public void testParseBlankPath() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Path=\" \";Version=1"); try { cookiespec.parse("www.domain.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } /** * Test parsing cookie "Domain" attribute. */ public void testParseDomain() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Domain=.domain.com;Version=1;Domain="); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); // only the first occurence of domain attribute is considered, others ignored Cookie2 cookie = (Cookie2) parsed[0]; assertEquals(".domain.com", cookie.getDomain()); assertTrue(cookie.isDomainAttributeSpecified()); // should put a leading dot if there is no dot in front of domain header = new Header("Set-Cookie2", "name=value;Domain=domain.com;Version=1"); parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); cookie = (Cookie2) parsed[0]; assertEquals(".domain.com", cookie.getDomain()); } public void testParseDomainDefault() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // Domain is OPTIONAL, defaults to the request host Header header = new Header("Set-Cookie2", "name=value;Version=1"); Cookie[] parsed = cookiespec.parse("www.domain.com" /* request host */, 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertEquals("www.domain.com", cookie.getDomain()); assertFalse(cookie.isDomainAttributeSpecified()); } public void testParseNullDomain() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // domain cannot be null Header header = new Header("Set-Cookie2", "name=value;Domain=;Version=1"); try { cookiespec.parse("www.domain.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } public void testParseBlankDomain() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Domain=\" \";Version=1"); try { cookiespec.parse("www.domain.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } /** * Test parsing cookie "Port" attribute. */ public void testParsePort() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Port=\"80,800,8000\";Version=1;Port=nonsense"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); // only the first occurence of port attribute is considered, others ignored Cookie2 cookie = (Cookie2) parsed[0]; int[] ports = cookie.getPorts(); assertNotNull(ports); assertEquals(3, ports.length); assertEquals(80, ports[0]); assertEquals(800, ports[1]); assertEquals(8000, ports[2]); assertTrue(cookie.isPortAttributeSpecified()); } public void testParsePortDefault() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // Port is OPTIONAL, cookie can be accepted from any port Header header = new Header("Set-Cookie2", "name=value;Version=1"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertFalse(cookie.isPortAttributeSpecified()); } public void testParseNullPort() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // null port defaults to request port Header header = new Header("Set-Cookie2", "name=value;Port=;Version=1"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80 /* request port */, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; int[] ports = cookie.getPorts(); assertNotNull(ports); assertEquals(1, ports.length); assertEquals(80, ports[0]); assertTrue(cookie.isPortAttributeSpecified() && cookie.isPortAttributeBlank()); } public void testParseBlankPort() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // blank port defaults to request port Header header = new Header("Set-Cookie2", "name=value;Port=\" \";Version=1"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80 /* request port */, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; int[] ports = cookie.getPorts(); assertNotNull(ports); assertEquals(1, ports.length); assertEquals(80, ports[0]); assertTrue(cookie.isPortAttributeSpecified() && cookie.isPortAttributeBlank()); } public void testParseInvalidPort() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Port=nonsense;Version=1"); try { cookiespec.parse("www.domain.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } public void testParseNegativePort() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Port=\"80,-800,8000\";Version=1"); try { cookiespec.parse("www.domain.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } /** * test parsing cookie name/value. */ public void testParseNameValue() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Version=1;"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertEquals("name", cookie.getName()); assertEquals("value", cookie.getValue()); } /** * test parsing cookie "Version" attribute. */ public void testParseVersion() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Version=1;"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertEquals(1, cookie.getVersion()); assertTrue(cookie.isVersionAttributeSpecified()); } public void testParseNullVersion() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // version cannot ne null Header header = new Header("Set-Cookie2", "name=value;Version=;"); try { cookiespec.parse("www.domain.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } public void testParseNegativeVersion() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Version=-1;"); try { cookiespec.parse("www.domain.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } /** * test parsing cookie "Max-age" attribute. */ public void testParseMaxage() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Max-age=3600;Version=1;Max-age=nonsense"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); // only the first occurence of max-age attribute is considered, others ignored Cookie2 cookie = (Cookie2) parsed[0]; assertFalse(cookie.isExpired()); } public void testParseMaxageDefault() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // Max-age is OPTIONAL, defaults to session cookie Header header = new Header("Set-Cookie2", "name=value;Version=1"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertFalse(cookie.isPersistent()); } public void testParseNullMaxage() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Max-age=;Version=1"); try { cookiespec.parse("www.domain.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } public void testParseNegativeMaxage() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Max-age=-3600;Version=1;"); try { cookiespec.parse("www.domain.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException ex) { // expected } } /** * test parsing "Secure" attribute. */ public void testParseSecure() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Secure;Version=1"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertTrue(cookie.getSecure()); } /** * test parsing "Discard" attribute. */ public void testParseDiscard() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Discard;Max-age=36000;Version=1"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; // discard overrides max-age assertFalse(cookie.isPersistent()); // Discard is OPTIONAL, default behavior is dictated by max-age header = new Header("Set-Cookie2", "name=value;Max-age=36000;Version=1"); parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); cookie = (Cookie2) parsed[0]; assertTrue(cookie.isPersistent()); } /** * test parsing "Comment", "CommentURL" and * "Secure" attributes. */ public void testParseOtherAttributes() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Comment=\"good cookie\";" + "CommentURL=\"www.domain.com/goodcookie/\";Secure;Version=1"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertEquals("good cookie", cookie.getComment()); assertEquals("www.domain.com/goodcookie/", cookie.getCommentURL()); assertTrue(cookie.getSecure()); // Comment, CommentURL, Secure are OPTIONAL header = new Header("Set-Cookie2", "name=value;Version=1"); parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); cookie = (Cookie2) parsed[0]; assertFalse(cookie.getSecure()); } /** * Test parsing header with 2 cookies (separated by comma) */ public void testCookiesWithComma() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "a=b,c"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(2, parsed.length); assertEquals("a", parsed[0].getName()); assertEquals("b", parsed[0].getValue()); assertEquals("c", parsed[1].getName()); assertEquals(null, parsed[1].getValue()); } // ------------------------------------------------------- Test Cookie Validation /** * Test Domain validation when domain is not specified * in Set-Cookie2 header. */ public void testValidateNoDomain() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Version=1"); Cookie[] parsed = cookieParse(cookiespec, "www.domain.com" /* request host */, 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; // cookie domain must string match request host assertEquals("www.domain.com", cookie.getDomain()); } /** * Test Domain validation. Cookie domain attribute must have a * leading dot. */ public void testValidateDomainLeadingDot() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Domain=domain.com;Version=1"); Cookie[] parsed = cookieParse(cookiespec, "www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertEquals(".domain.com", cookie.getDomain()); } /** * Test Domain validation. Domain must have atleast one embedded dot. */ public void testValidateDomainEmbeddedDot() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value; domain=.com; version=1"); try { cookieParse(cookiespec, "b.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException expected) {} header = new Header("Set-Cookie2", "name=value;Domain=domain.com;Version=1"); Cookie[] parsed = cookieParse(cookiespec, "www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); } /** * Test local Domain validation. Simple host names * (without any dots) are valid only when cookie domain is specified * as ".local". */ public void testValidateDomainLocal() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // when domain is specified as .local, simple host names are valid Header header = new Header("Set-Cookie2", "name=value; domain=.local; version=1"); Cookie[] parsed = cookieParse(cookiespec, "simplehost" /* request host */, 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertEquals(".local", cookie.getDomain()); // when domain is NOT specified as .local, simple host names are invalid header = new Header("Set-Cookie2", "name=value; domain=domain.com; version=1"); try { // since domain is not .local, this must fail parsed = cookieParse(cookiespec, "simplehost" /* request host */, 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException expected) {} } /** * Test Domain validation. Effective host name * must domain-match domain attribute. */ public void testValidateDomainEffectiveHost() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // cookie domain does not domain-match request host Header header = new Header("Set-Cookie2", "name=value; domain=.domain.com; version=1"); try { cookieParse(cookiespec, "www.domain.org" /* request host */, 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException expected) {} // cookie domain domain-matches request host header = new Header("Set-Cookie2", "name=value; domain=.domain.com; version=1"); Cookie[] parsed = cookieParse(cookiespec, "www.domain.com" /* request host */, 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); } /** * Test local Domain validation. * Effective host name minus domain must not contain any dots. */ public void testValidateDomainIllegal() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value; domain=.domain.com; version=1"); try { cookieParse(cookiespec, "a.b.domain.com" /* request host */, 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException expected) {} } /** * Test cookie Path validation. Cookie path attribute must path-match * request path. */ public void testValidatePath() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;path=/path;version=1"); try { cookieParse(cookiespec, "www.domain.com", 80, "/" /* request path */, false, header); fail("MalformedCookieException exception should have been thrown"); } catch (MalformedCookieException expected) {} // path-matching is case-sensitive header = new Header("Set-Cookie2", "name=value;path=/Path;version=1"); try { cookieParse(cookiespec, "www.domain.com", 80, "/path" /* request path */, false, header); fail("MalformedCookieException exception should have been thrown"); } catch (MalformedCookieException expected) {} header = new Header("Set-Cookie2", "name=value;path=/path;version=1"); Cookie[] parsed = cookieParse(cookiespec, "www.domain.com", 80, "/path/path1" /* request path */, false, header); assertNotNull(parsed); assertEquals(1, parsed.length); assertEquals("/path", parsed[0].getPath()); } /** * Test cookie name validation. */ public void testValidateCookieName() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // cookie name must not contain blanks Header header = new Header("Set-Cookie2", "invalid name=value; version=1"); try { cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header); fail("MalformedCookieException exception should have been thrown"); } catch (MalformedCookieException expected) {} // cookie name must not start with '$'. header = new Header("Set-Cookie2", "$invalid_name=value; version=1"); try { cookieParse(cookiespec, "127.0.0.1", 80, "/", false, header); fail("MalformedCookieException exception should have been thrown"); } catch (MalformedCookieException expected) {} // valid name header = new Header("Set-Cookie2", "name=value; version=1"); Cookie[] parsed = cookieParse(cookiespec, "www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertEquals("name", cookie.getName()); assertEquals("value", cookie.getValue()); } /** * Test cookie Port validation. Request port must be in the * port attribute list. */ public void testValidatePort() throws Exception { Header header = new Header("Set-Cookie2", "name=value; Port=\"80,800\"; version=1"); CookieSpec cookiespec = new RFC2965Spec(); try { cookieParse(cookiespec, "www.domain.com", 8000 /* request port */, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException e) {} // valid port list Cookie[] parsed = cookieParse(cookiespec, "www.domain.com", 80 /* request port */, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; int[] ports = cookie.getPorts(); assertNotNull(ports); assertEquals(2, ports.length); assertEquals(80, ports[0]); assertEquals(800, ports[1]); } /** * Test cookie Version validation. */ public void testValidateVersion() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // version attribute is REQUIRED Header header = new Header("Set-Cookie2", "name=value"); try { cookieParse(cookiespec, "www.domain.com", 8000, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException e) {} } // ------------------------------------------------------- Test Cookie Matching /** * test cookie Path matching. Cookie path attribute must path-match * path of the request URI. */ public void testMatchPath() throws Exception { Cookie2 cookie = new Cookie2(".domain.com", "name", "value", "/path" /* path */, null, false, new int[] {80}); CookieSpec cookiespec = new RFC2965Spec(); assertFalse(cookiespec.match("www.domain.com", 80, "/" /* request path */, false, cookie)); assertTrue(cookiespec.match("www.domain.com", 80, "/path/path1" /* request path */, false, cookie)); } /** * test cookie Domain matching. */ public void testMatchDomain() throws Exception { Cookie2 cookie = new Cookie2(".domain.com" /* domain */, "name", "value", "/", null, false, new int[] {80}); CookieSpec cookiespec = new RFC2965Spec(); // effective host name minus domain must not contain any dots assertFalse(cookiespec.match("a.b.domain.com" /* request host */, 80, "/", false, cookie)); // The effective host name MUST domain-match the Domain // attribute of the cookie. assertFalse(cookiespec.match("www.domain.org" /* request host */, 80, "/", false, cookie)); assertTrue(cookiespec.match("www.domain.com" /* request host */, 80, "/", false, cookie)); } /** * test cookie local Domain matching. */ public void testMatchDomainLocal() throws Exception { Cookie2 cookie = new Cookie2(".local" /* domain */, "name", "value", "/", null, false, new int[] {80}); CookieSpec cookiespec = new RFC2965Spec(); assertTrue(cookiespec.match("host" /* request host */, 80, "/", false, cookie)); assertFalse(cookiespec.match("host.com" /* request host */, 80, "/", false, cookie)); } /** * test cookie Port matching. */ public void testMatchPort() throws Exception { // cookie can be sent to any port if port attribute not specified Cookie2 cookie = new Cookie2(".domain.com", "name", "value", "/", null, false, null /* ports */); CookieSpec cookiespec = new RFC2965Spec(); cookie.setPortAttributeSpecified(false); assertTrue(cookiespec.match("www.domain.com", 8080 /* request port */, "/", false, cookie)); assertTrue(cookiespec.match("www.domain.com", 323 /* request port */, "/", false, cookie)); // otherwise, request port must be in cookie's port list cookie = new Cookie2(".domain.com", "name", "value", "/", null, false, new int[] {80, 8080} /* ports */); cookie.setPortAttributeSpecified(true); assertFalse(cookiespec.match("www.domain.com", 434 /* request port */, "/", false, cookie)); assertTrue(cookiespec.match("www.domain.com", 8080 /* request port */, "/", false, cookie)); } /** * test cookie expiration. */ public void testCookieExpiration() throws Exception { Date afterOneHour = new Date(System.currentTimeMillis() + 3600 * 1000L); Cookie2 cookie = new Cookie2(".domain.com", "name", "value", "/", afterOneHour /* expiry */, false, null); CookieSpec cookiespec = new RFC2965Spec(); assertTrue(cookiespec.match("www.domain.com", 80, "/", false, cookie)); Date beforeOneHour = new Date(System.currentTimeMillis() - 3600 * 1000L); cookie = new Cookie2(".domain.com", "name", "value", "/", beforeOneHour /* expiry */, false, null); assertFalse(cookiespec.match("www.domain.com", 80, "/", false, cookie)); // discard attributes overrides cookie age, makes it a session cookie. cookie.setDiscard(true); assertFalse(cookie.isPersistent()); assertTrue(cookiespec.match("www.domain.com", 80, "/", false, cookie)); } /** * test cookie Secure attribute. */ public void testCookieSecure() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); // secure cookie can only be sent over a secure connection Cookie2 cookie = new Cookie2(".domain.com", "name", "value", "/", null, true /* secure */, null); assertFalse(cookiespec.match("www.domain.com", 80, "/", false /* request secure */, cookie)); assertTrue(cookiespec.match("www.domain.com", 80, "/", true /* request secure */, cookie)); } // ------------------------------------------------------- Test Cookie Formatting public void testFormatInvalidCookie() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); try { cookiespec.formatCookie(null); fail("IllegalArgumentException nust have been thrown"); } catch (IllegalArgumentException expected) {} } /** * Tests RFC 2965 compliant cookie formatting. */ public void testRFC2965CookieFormatting() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Cookie2 cookie1 = new Cookie2(".domain.com", "name1", "value", "/", null, false, new int[] {80,8080}); cookie1.setVersion(1); // domain, path, port specified cookie1.setDomainAttributeSpecified(true); cookie1.setPathAttributeSpecified(true); cookie1.setPortAttributeSpecified(true); assertEquals("$Version=\"1\"; name1=\"value\"; $Domain=\".domain.com\"; $Path=\"/\"; $Port=\"80,8080\"", cookiespec.formatCookie(cookie1)); Cookie2 cookie2 = new Cookie2(".domain.com", "name2", "value", "/a/", null, false, new int[] {80,8080}); cookie2.setVersion(2); // domain, path specified but port unspecified cookie2.setDomainAttributeSpecified(true); cookie2.setPathAttributeSpecified(true); cookie2.setPortAttributeSpecified(false); assertEquals("$Version=\"2\"; name2=\"value\"; $Domain=\".domain.com\"; $Path=\"/a/\"", cookiespec.formatCookie(cookie2)); Cookie2 cookie3 = new Cookie2(".domain.com", "name3", "value", "/a/b/", null, false, new int[] {80,8080}); cookie3.setVersion(1); // path specified, port specified but blank, domain unspecified cookie3.setDomainAttributeSpecified(false); cookie3.setPathAttributeSpecified(true); cookie3.setPortAttributeSpecified(true); cookie3.setPortAttributeBlank(true); assertEquals("$Version=\"1\"; name3=\"value\"; $Path=\"/a/b/\"; $Port=\"\"", cookiespec.formatCookie(cookie3)); assertEquals("$Version=\"2\"; " + "name3=\"value\"; $Path=\"/a/b/\"; $Port=\"\"; " + "name2=\"value\"; $Domain=\".domain.com\"; $Path=\"/a/\"; " + "name1=\"value\"; $Domain=\".domain.com\"; $Path=\"/\"; $Port=\"80,8080\"", cookiespec.formatCookies(new Cookie[] {cookie3, cookie2, cookie1})); } /** * Tests RFC 2965 compliant cookies formatting. */ public void testRFC2965CookiesFormatting() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Cookie2 cookie1 = new Cookie2(".domain.com", "name1", "value1", "/", null, false, new int[] {80,8080}); cookie1.setVersion(1); // domain, path, port specified cookie1.setDomainAttributeSpecified(true); cookie1.setPathAttributeSpecified(true); cookie1.setPortAttributeSpecified(true); Cookie2 cookie2 = new Cookie2(".domain.com", "name2", null, "/", null, false, null); cookie2.setVersion(1); // value null, domain, path, port specified cookie2.setDomainAttributeSpecified(true); cookie2.setPathAttributeSpecified(true); cookie2.setPortAttributeSpecified(false); Cookie[] cookies = new Cookie[] {cookie1, cookie2}; assertEquals("$Version=\"1\"; name1=\"value1\"; $Domain=\".domain.com\"; $Path=\"/\"; $Port=\"80,8080\"; " + "name2=\"\"; $Domain=\".domain.com\"; $Path=\"/\"", cookiespec.formatCookies(cookies)); } // ------------------------------------------------------- Backward compatibility tests /** * Test backward compatibility with Set-Cookie header. */ public void testCompatibilityWithSetCookie() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie", "name=value; domain=.domain.com; version=1"); Cookie[] parsed = cookieParse(cookiespec, "www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); assertEquals("name", parsed[0].getName()); assertEquals("value", parsed[0].getValue()); assertEquals(".domain.com", parsed[0].getDomain()); assertEquals("/", parsed[0].getPath()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestCookieVersionSupport.java100644 0 0 21300 10661532626 31115 0ustar 0 0 /* * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/test/org/apache/commons/httpclient/cookie/TestCookieVersionSupport.java $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient.cookie; import java.io.IOException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClientTestBase; import org.apache.commons.httpclient.HttpState; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * Cookie version support tests. * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class TestCookieVersionSupport extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestCookieVersionSupport(final String testName) throws IOException { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestCookieVersionSupport.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestCookieVersionSupport.class); } private static class CookieVer0Service implements HttpService { public CookieVer0Service() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Set-Cookie", "name1=value1; path=/test")); response.setBodyString("whatever"); return true; } } public void testCookieVersionSupportHeader1() throws IOException { this.server.setHttpService(new CookieVer0Service()); this.client.getParams().setCookiePolicy(CookiePolicy.RFC_2965); GetMethod httpget1 = new GetMethod("/test/"); try { this.client.executeMethod(httpget1); } finally { httpget1.releaseConnection(); } GetMethod httpget2 = new GetMethod("/test/"); try { this.client.executeMethod(httpget2); } finally { httpget2.releaseConnection(); } Header cookiesupport = httpget2.getRequestHeader("Cookie2"); assertNotNull(cookiesupport); assertEquals("$Version=\"1\"", cookiesupport.getValue()); } private static class CookieVer1Service implements HttpService { public CookieVer1Service() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Set-Cookie", "name1=value1; Path=\"/test\"; Version=\"1\"")); response.addHeader(new Header("Set-Cookie2", "name2=value2; Path=\"/test\"; Version=\"1\"")); response.setBodyString("whatever"); return true; } } public void testCookieVersionSupportHeader2() throws IOException { this.server.setHttpService(new CookieVer1Service()); this.client.getParams().setCookiePolicy(CookiePolicy.RFC_2965); GetMethod httpget1 = new GetMethod("/test/"); try { this.client.executeMethod(httpget1); } finally { httpget1.releaseConnection(); } GetMethod httpget2 = new GetMethod("/test/"); try { this.client.executeMethod(httpget2); } finally { httpget2.releaseConnection(); } Header cookiesupport = httpget2.getRequestHeader("Cookie2"); assertNull(cookiesupport); } private static class CookieVer2Service implements HttpService { public CookieVer2Service() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Set-Cookie2", "name2=value2; Path=\"/test\"; Version=\"2\"")); response.setBodyString("whatever"); return true; } } public void testCookieVersionSupportHeader3() throws IOException { this.server.setHttpService(new CookieVer2Service()); this.client.getParams().setCookiePolicy(CookiePolicy.RFC_2965); GetMethod httpget1 = new GetMethod("/test/"); try { this.client.executeMethod(httpget1); } finally { httpget1.releaseConnection(); } GetMethod httpget2 = new GetMethod("/test/"); try { this.client.executeMethod(httpget2); } finally { httpget2.releaseConnection(); } Header cookiesupport = httpget2.getRequestHeader("Cookie2"); assertNotNull(cookiesupport); assertEquals("$Version=\"1\"", cookiesupport.getValue()); } private static class SetCookieVersionMixService implements HttpService { public SetCookieVersionMixService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { HttpVersion httpversion = request.getRequestLine().getHttpVersion(); response.setStatusLine(httpversion, HttpStatus.SC_OK); response.addHeader(new Header("Set-Cookie", "name=wrong; Path=/test")); response.addHeader(new Header("Set-Cookie2", "name=right; Path=\"/test\"; Version=\"1\"")); response.setBodyString("whatever"); return true; } } public static class TestHttpState extends HttpState { public synchronized void addCookie(Cookie cookie) { if (cookie != null) { if ("localhost.local".equals(cookie.getDomain())) { cookie.setDomain("localhost"); } super.addCookie(cookie); } } } public void testSetCookieVersionMix() throws IOException { this.server.setHttpService(new SetCookieVersionMixService()); this.client.setState(new TestHttpState()); this.client.getParams().setCookiePolicy(CookiePolicy.RFC_2965); GetMethod httpget1 = new GetMethod("/test/"); try { this.client.executeMethod(httpget1); } finally { httpget1.releaseConnection(); } Cookie[] cookies = this.client.getState().getCookies(); assertNotNull(cookies); assertEquals(1, cookies.length); assertEquals("right", cookies[0].getValue()); assertTrue(cookies[0] instanceof Cookie2); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/cookie/TestDateParser.java100644 0 0 6477 10661532627 26776 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/cookie/TestDateParser.java,v 1.1 2004/12/24 20:36:13 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.cookie; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.apache.commons.httpclient.util.DateUtil; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test cases for expiry date parsing * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class TestDateParser extends TestCase { // ------------------------------------------------------------ Constructor public TestDateParser(String name) { super(name); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestDateParser.class); } private static final String PATTERN = "EEE, dd-MMM-yy HH:mm:ss zzz"; private static final List PATTERNS = new ArrayList(); static { PATTERNS.add(PATTERN); } public void testFourDigitYear() throws Exception { Calendar calendar = Calendar.getInstance(); calendar.setTime(DateUtil.parseDate("Thu, 23-Dec-2004 24:00:00 CET", PATTERNS)); assertEquals(2004, calendar.get(Calendar.YEAR)); } public void testThreeDigitYear() throws Exception { Calendar calendar = Calendar.getInstance(); calendar.setTime(DateUtil.parseDate("Thu, 23-Dec-994 24:00:00 CET", PATTERNS)); assertEquals(994, calendar.get(Calendar.YEAR)); } public void testTwoDigitYear() throws Exception { Calendar calendar = Calendar.getInstance(); calendar.setTime(DateUtil.parseDate("Thu, 23-Dec-04 24:00:00 CET", PATTERNS)); assertEquals(2004, calendar.get(Calendar.YEAR)); calendar.setTime(DateUtil.parseDate("Thu, 23-Dec-94 24:00:00 CET", PATTERNS)); assertEquals(2094, calendar.get(Calendar.YEAR)); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/params/TestHttpParams.java100644 0 0 14520 10661532630 27037 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/params/TestHttpParams.java,v 1.4 2004/10/31 14:42:59 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.params; import java.io.IOException; import java.util.ArrayList; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClientTestBase; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HostParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.server.HttpService; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * HTTP preference framework tests. * * @author Oleg Kalnichevski * * @version $Revision: 480424 $ */ public class TestHttpParams extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestHttpParams(final String testName) throws IOException { super(testName); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestHttpParams.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { return new TestSuite(TestHttpParams.class); } private class SimpleService implements HttpService { public SimpleService() { super(); } public boolean process(final SimpleRequest request, final SimpleResponse response) throws IOException { String uri = request.getRequestLine().getUri(); HttpVersion httpversion = request.getRequestLine().getHttpVersion(); if ("/miss/".equals(uri)) { response.setStatusLine(httpversion, HttpStatus.SC_MOVED_TEMPORARILY); response.addHeader(new Header("Location", "/hit/")); response.setBodyString("Missed!"); } else if ("/hit/".equals(uri)) { response.setStatusLine(httpversion, HttpStatus.SC_OK); response.setBodyString("Hit!"); } else { response.setStatusLine(httpversion, HttpStatus.SC_NOT_FOUND); response.setBodyString(uri + " not found"); } return true; } } public void testDefaultHeaders() throws IOException { this.server.setHttpService(new SimpleService()); ArrayList defaults = new ArrayList(); defaults.add(new Header("this-header", "value1")); defaults.add(new Header("that-header", "value1")); defaults.add(new Header("that-header", "value2")); defaults.add(new Header("User-Agent", "test")); HostConfiguration hostconfig = new HostConfiguration(); hostconfig.setHost( this.server.getLocalAddress(), this.server.getLocalPort(), Protocol.getProtocol("http")); hostconfig.getParams().setParameter(HostParams.DEFAULT_HEADERS, defaults); GetMethod httpget = new GetMethod("/miss/"); try { this.client.executeMethod(hostconfig, httpget); } finally { httpget.releaseConnection(); } assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); Header[] thisheader = httpget.getRequestHeaders("this-header"); assertEquals(1, thisheader.length); Header[] thatheader = httpget.getRequestHeaders("that-header"); assertEquals(2, thatheader.length); assertEquals("test", httpget.getRequestHeader("User-Agent").getValue()); } public void testDefaults() throws IOException { this.server.setHttpService(new SimpleService()); this.client.getParams().setParameter(HttpMethodParams.USER_AGENT, "test"); HostConfiguration hostconfig = new HostConfiguration(); hostconfig.setHost( this.server.getLocalAddress(), this.server.getLocalPort(), Protocol.getProtocol("http")); GetMethod httpget = new GetMethod("/miss/"); try { this.client.executeMethod(hostconfig, httpget); } finally { httpget.releaseConnection(); } assertEquals(HttpStatus.SC_OK, httpget.getStatusCode()); assertEquals("test", httpget.getRequestHeader("User-Agent").getValue()); assertEquals("test", httpget.getParams(). getParameter(HttpMethodParams.USER_AGENT)); assertEquals("test", hostconfig.getParams(). getParameter(HttpMethodParams.USER_AGENT)); assertEquals("test", client.getParams(). getParameter(HttpMethodParams.USER_AGENT)); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/params/TestParamsAll.java100644 0 0 3662 10661532626 26622 0ustar 0 0 /* * $Header$ * $Revision: 515317 $ * $Date: 2007-03-06 22:41:04 +0100 (Tue, 06 Mar 2007) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.commons.httpclient.params; import junit.framework.*; /** * @author Oleg Kalnichevski * * @version $Id: TestParamsAll.java 515317 2007-03-06 21:41:04Z sebb $ */ public class TestParamsAll extends TestCase { public TestParamsAll(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(TestHttpParams.suite()); suite.addTest(TestSSLTunnelParams.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = { TestParamsAll.class.getName() }; junit.textui.TestRunner.main(testCaseName); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/params/TestSSLTunnelParams.java100644 0 0 16354 10661532626 27763 0ustar 0 0 /* * $Header$ * $Revision: 515317 $ * $Date: 2007-03-06 22:41:04 +0100 (Tue, 06 Mar 2007) $ * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.params; import java.io.IOException; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.httpclient.FeedbackService; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClientTestBase; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.server.HttpRequestHandler; import org.apache.commons.httpclient.server.SimpleHttpServerConnection; import org.apache.commons.httpclient.server.SimpleRequest; import org.apache.commons.httpclient.server.SimpleResponse; /** * Tunnelling proxy configuration. * * @author Oleg Kalnichevski * * @version $Id: TestSSLTunnelParams.java 515317 2007-03-06 21:41:04Z sebb $ */ public class TestSSLTunnelParams extends HttpClientTestBase { // ------------------------------------------------------------ Constructor public TestSSLTunnelParams(final String testName) throws IOException { super(testName); setUseProxy(true); setUseSSL(true); } // ------------------------------------------------------------------- Main public static void main(String args[]) { String[] testCaseName = { TestSSLTunnelParams.class.getName() }; junit.textui.TestRunner.main(testCaseName); } // ------------------------------------------------------- TestCase Methods public static Test suite() { TestSuite suite = new TestSuite(TestSSLTunnelParams.class); return suite; } static class HttpVersionHandler implements HttpRequestHandler { public HttpVersionHandler() { super(); } public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { HttpVersion ver = request.getRequestLine().getHttpVersion(); if (ver.equals(HttpVersion.HTTP_1_0)) { return false; } else { SimpleResponse response = new SimpleResponse(); response.setStatusLine(ver, HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED); response.addHeader(new Header("Proxy-Connection", "close")); conn.setKeepAlive(false); // Make sure the request body is fully consumed request.getBodyBytes(); conn.writeResponse(response); return true; } } } /** * Tests correct proparation of HTTP params from the client to * CONNECT method. */ public void testTunnellingParamsAgentLevel() throws IOException { this.proxy.addHandler(new HttpVersionHandler()); this.server.setHttpService(new FeedbackService()); this.client.getParams().setVersion(HttpVersion.HTTP_1_1); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED, httpget.getStatusLine().getStatusCode()); } finally { httpget.releaseConnection(); } this.client.getParams().setVersion(HttpVersion.HTTP_1_0); httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); } finally { httpget.releaseConnection(); } } /** * Tests correct proparation of HTTP params from the host config to * CONNECT method. */ public void testTunnellingParamsHostLevel() throws IOException { this.proxy.addHandler(new HttpVersionHandler()); this.server.setHttpService(new FeedbackService()); this.client.getHostConfiguration().getParams().setParameter( HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); GetMethod httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED, httpget.getStatusLine().getStatusCode()); } finally { httpget.releaseConnection(); } this.client.getHostConfiguration().getParams().setParameter( HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); httpget = new GetMethod("/test/"); try { this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); } finally { httpget.releaseConnection(); } } /** * Tests ability to use HTTP/1.0 to execute CONNECT method and HTTP/1.1 to * execute methods once the tunnel is established. */ public void testTunnellingParamsHostHTTP10AndMethodHTTP11() throws IOException { this.proxy.addHandler(new HttpVersionHandler()); this.server.setHttpService(new FeedbackService()); this.client.getHostConfiguration().getParams().setParameter( HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); GetMethod httpget = new GetMethod("/test/"); httpget.getParams().setVersion(HttpVersion.HTTP_1_1); try { this.client.executeMethod(httpget); assertNotNull(httpget.getStatusLine()); assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode()); assertEquals(HttpVersion.HTTP_1_1, httpget.getEffectiveVersion()); } finally { httpget.releaseConnection(); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/AuthRequestHandler.java100644 0 0 12125 10661532626 27713 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/AuthRequestHandler.java,v 1.1 2004/11/20 17:56:40 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.BasicScheme; /** * This request handler guards access to the http server when used in a request handler * chain. It checks the headers for valid credentials and performs the * authentication handshake if necessary. * * @author Ortwin Glueck * @author Oleg Kalnichevski */ public class AuthRequestHandler implements HttpRequestHandler { private Credentials credentials = null; private String realm = null; private boolean keepalive = true; /** * The authenticate response header. */ public static final String AUTH_RESP = "Authorization"; /** * TODO replace creds parameter with a class specific to an auth scheme * encapsulating all required information for a specific scheme * * @param creds */ public AuthRequestHandler(final Credentials creds, final String realm, boolean keepalive) { if (creds == null) throw new IllegalArgumentException("Credentials may not be null"); this.credentials = creds; this.keepalive = keepalive; if (realm != null) { this.realm = realm; } else { this.realm = "test"; } } public AuthRequestHandler(final Credentials creds, final String realm) { this(creds, realm, true); } public AuthRequestHandler(final Credentials creds) { this(creds, null, true); } public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { Header clientAuth = request.getFirstHeader(AUTH_RESP); if (clientAuth != null && checkAuthorization(clientAuth)) { return false; } else { SimpleResponse response = performBasicHandshake(conn, request); // Make sure the request body is fully consumed request.getBodyBytes(); conn.writeResponse(response); return true; } } //TODO add more auth schemes private SimpleResponse performBasicHandshake( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { SimpleResponse response = new SimpleResponse(); response.setStatusLine( request.getRequestLine().getHttpVersion(), HttpStatus.SC_UNAUTHORIZED); if (!request.getRequestLine().getMethod().equalsIgnoreCase("HEAD")) { response.setBodyString("unauthorized"); } response.addHeader(new Header("WWW-Authenticate", "basic realm=\"" + this.realm + "\"")); if (this.keepalive) { response.addHeader(new Header("Connection", "keep-alive")); conn.setKeepAlive(true); } else { response.addHeader(new Header("Connection", "close")); conn.setKeepAlive(false); } return response; } /** * Checks if the credentials provided by the client match the required * credentials * * @return true if the client is authorized, false if not. * @param clientAuth */ private boolean checkAuthorization(final Header clientAuth) { String expectedAuthString = BasicScheme.authenticate( (UsernamePasswordCredentials)credentials, "ISO-8859-1"); return expectedAuthString.equals(clientAuth.getValue()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/ErrorResponse.java100644 0 0 5445 10661532626 26742 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/ErrorResponse.java,v 1.6 2004/11/13 12:21:28 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.server; import java.util.HashMap; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpVersion; /** * Default error responses. * * @author Christian Kohlschuetter */ public class ErrorResponse { private static final HashMap responses = new HashMap(); private ErrorResponse() { super(); } public static SimpleResponse getResponse(int statusCode) { Integer code = new Integer(statusCode); SimpleResponse response = (SimpleResponse)responses.get(code); if (response == null) { response = new SimpleResponse(); response.setStatusLine(HttpVersion.HTTP_1_0, statusCode); response.setHeader(new Header("Content-Type", "text/plain; charset=US-ASCII")); String s = HttpStatus.getStatusText(statusCode); if (s == null) { s = "Error " + statusCode; } response.setBodyString(s); response.addHeader(new Header("Connection", "close")); response.addHeader(new Header("Content-Lenght", Integer.toString(s.length()))); responses.put(code, response); } return response; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/HttpRequestHandler.java100644 0 0 5313 10661532626 27712 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/HttpRequestHandler.java,v 1.4 2004/02/27 19:01:33 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.server; import java.io.IOException; /** * Defines an HTTP request handler for the SimpleHttpServer * * @author Christian Kohlschuetter * @author Oleg Kalnichevski */ public interface HttpRequestHandler { /** * The request handler is asked to process this request. * * If it is not capable/interested in processing it, this call should * be simply ignored. * * Any modification of the output stream (via conn.getWriter()) * by this request handler will stop the execution chain and return the output * to the client. * * The handler may also rewrite the request parameters (this is useful in * {@link HttpRequestHandlerChain} structures). * * @param conn The Connection object to which this request belongs to. * @param request The request object. * @return true if this handler handled the request and no other handlers in the * chain should be called, false otherwise. * @throws IOException */ public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException; } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/HttpRequestHandlerChain.java100644 0 0 6334 10661532626 30661 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/HttpRequestHandlerChain.java,v 1.6 2004/11/28 15:44:39 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.server; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Maintains a chain of {@link HttpRequestHandler}s where new request-handlers * can be prepended/appended. * * For each call to {@link #processRequest(ResponseWriter,SimpleHttpServerConnection,RequestLine,Header[])} * we iterate over the chain from the start to the end, stopping as soon as a handler * has claimed the output. * * @author Christian Kohlschuetter */ public class HttpRequestHandlerChain implements HttpRequestHandler { private List subhandlers = new ArrayList(); public HttpRequestHandlerChain(final HttpRequestHandlerChain chain) { super(); if (chain != null) { this.subhandlers.clear(); this.subhandlers.addAll(chain.subhandlers); } } public HttpRequestHandlerChain() { super(); } public synchronized void clear() { subhandlers.clear(); } public synchronized void prependHandler(HttpRequestHandler handler) { subhandlers.add(0,handler); } public synchronized void appendHandler(HttpRequestHandler handler) { subhandlers.add(handler); } public synchronized boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { for(Iterator it=subhandlers.iterator();it.hasNext();) { HttpRequestHandler h = (HttpRequestHandler)it.next(); boolean stop = h.processRequest(conn, request); if (stop) { return true; } } return false; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/HttpService.java100644 0 0 4246 10661532626 26370 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/HttpService.java,v 1.1 2004/02/27 19:04:32 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.server; import java.io.IOException; /** * Defines an HTTP request/response service for the SimpleHttpServer * * @author Oleg Kalnichevski */ public interface HttpService { /** * This interface represents a serice to process HTTP requests. * * @param request The HTTP request object. * @param response The HTTP response object. * @return true if this service was able to handle the request, false otherwise. * * @throws IOException */ public boolean process( final SimpleRequest request, final SimpleResponse response) throws IOException; } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/HttpServiceHandler.java100644 0 0 12460 10661532626 27703 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/HttpServiceHandler.java,v 1.9 2004/11/13 22:38:27 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpVersion; /** * This request handler provides service interface similar to that of Servlet API. * * @author Oleg Kalnichevski */ public class HttpServiceHandler implements HttpRequestHandler { private HttpService service = null; public HttpServiceHandler(final HttpService service) { super(); if (service == null) { throw new IllegalArgumentException("Service may not be null"); } this.service = service; } public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { if (conn == null) { throw new IllegalArgumentException("Connection may not be null"); } if (request == null) { throw new IllegalArgumentException("Request may not be null"); } boolean complete = false; SimpleResponse response = new SimpleResponse(); this.service.process(request, response); // Nake sure the request if fully consumed request.getBodyBytes(); // Ensure there's a content type header if (!response.containsHeader("Content-Type")) { response.addHeader(new Header("Content-Type", "text/plain")); } // Ensure there's a content length or transfer encoding header if (!response.containsHeader("Content-Length") && !response.containsHeader("Transfer-Encoding")) { InputStream content = response.getBody(); if (content != null) { long len = response.getContentLength(); if (len < 0) { if (response.getHttpVersion().lessEquals(HttpVersion.HTTP_1_0)) { throw new IOException("Chunked encoding not supported for HTTP version " + response.getHttpVersion()); } Header header = new Header("Transfer-Encoding", "chunked"); response.addHeader(header); } else { Header header = new Header("Content-Length", Long.toString(len)); response.setHeader(header); } } else { Header header = new Header("Content-Length", "0"); response.addHeader(header); } } if (!response.containsHeader("Connection")) { // See if the the client explicitly handles connection persistence Header connheader = request.getFirstHeader("Connection"); if (connheader != null) { if (connheader.getValue().equalsIgnoreCase("keep-alive")) { Header header = new Header("Connection", "keep-alive"); response.addHeader(header); conn.setKeepAlive(true); } if (connheader.getValue().equalsIgnoreCase("close")) { Header header = new Header("Connection", "close"); response.addHeader(header); conn.setKeepAlive(false); } } else { // Use protocol default connection policy if (response.getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) { conn.setKeepAlive(true); } else { conn.setKeepAlive(false); } } } if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) { // this is a head request, we don't want to send the actualy content response.setBody(null); } conn.writeResponse(response); return true; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/ProxyAuthRequestHandler.java100644 0 0 12172 10661532626 30757 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/ProxyAuthRequestHandler.java,v 1.12 2004/11/28 15:44:39 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.BasicScheme; /** * This request handler guards access to a proxy when used in a request handler * chain. It checks the headers for valid credentials and performs the * authentication handshake if necessary. * * @author Ortwin Glueck * @author Oleg Kalnichevski */ public class ProxyAuthRequestHandler implements HttpRequestHandler { private Credentials credentials = null; private String realm = null; private boolean keepalive = true; /** * The proxy authenticate response header. */ public static final String PROXY_AUTH_RESP = "Proxy-Authorization"; /** * TODO replace creds parameter with a class specific to an auth scheme * encapsulating all required information for a specific scheme * * @param creds */ public ProxyAuthRequestHandler(final Credentials creds, final String realm, boolean keepalive) { if (creds == null) throw new IllegalArgumentException("Credentials may not be null"); this.credentials = creds; this.keepalive = keepalive; if (realm != null) { this.realm = realm; } else { this.realm = "test"; } } public ProxyAuthRequestHandler(final Credentials creds, final String realm) { this(creds, realm, true); } public ProxyAuthRequestHandler(final Credentials creds) { this(creds, null, true); } public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { Header clientAuth = request.getFirstHeader(PROXY_AUTH_RESP); if (clientAuth != null && checkAuthorization(clientAuth)) { return false; } else { SimpleResponse response = performBasicHandshake(conn, request); // Make sure the request body is fully consumed request.getBodyBytes(); conn.writeResponse(response); return true; } } //TODO add more auth schemes private SimpleResponse performBasicHandshake( final SimpleHttpServerConnection conn, final SimpleRequest request) { SimpleResponse response = new SimpleResponse(); response.setStatusLine( request.getRequestLine().getHttpVersion(), HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED); if (!request.getRequestLine().getMethod().equalsIgnoreCase("HEAD")) { response.setBodyString("unauthorized"); } response.addHeader(new Header("Proxy-Authenticate", "basic realm=\"" + this.realm + "\"")); if (this.keepalive) { response.addHeader(new Header("Proxy-Connection", "keep-alive")); conn.setKeepAlive(true); } else { response.addHeader(new Header("Proxy-Connection", "close")); conn.setKeepAlive(false); } return response; } /** * Checks if the credentials provided by the client match the required * credentials * * @return true if the client is authorized, false if not. * @param clientAuth */ private boolean checkAuthorization(Header clientAuth) { String expectedAuthString = BasicScheme.authenticate( (UsernamePasswordCredentials)credentials, "ISO-8859-1"); return expectedAuthString.equals(clientAuth.getValue()); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/ProxyRequestHandler.java100644 0 0 15215 10661532630 30131 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/ProxyRequestHandler.java,v 1.11 2004/12/11 22:35:26 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import java.net.UnknownHostException; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.URIException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Ortwin Glueck * @author Oleg Kalnichevski */ public class ProxyRequestHandler implements HttpRequestHandler { private static final Log LOG = LogFactory.getLog(ProxyRequestHandler.class); private SimpleConnManager connmanager = null; public ProxyRequestHandler(final SimpleConnManager connmanager) { super(); if (connmanager == null) { throw new IllegalArgumentException("Connection manager may not be null"); } this.connmanager = connmanager; } /** * @see org.apache.commons.httpclient.server.HttpRequestHandler#processRequest(org.apache.commons.httpclient.server.SimpleHttpServerConnection) */ public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { httpProxy(conn, request); return true; } private void httpProxy( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { RequestLine oldreqline = request.getRequestLine(); URI uri = null; SimpleHost host = null; try { uri = new URI(oldreqline.getUri(), true); host = new SimpleHost(uri.getHost(), uri.getPort()); } catch (URIException ex) { SimpleResponse response = ErrorResponse.getResponse(HttpStatus.SC_BAD_REQUEST); conn.writeResponse(response); return; } SimpleHttpServerConnection proxyconn = null; try { proxyconn = this.connmanager.openConnection(host); } catch (UnknownHostException e) { SimpleResponse response = ErrorResponse.getResponse(HttpStatus.SC_NOT_FOUND); conn.writeResponse(response); return; } try { proxyconn.setSocketTimeout(0); // Rewrite target url RequestLine newreqline = new RequestLine( oldreqline.getMethod(), uri.getEscapedPath(), oldreqline.getHttpVersion()); request.setRequestLine(newreqline); // Remove proxy-auth headers if present request.removeHeaders("Proxy-Authorization"); // Manage connection persistence Header connheader = request.getFirstHeader("Proxy-Connection"); if (connheader != null) { if (connheader.getValue().equalsIgnoreCase("close")) { request.setHeader(new Header("Connection", "close")); } } request.removeHeaders("Proxy-Connection"); proxyconn.writeRequest(request); SimpleResponse response = proxyconn.readResponse(); if (response == null) { return; } response.setHeader(new Header("Via", "1.1 test (Test-Proxy)")); connheader = response.getFirstHeader("Connection"); if (connheader != null) { String s = connheader.getValue(); if (s.equalsIgnoreCase("close")) { response.setHeader(new Header("Proxy-Connection", "close")); conn.setKeepAlive(false); proxyconn.setKeepAlive(false); response.removeHeaders("Connection"); } if (s.equalsIgnoreCase("keep-alive")) { response.setHeader(new Header("Proxy-Connection", "keep-alive")); conn.setKeepAlive(true); proxyconn.setKeepAlive(true); response.removeHeaders("Connection"); } } else { // Use protocol default connection policy if (response.getHttpVersion().greaterEquals(HttpVersion.HTTP_1_1)) { conn.setKeepAlive(true); proxyconn.setKeepAlive(true); } else { conn.setKeepAlive(false); proxyconn.setKeepAlive(false); } } if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) { // this is a head request, we don't want to send the actualy content response.setBody(null); } conn.writeResponse(response); } catch (HttpException e) { SimpleResponse response = ErrorResponse.getResponse(HttpStatus.SC_BAD_REQUEST); conn.writeResponse(response); proxyconn.setKeepAlive(false); } catch (IOException e) { LOG.warn(e.getMessage()); proxyconn.setKeepAlive(false); } finally { this.connmanager.releaseConnection(host, proxyconn); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/RequestLine.java100644 0 0 7530 10661532630 26362 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/RequestLine.java,v 1.4 2004/09/14 15:50:41 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.commons.httpclient.server; import java.util.NoSuchElementException; import java.util.StringTokenizer; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.ProtocolException; /** * Defines a HTTP request-line, consisting of method name, URI and protocol. * Instances of this class are immutable. * * @author Christian Kohlschuetter * @author Oleg Kalnichevski */ public class RequestLine { private HttpVersion httpversion = null; private String method = null; private String uri= null; public static RequestLine parseLine(final String l) throws HttpException { String method = null; String uri = null; String protocol = null; try { StringTokenizer st = new StringTokenizer(l, " "); method = st.nextToken(); uri = st.nextToken(); protocol = st.nextToken(); } catch (NoSuchElementException e) { throw new ProtocolException("Invalid request line: " + l); } return new RequestLine(method, uri, protocol); } public RequestLine(final String method, final String uri, final HttpVersion httpversion) { super(); if (method == null) { throw new IllegalArgumentException("Method may not be null"); } if (uri == null) { throw new IllegalArgumentException("URI may not be null"); } if (httpversion == null) { throw new IllegalArgumentException("HTTP version may not be null"); } this.method = method; this.uri = uri; this.httpversion = httpversion; } public RequestLine(final String method, final String uri, final String httpversion) throws ProtocolException { this(method, uri, HttpVersion.parse(httpversion)); } public String getMethod() { return this.method; } public HttpVersion getHttpVersion() { return this.httpversion; } public String getUri() { return this.uri; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(this.method); sb.append(" "); sb.append(this.uri); sb.append(" "); sb.append(this.httpversion); return sb.toString(); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/ResponseWriter.java100644 0 0 10002 10661532626 27126 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/ResponseWriter.java,v 1.5 2004/11/07 12:31:42 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.BufferedWriter; import java.io.FilterWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; /** * Provides a hybrid Writer/OutputStream for sending HTTP response data * * @author Christian Kohlschuetter */ public class ResponseWriter extends FilterWriter { public static final String CRLF = "\r\n"; public static final String ISO_8859_1 = "ISO-8859-1"; private OutputStream outStream = null; private String encoding = null; public ResponseWriter(final OutputStream outStream) throws UnsupportedEncodingException { this(outStream, CRLF, ISO_8859_1); } public ResponseWriter(final OutputStream outStream, final String encoding) throws UnsupportedEncodingException { this(outStream, CRLF, encoding); } public ResponseWriter( final OutputStream outStream, final String lineSeparator, final String encoding) throws UnsupportedEncodingException { super(new BufferedWriter(new OutputStreamWriter(outStream, encoding))); this.outStream = outStream; this.encoding = encoding; } public String getEncoding() { return encoding; } public void close() throws IOException { if(outStream != null) { super.close(); outStream = null; } } /* (non-Javadoc) * @see java.io.Writer#flush() */ public void flush() throws IOException { if(outStream != null) { super.flush(); outStream.flush(); } } public void write(byte b) throws IOException { super.flush(); outStream.write((int)b); } public void write(byte[] b) throws IOException { super.flush(); outStream.write(b); } public void write(byte[] b, int off, int len) throws IOException { super.flush(); outStream.write(b,off,len); } public void print(String s) throws IOException { if (s == null) { s = "null"; } write(s); } public void print(int i) throws IOException { write(Integer.toString(i)); } public void println(int i) throws IOException { write(Integer.toString(i)); write(CRLF); } public void println(String s) throws IOException { print(s); write(CRLF); } public void println() throws IOException { write(CRLF); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleConnList.java100644 0 0 5516 10661532626 27034 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnList.java,v 1.1 2004/11/13 12:21:28 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * A simple list of connections. * * @author Oleg Kalnichevski */ public class SimpleConnList { private List connections = new ArrayList(); public SimpleConnList() { super(); } public synchronized void addConnection(final SimpleHttpServerConnection conn) { this.connections.add(conn); } public synchronized void removeConnection(final SimpleHttpServerConnection conn) { this.connections.remove(conn); } public synchronized SimpleHttpServerConnection removeLast() { int s = this.connections.size(); if (s > 0) { return (SimpleHttpServerConnection)this.connections.remove(s - 1); } else { return null; } } public synchronized SimpleHttpServerConnection removeFirst() { int s = this.connections.size(); if (s > 0) { return (SimpleHttpServerConnection)this.connections.remove(0); } else { return null; } } public synchronized void shutdown() { for (Iterator i = this.connections.iterator(); i.hasNext();) { SimpleHttpServerConnection conn = (SimpleHttpServerConnection) i.next(); conn.close(); } this.connections.clear(); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleConnManager.java100644 0 0 6774 10661532626 27502 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnManager.java,v 1.2 2004/11/20 17:56:40 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import java.net.Socket; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * A REALLY simple connection manager. * * @author Oleg Kalnichevski */ public class SimpleConnManager { private Map connsets = new HashMap(); public SimpleConnManager() { super(); } public synchronized SimpleHttpServerConnection openConnection(final SimpleHost host) throws IOException { if (host == null) { throw new IllegalArgumentException("Host may not be null"); } SimpleHttpServerConnection conn = null; SimpleConnList connlist = (SimpleConnList)this.connsets.get(host); if (connlist != null) { conn = connlist.removeFirst(); if (conn != null && !conn.isOpen()) { conn = null; } } if (conn == null) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn = new SimpleHttpServerConnection(socket); } return conn; } public synchronized void releaseConnection(final SimpleHost host, final SimpleHttpServerConnection conn) throws IOException { if (host == null) { throw new IllegalArgumentException("Host may not be null"); } if (conn == null) { return; } if (!conn.isKeepAlive()) { conn.close(); } if (conn.isOpen()) { SimpleConnList connlist = (SimpleConnList)this.connsets.get(host); if (connlist == null) { connlist = new SimpleConnList(); this.connsets.put(host, connlist); } connlist.addConnection(conn); } } public synchronized void shutdown() { for (Iterator i = this.connsets.values().iterator(); i.hasNext();) { SimpleConnList connlist = (SimpleConnList) i.next(); connlist.shutdown(); } this.connsets.clear(); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleConnSet.java100644 0 0 4412 10661532626 26646 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnSet.java,v 1.1 2004/11/13 12:21:28 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * A simple set of connections. * * @author Oleg Kalnichevski */ public class SimpleConnSet { private Set connections = new HashSet(); public SimpleConnSet() { super(); } public synchronized void addConnection(final SimpleHttpServerConnection conn) { this.connections.add(conn); } public synchronized void removeConnection(final SimpleHttpServerConnection conn) { this.connections.remove(conn); } public synchronized void shutdown() { for (Iterator i = connections.iterator(); i.hasNext();) { SimpleHttpServerConnection conn = (SimpleHttpServerConnection) i.next(); conn.close(); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleConnectionThread.java100644 0 0 7532 10661532630 30525 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleConnectionThread.java,v 1.3 2004/11/13 22:38:27 mbecke Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import java.io.InterruptedIOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Simple HTTP connection thread. * * @author Christian Kohlschuetter * @author Oleg Kalnichevski */ public class SimpleConnectionThread extends Thread { private static final Log LOG = LogFactory.getLog(SimpleConnectionThread.class); public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1"; private SimpleHttpServerConnection conn = null; private SimpleConnSet connpool = null; private HttpRequestHandler handler = null; transient boolean stopped; public SimpleConnectionThread( final ThreadGroup tg, final String name, final SimpleHttpServerConnection conn, final SimpleConnSet connpool, final HttpRequestHandler handler) throws IOException { super(tg, name); if (conn == null) { throw new IllegalArgumentException("Connection may not be null"); } if (connpool == null) { throw new IllegalArgumentException("Connection pool not be null"); } if (handler == null) { throw new IllegalArgumentException("Request handler may not be null"); } this.conn = conn; this.connpool = connpool; this.handler = handler; this.stopped = false; } public synchronized void destroy() { if (this.stopped) { return; } this.stopped = true; if (conn != null) { conn.close(); conn = null; } interrupt(); } public void run() { try { do { this.conn.setKeepAlive(false); SimpleRequest request = this.conn.readRequest(); if (request != null) { this.handler.processRequest(this.conn, request); } } while (this.conn.isKeepAlive()); } catch (InterruptedIOException e) { } catch (IOException e) { if (!this.stopped && !isInterrupted() && LOG.isWarnEnabled()) { LOG.warn("[" + getName() + "] I/O error: " + e.getMessage()); } } finally { destroy(); this.connpool.removeConnection(this.conn); } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleHost.java100644 0 0 6521 10661532630 26210 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleHost.java,v 1.1 2004/11/13 12:21:28 olegk Exp $ * $Revision: 510582 $ * $Date: 2007-02-22 17:42:43 +0100 (Thu, 22 Feb 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; /** * @author Oleg Kalnichevski */ public class SimpleHost implements Cloneable { private String hostname = null; private int port = -1; public SimpleHost(final String hostname, int port) { super(); if (hostname == null) { throw new IllegalArgumentException("Host name may not be null"); } if (port < 0) { throw new IllegalArgumentException("Port may not be negative"); } this.hostname = hostname; this.port = port; } public SimpleHost (final SimpleHost httphost) { super(); init(httphost); } private void init(final SimpleHost httphost) { this.hostname = httphost.hostname; this.port = httphost.port; } public Object clone() throws CloneNotSupportedException { SimpleHost copy = (SimpleHost) super.clone(); copy.init(this); return copy; } public String getHostName() { return this.hostname; } public int getPort() { return this.port; } public String toString() { StringBuffer buffer = new StringBuffer(50); buffer.append(this.hostname); buffer.append(':'); buffer.append(this.port); return buffer.toString(); } public boolean equals(final Object o) { if (o instanceof SimpleHost) { if (o == this) { return true; } SimpleHost that = (SimpleHost) o; if (!this.hostname.equalsIgnoreCase(that.hostname)) { return false; } if (this.port != that.port) { return false; } return true; } else { return false; } } public int hashCode() { return this.hostname.hashCode() + this.port; } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleHttpServer.java100644 0 0 16321 10661532630 27420 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleHttpServer.java,v 1.15 2004/12/11 22:35:26 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A simple, but extensible HTTP server, mostly for testing purposes. * * @author Christian Kohlschuetter * @author Oleg Kalnichevski */ public class SimpleHttpServer implements Runnable { private static final Log LOG = LogFactory.getLog(SimpleHttpServer.class); private String testname = "Simple test"; private long count = 0; private ServerSocket listener = null; private Thread t; private ThreadGroup tg; private boolean stopped = false; private SimpleConnSet connections = new SimpleConnSet(); private HttpRequestHandler requestHandler = null; /** * Creates a new HTTP server instance, using an arbitrary free TCP port * * @throws IOException if anything goes wrong during initialization */ public SimpleHttpServer() throws IOException { this(null, 0); } /** * Creates a new HTTP server instance, using the specified socket * factory and the TCP port * * @param port Desired TCP port * @throws IOException if anything goes wrong during initialization */ public SimpleHttpServer(SimpleSocketFactory socketfactory, int port) throws IOException { if (socketfactory == null) { socketfactory = new SimplePlainSocketFactory(); } listener = socketfactory.createServerSocket(port); if(LOG.isDebugEnabled()) { LOG.debug("Starting test HTTP server on port " + getLocalPort()); } tg = new ThreadGroup("SimpleHttpServer thread group"); t = new Thread(tg, this, "SimpleHttpServer listener"); t.setDaemon(true); t.start(); } /** * Creates a new HTTP server instance, using the specified TCP port * * @param port Desired TCP port * @throws IOException if anything goes wrong during initialization */ public SimpleHttpServer(int port) throws IOException { this(null, port); } public String getTestname() { return this.testname; } public void setTestname(final String testname) { this.testname = testname; } /** * Returns the TCP port that this HTTP server instance is bound to. * * @return TCP port, or -1 if not running */ public int getLocalPort() { return listener.getLocalPort(); } /** * Returns the IP address that this HTTP server instance is bound to. * @return String representation of the IP address or null if not running */ public String getLocalAddress() { InetAddress address = listener.getInetAddress(); // Ugly work-around for older JDKs byte[] octets = address.getAddress(); if ((octets[0] == 0) && (octets[1] == 0) && (octets[2] == 0) && (octets[3] == 0)) { return "localhost"; } else { return address.getHostAddress(); } } /** * Checks if this HTTP server instance is running. * * @return true/false */ public boolean isRunning() { if(t == null) { return false; } return t.isAlive(); } /** * Stops this HTTP server instance. */ public synchronized void destroy() { if (stopped) { return; } this.stopped = true; if(LOG.isDebugEnabled()) { LOG.debug("Stopping test HTTP server on port " + getLocalPort()); } tg.interrupt(); if (listener != null) { try { listener.close(); } catch(IOException e) { } } this.connections.shutdown(); } /** * Returns the currently used HttpRequestHandler by this SimpleHttpServer * * @return The used HttpRequestHandler, or null. */ public HttpRequestHandler getRequestHandler() { return requestHandler; } /** * Sets the HttpRequestHandler to be used for this SimpleHttpServer. * * @param rh Request handler to be used, or null to disable. */ public void setRequestHandler(HttpRequestHandler rh) { this.requestHandler = rh; } public void setHttpService(HttpService service) { setRequestHandler(new HttpServiceHandler(service)); } public void run() { try { while (!this.stopped && !Thread.interrupted()) { Socket socket = listener.accept(); try { if (this.requestHandler == null) { socket.close(); break; } SimpleHttpServerConnection conn = new SimpleHttpServerConnection(socket); this.connections.addConnection(conn); Thread t = new SimpleConnectionThread( tg, this.testname + " thread " + this.count, conn, this.connections, this.requestHandler); t.setDaemon(true); t.start(); } catch (IOException e) { LOG.error("I/O error: " + e.getMessage()); } this.count++; Thread.sleep(100); } } catch (InterruptedException accept) { } catch (IOException e) { if (!stopped) { LOG.error("I/O error: " + e.getMessage()); } } finally { destroy(); } } } ././@LongLink100644 0 0 145 10661532634 10261 Lustar 0 0 commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleHttpServerConnection.javacommons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleHttpServerConnection.java100644 0 0 17542 10661532630 31446 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleHttpServerConnection.java,v 1.21 2004/12/11 22:35:26 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.SocketException; import java.util.Iterator; import org.apache.commons.httpclient.ChunkedOutputStream; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpParser; import org.apache.commons.httpclient.StatusLine; /** * A connection to the SimpleHttpServer. * * @author Christian Kohlschuetter * @author Oleg Kalnichevski */ public class SimpleHttpServerConnection { private static final String HTTP_ELEMENT_CHARSET = "US-ASCII"; private Socket socket = null; private InputStream in = null; private OutputStream out = null; private boolean keepAlive = false; public SimpleHttpServerConnection(final Socket socket) throws IOException { super(); if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); } this.socket = socket; this.socket.setSoTimeout(500); this.in = socket.getInputStream(); this.out = socket.getOutputStream(); } public synchronized void close() { try { if (socket != null) { in.close(); out.close(); socket.close(); socket = null; } } catch (IOException e) { } } public synchronized boolean isOpen() { return this.socket != null; } public void setKeepAlive(boolean b) { this.keepAlive = b; } public boolean isKeepAlive() { return this.keepAlive; } public InputStream getInputStream() { return this.in; } public OutputStream getOutputStream() { return this.out; } /** * Returns the ResponseWriter used to write the output to the socket. * * @return This connection's ResponseWriter */ public ResponseWriter getWriter() throws UnsupportedEncodingException { return new ResponseWriter(out); } public SimpleRequest readRequest() throws IOException { try { String line = null; do { line = HttpParser.readLine(in, HTTP_ELEMENT_CHARSET); } while (line != null && line.length() == 0); if (line == null) { setKeepAlive(false); return null; } SimpleRequest request = new SimpleRequest( RequestLine.parseLine(line), HttpParser.parseHeaders(this.in, HTTP_ELEMENT_CHARSET), this.in); return request; } catch (IOException e) { close(); throw e; } } public SimpleResponse readResponse() throws IOException { try { String line = null; do { line = HttpParser.readLine(in, HTTP_ELEMENT_CHARSET); } while (line != null && line.length() == 0); if (line == null) { setKeepAlive(false); return null; } SimpleResponse response = new SimpleResponse( new StatusLine(line), HttpParser.parseHeaders(this.in, HTTP_ELEMENT_CHARSET), this.in); return response; } catch (IOException e) { close(); throw e; } } public void writeRequest(final SimpleRequest request) throws IOException { if (request == null) { return; } ResponseWriter writer = new ResponseWriter(this.out, HTTP_ELEMENT_CHARSET); writer.println(request.getRequestLine().toString()); Iterator item = request.getHeaderIterator(); while (item.hasNext()) { Header header = (Header) item.next(); writer.print(header.toExternalForm()); } writer.println(); writer.flush(); OutputStream outsream = this.out; InputStream content = request.getBody(); if (content != null) { Header transferenc = request.getFirstHeader("Transfer-Encoding"); if (transferenc != null) { request.removeHeaders("Content-Length"); if (transferenc.getValue().indexOf("chunked") != -1) { outsream = new ChunkedOutputStream(outsream); } } byte[] tmp = new byte[4096]; int i = 0; while ((i = content.read(tmp)) >= 0) { outsream.write(tmp, 0, i); } if (outsream instanceof ChunkedOutputStream) { ((ChunkedOutputStream)outsream).finish(); } } outsream.flush(); } public void writeResponse(final SimpleResponse response) throws IOException { if (response == null) { return; } ResponseWriter writer = new ResponseWriter(this.out, HTTP_ELEMENT_CHARSET); writer.println(response.getStatusLine()); Iterator item = response.getHeaderIterator(); while (item.hasNext()) { Header header = (Header) item.next(); writer.print(header.toExternalForm()); } writer.println(); writer.flush(); OutputStream outsream = this.out; InputStream content = response.getBody(); if (content != null) { Header transferenc = response.getFirstHeader("Transfer-Encoding"); if (transferenc != null) { response.removeHeaders("Content-Length"); if (transferenc.getValue().indexOf("chunked") != -1) { outsream = new ChunkedOutputStream(outsream); } } byte[] tmp = new byte[1024]; int i = 0; while ((i = content.read(tmp)) >= 0) { outsream.write(tmp, 0, i); } if (outsream instanceof ChunkedOutputStream) { ((ChunkedOutputStream)outsream).finish(); } } outsream.flush(); } public int getSocketTimeout() throws SocketException { return this.socket.getSoTimeout(); } public void setSocketTimeout(int timeout) throws SocketException { this.socket.setSoTimeout(timeout); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimplePlainSocketFactory.java100644 0 0 3625 10661532630 31041 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimplePlainSocketFactory.java,v 1.1 2004/12/11 22:35:26 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import java.net.ServerSocket; /** * Defines a plain socket factory * * @author Oleg Kalnichevski */ public class SimplePlainSocketFactory implements SimpleSocketFactory { public SimplePlainSocketFactory() { super(); } public ServerSocket createServerSocket(int port) throws IOException { return new ServerSocket(port); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleProxy.java100644 0 0 6130 10661532626 26415 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleProxy.java,v 1.8 2004/12/11 22:35:26 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import org.apache.commons.httpclient.Credentials; /** * Simple server that registers default request handlers to act as a proxy. * * @author Ortwin Glueck * @author Oleg Kalnichevski */ public class SimpleProxy extends SimpleHttpServer { private SimpleConnManager connmanager = null; private HttpRequestHandlerChain stdchain = null; public SimpleProxy(int port) throws IOException { super(port); this.connmanager = new SimpleConnManager(); this.stdchain = new HttpRequestHandlerChain(); this.stdchain.appendHandler(new TransparentProxyRequestHandler()); this.stdchain.appendHandler(new ProxyRequestHandler(this.connmanager)); setRequestHandler(this.stdchain); } public SimpleProxy() throws IOException { this(0); } public void requireAuthentication(final Credentials creds, final String realm, boolean keepalive) { HttpRequestHandlerChain chain = new HttpRequestHandlerChain(this.stdchain); chain.prependHandler(new ProxyAuthRequestHandler(creds ,realm, keepalive)); setRequestHandler(chain); } public void requireAuthentication(final Credentials creds) { HttpRequestHandlerChain chain = new HttpRequestHandlerChain(this.stdchain); chain.prependHandler(new ProxyAuthRequestHandler(creds)); setRequestHandler(chain); } public void destroy() { super.destroy(); this.connmanager.shutdown(); } public void addHandler(final HttpRequestHandler handler) { this.stdchain.prependHandler(handler); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleRequest.java100644 0 0 16160 10661532627 26751 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleRequest.java,v 1.3 2004/11/13 12:21:28 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import org.apache.commons.httpclient.ChunkedInputStream; import org.apache.commons.httpclient.ContentLengthInputStream; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HeaderElement; import org.apache.commons.httpclient.HeaderGroup; import org.apache.commons.httpclient.NameValuePair; /** * A generic HTTP request. * * @author Oleg Kalnichevski */ public class SimpleRequest { public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1"; private RequestLine requestLine = null; private HeaderGroup headers = new HeaderGroup(); private InputStream entity = null; public SimpleRequest() { super(); } public SimpleRequest( final RequestLine requestLine, final Header[] headers, final InputStream content) throws IOException { super(); if (requestLine == null) { throw new IllegalArgumentException("Request line may not be null"); } this.requestLine = requestLine; if (headers != null) { this.headers.setHeaders(headers); } if (content != null) { // only PUT and POST have content String methodname = requestLine.getMethod(); if ("POST".equalsIgnoreCase(methodname) || "PUT".equalsIgnoreCase(methodname)) { Header contentLength = this.headers.getFirstHeader("Content-Length"); Header transferEncoding = this.headers.getFirstHeader("Transfer-Encoding"); InputStream in = content; if (transferEncoding != null) { if (transferEncoding.getValue().indexOf("chunked") != -1) { in = new ChunkedInputStream(in); } } else if (contentLength != null) { long len = getContentLength(); if (len >= 0) { in = new ContentLengthInputStream(in, len); } } this.entity = in; } } } public SimpleRequest(final RequestLine requestLine, final Header[] headers) throws IOException { this(requestLine, headers, null); } public RequestLine getRequestLine() { return this.requestLine; } public void setRequestLine(final RequestLine requestline) { if (requestline == null) { throw new IllegalArgumentException("Request line may not be null"); } this.requestLine = requestline; } public boolean containsHeader(final String name) { return this.headers.containsHeader(name); } public Header[] getHeaders() { return this.headers.getAllHeaders(); } public Header getFirstHeader(final String s) { return this.headers.getFirstHeader(s); } public void removeHeaders(final String s) { if (s == null) { return; } Header[] headers = this.headers.getHeaders(s); for (int i = 0; i < headers.length; i++) { this.headers.removeHeader(headers[i]); } } public void addHeader(final Header header) { if (header == null) { return; } this.headers.addHeader(header); } public void setHeader(final Header header) { if (header == null) { return; } removeHeaders(header.getName()); addHeader(header); } public Iterator getHeaderIterator() { return this.headers.getIterator(); } public String getContentType() { Header contenttype = this.headers.getFirstHeader("Content-Type"); if (contenttype != null) { return contenttype.getValue(); } else { return "text/plain"; } } public String getCharset() { String charset = null; Header contenttype = this.headers.getFirstHeader("Content-Type"); if (contenttype != null) { HeaderElement values[] = contenttype.getElements(); if (values.length == 1) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } if (charset != null) { return charset; } else { return DEFAULT_CONTENT_CHARSET; } } public long getContentLength() { Header contentLength = this.headers.getFirstHeader("Content-Length"); if (contentLength != null) { try { return Long.parseLong(contentLength.getValue()); } catch (NumberFormatException e) { return -1; } } else { return -1; } } public InputStream getBody() { return this.entity; } public byte[] getBodyBytes() throws IOException { InputStream in = getBody(); if (in != null) { byte[] tmp = new byte[4096]; int bytesRead = 0; ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024); while ((bytesRead = in.read(tmp)) != -1) { buffer.write(tmp, 0, bytesRead); } return buffer.toByteArray(); } else { return null; } } public String getBodyString() throws IOException { byte[] raw = getBodyBytes(); if (raw != null) { return new String(raw, getCharset()); } else { return null; } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleResponse.java100644 0 0 21151 10661532626 27112 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleResponse.java,v 1.8 2004/11/13 12:21:28 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Iterator; import org.apache.commons.httpclient.ChunkedInputStream; import org.apache.commons.httpclient.ContentLengthInputStream; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HeaderElement; import org.apache.commons.httpclient.HeaderGroup; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.StatusLine; /** * A generic HTTP response. * * @author Christian Kohlschuetter * @author Oleg Kalnichevski */ public class SimpleResponse { public static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1"; private HttpVersion ver = HttpVersion.HTTP_1_1; private int statuscode = HttpStatus.SC_OK; private String phrase = HttpStatus.getStatusText(HttpStatus.SC_OK); private HeaderGroup headers = new HeaderGroup(); private InputStream entity = null; public SimpleResponse() { super(); } public SimpleResponse( final StatusLine statusline, final Header[] headers, final InputStream content) throws IOException { super(); if (statusline == null) { throw new IllegalArgumentException("Status line may not be null"); } setStatusLine(HttpVersion.parse(statusline.getHttpVersion()), statusline.getStatusCode(), statusline.getReasonPhrase()); setHeaders(headers); if (content != null) { InputStream in = content; Header contentLength = this.headers.getFirstHeader("Content-Length"); Header transferEncoding = this.headers.getFirstHeader("Transfer-Encoding"); if (transferEncoding != null) { if (transferEncoding.getValue().indexOf("chunked") != -1) { in = new ChunkedInputStream(in); } } else if (contentLength != null) { long len = getContentLength(); if (len >= 0) { in = new ContentLengthInputStream(in, len); } } this.entity = in; } } public void setStatusLine(final HttpVersion ver, int statuscode, final String phrase) { if (ver == null) { throw new IllegalArgumentException("HTTP version may not be null"); } if (statuscode <= 0) { throw new IllegalArgumentException("Status code may not be negative or zero"); } this.ver = ver; this.statuscode = statuscode; if (phrase != null) { this.phrase = phrase; } else { this.phrase = HttpStatus.getStatusText(statuscode); } } public void setStatusLine(final HttpVersion ver, int statuscode) { setStatusLine(ver, statuscode, null); } public String getPhrase() { return this.phrase; } public int getStatuscode() { return this.statuscode; } public HttpVersion getHttpVersion() { return this.ver; } public String getStatusLine() { StringBuffer buffer = new StringBuffer(); buffer.append(this.ver); buffer.append(' '); buffer.append(this.statuscode); if (this.phrase != null) { buffer.append(' '); buffer.append(this.phrase); } return buffer.toString(); } public boolean containsHeader(final String name) { return this.headers.containsHeader(name); } public Header[] getHeaders() { return this.headers.getAllHeaders(); } public Header getFirstHeader(final String name) { return this.headers.getFirstHeader(name); } public void removeHeaders(final String s) { if (s == null) { return; } Header[] headers = this.headers.getHeaders(s); for (int i = 0; i < headers.length; i++) { this.headers.removeHeader(headers[i]); } } public void addHeader(final Header header) { if (header == null) { return; } this.headers.addHeader(header); } public void setHeader(final Header header) { if (header == null) { return; } removeHeaders(header.getName()); addHeader(header); } public void setHeaders(final Header[] headers) { if (headers == null) { return; } this.headers.setHeaders(headers); } public Iterator getHeaderIterator() { return this.headers.getIterator(); } public String getCharset() { String charset = DEFAULT_CONTENT_CHARSET; Header contenttype = this.headers.getFirstHeader("Content-Type"); if (contenttype != null) { HeaderElement values[] = contenttype.getElements(); if (values.length == 1) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } return charset; } public long getContentLength() { Header contentLength = this.headers.getFirstHeader("Content-Length"); if (contentLength != null) { try { return Long.parseLong(contentLength.getValue()); } catch (NumberFormatException e) { return -1; } } else { return -1; } } public void setBodyString(final String string) { if (string != null) { byte[] raw = null; try { raw = string.getBytes(DEFAULT_CONTENT_CHARSET); } catch (UnsupportedEncodingException e) { raw = string.getBytes(); } this.entity = new ByteArrayInputStream(raw); if (!containsHeader("Content-Type")) { setHeader(new Header("Content-Type", "text/plain")); } setHeader(new Header("Content-Length", Long.toString(raw.length))); } else { this.entity = null; } } public void setBody(final InputStream instream) { this.entity = instream; } public InputStream getBody() { return this.entity; } public byte[] getBodyBytes() throws IOException { InputStream in = getBody(); if (in != null) { byte[] tmp = new byte[4096]; int bytesRead = 0; ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024); while ((bytesRead = in.read(tmp)) != -1) { buffer.write(tmp, 0, bytesRead); } return buffer.toByteArray(); } else { return null; } } public String getBodyString() throws IOException { byte[] raw = getBodyBytes(); if (raw != null) { return new String(raw, getCharset()); } else { return null; } } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/SimpleSocketFactory.java100644 0 0 3373 10661532626 30062 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/SimpleSocketFactory.java,v 1.1 2004/12/11 22:35:26 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import java.net.ServerSocket; /** * Defines a socket factory interface * * @author Oleg Kalnichevski */ public interface SimpleSocketFactory { ServerSocket createServerSocket(int port) throws IOException; } ././@LongLink100644 0 0 151 10661532634 10256 Lustar 0 0 commons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/TransparentProxyRequestHandler.javacommons-httpclient-3.1/src/test/org/apache/commons/httpclient/server/TransparentProxyRequestHandler.100644 0 0 12417 10661532630 31512 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/server/TransparentProxyRequestHandler.java,v 1.7 2004/12/11 22:35:26 olegk Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.server; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.Socket; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpVersion; /** * This request handler can handle the CONNECT method. It does nothing for any * other HTTP methods. * * @author Ortwin Glueck */ public class TransparentProxyRequestHandler implements HttpRequestHandler { /* * (non-Javadoc) * * @see org.apache.commons.httpclient.server.HttpRequestHandler#processRequest(org.apache.commons.httpclient.server.SimpleHttpServerConnection) */ public boolean processRequest( final SimpleHttpServerConnection conn, final SimpleRequest request) throws IOException { RequestLine line = request.getRequestLine(); HttpVersion ver = line.getHttpVersion(); String method = line.getMethod(); if (!"CONNECT".equalsIgnoreCase(method)) { return false; } Socket targetSocket = null; try { targetSocket = connect(line.getUri()); } catch (IOException e) { SimpleResponse response = new SimpleResponse(); response.setStatusLine(ver, HttpStatus.SC_NOT_FOUND); response.setHeader(new Header("Server", "test proxy")); response.setBodyString("Cannot connect to " + line.getUri()); conn.writeResponse(response); return true; } SimpleResponse response = new SimpleResponse(); response.setHeader(new Header("Server", "test proxy")); response.setStatusLine(ver, HttpStatus.SC_OK, "Connection established"); conn.writeResponse(response); SimpleHttpServerConnection target = new SimpleHttpServerConnection(targetSocket); pump(conn, target); return true; } private void pump(final SimpleHttpServerConnection source, final SimpleHttpServerConnection target) throws IOException { source.setSocketTimeout(100); target.setSocketTimeout(100); InputStream sourceIn = source.getInputStream(); OutputStream sourceOut = source.getOutputStream(); InputStream targetIn = target.getInputStream(); OutputStream targetOut = target.getOutputStream(); byte[] tmp = new byte[1024]; int l; for (;;) { if (!source.isOpen() || !target.isOpen()) { break; } try { l = sourceIn.read(tmp); if (l == -1) { break; } targetOut.write(tmp, 0, l); } catch (InterruptedIOException ignore) { if (Thread.interrupted()) { break; } } try { l = targetIn.read(tmp); if (l == -1) { break; } sourceOut.write(tmp, 0, l); } catch (InterruptedIOException ignore) { if (Thread.interrupted()) { break; } } } } private static Socket connect(final String host) throws IOException { String hostname = null; int port; int i = host.indexOf(':'); if (i != -1) { hostname = host.substring(0, i); try { port = Integer.parseInt(host.substring(i + 1)); } catch (NumberFormatException ex) { throw new IOException("Invalid host address: " + host); } } else { hostname = host; port = 80; } return new Socket(hostname, port); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/ssl/SimpleSSLSocketFactory.java100644 0 0 7632 10661532630 27734 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/ssl/SimpleSSLSocketFactory.java,v 1.1 2004/12/11 22:35:26 olegk Exp $ * $Revision: 514390 $ * $Date: 2007-03-04 13:37:15 +0100 (Sun, 04 Mar 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.ssl; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.URL; import java.security.KeyStore; import javax.net.ServerSocketFactory; import org.apache.commons.httpclient.server.SimpleSocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.sun.net.ssl.KeyManager; import com.sun.net.ssl.KeyManagerFactory; import com.sun.net.ssl.SSLContext; /** * Defines a SSL socket factory * * @author Oleg Kalnichevski */ public class SimpleSSLSocketFactory implements SimpleSocketFactory { private static final Log LOG = LogFactory.getLog(SimpleSocketFactory.class); private static SSLContext SSLCONTEXT = null; private static SSLContext createSSLContext() { try { ClassLoader cl = SimpleSocketFactory.class.getClassLoader(); URL url = cl.getResource("org/apache/commons/httpclient/ssl/simpleserver.keystore"); KeyStore keystore = KeyStore.getInstance("jks"); InputStream is = null; try { is = url.openStream(); keystore.load(is, "nopassword".toCharArray()); } finally { if (is != null) is.close(); } KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, "nopassword".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); return sslcontext; } catch (Exception ex) { // this is not the way a sane exception handling should be done // but for our simple HTTP testing framework this will suffice LOG.error(ex.getMessage(), ex); throw new IllegalStateException(ex.getMessage()); } } private static SSLContext getSSLContext() { if (SSLCONTEXT == null) { SSLCONTEXT = createSSLContext(); } return SSLCONTEXT; } public SimpleSSLSocketFactory() { super(); } public ServerSocket createServerSocket(int port) throws IOException { ServerSocketFactory socketfactory = getSSLContext().getServerSocketFactory(); return socketfactory.createServerSocket(port); } } ././@LongLink100644 0 0 152 10661532634 10257 Lustar 0 0 commons-httpclient-3.1/src/test/org/apache/commons/httpclient/ssl/SimpleSSLTestProtocolSocketFactory.javacommons-httpclient-3.1/src/test/org/apache/commons/httpclient/ssl/SimpleSSLTestProtocolSocketFactory100644 0 0 13145 10661532630 31412 0ustar 0 0 /* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/test/org/apache/commons/httpclient/ssl/SimpleSSLTestProtocolSocketFactory.java,v 1.1 2004/12/11 22:35:26 olegk Exp $ * $Revision: 514390 $ * $Date: 2007-03-04 13:37:15 +0100 (Sun, 04 Mar 2007) $ * * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ package org.apache.commons.httpclient.ssl; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.Socket; import java.net.URL; import java.net.UnknownHostException; import java.security.KeyStore; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory; import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; import org.apache.commons.httpclient.server.SimpleSocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.sun.net.ssl.SSLContext; import com.sun.net.ssl.TrustManager; import com.sun.net.ssl.TrustManagerFactory; public class SimpleSSLTestProtocolSocketFactory implements SecureProtocolSocketFactory { private static final Log LOG = LogFactory.getLog(SimpleSSLTestProtocolSocketFactory.class); private static SSLContext SSLCONTEXT = null; private static SSLContext createSSLContext() { try { ClassLoader cl = SimpleSocketFactory.class.getClassLoader(); URL url = cl.getResource("org/apache/commons/httpclient/ssl/simpleserver.keystore"); KeyStore keystore = KeyStore.getInstance("jks"); InputStream is = null; try { is = url.openStream(); keystore.load(is, "nopassword".toCharArray()); } finally { if (is != null) is.close(); } TrustManagerFactory tmfactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(keystore); TrustManager[] trustmanagers = tmfactory.getTrustManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, trustmanagers, null); return sslcontext; } catch (Exception ex) { // this is not the way a sane exception handling should be done // but for our simple HTTP testing framework this will suffice LOG.error(ex.getMessage(), ex); throw new IllegalStateException(ex.getMessage()); } } private static SSLContext getSSLContext() { if (SSLCONTEXT == null) { SSLCONTEXT = createSSLContext(); } return SSLCONTEXT; } public SimpleSSLTestProtocolSocketFactory() { super(); } public Socket createSocket( final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params ) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); if (timeout == 0) { return createSocket(host, port, localAddress, localPort); } else { // To be eventually deprecated when migrated to Java 1.4 or above return ControllerThreadSocketFactory.createSocket( this, host, port, localAddress, localPort, timeout); } } public Socket createSocket( String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket( host, port, clientHost, clientPort ); } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket( host, port ); } public Socket createSocket( Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket( socket, host, port, autoClose ); } } commons-httpclient-3.1/src/test/org/apache/commons/httpclient/ssl/simpleserver.keystore100644 0 0 2542 10661532626 27064 0ustar 0 0 simple-http-servercN00 +*wyf\"^`z-28~{nV2'H/"a!VY*kMRZ"=nlRкȮVޙ g@4^A_Y;0nPӍ`E05/?V*\:s݊D?9HwH2E%g9M:GC)H60 29GD=(` )x?*T̾kl]⇒6̱'m !2+'ݲ1"#Vk̻Q P`wX TpRsaDj: u)Qq/pQߍ&inH7*|S-ǵU OGX]mBmhn- X.5090|09A0 *H8010UUnknown10UUnknown10UUnknown1#0!U Apache Software Foundation1#0!U Jakarta HttpClient Project1 0USimple Test Http Server0 041211134835Z 141209134835Z010UUnknown10UUnknown10UUnknown1#0!U Apache Software Foundation1#0!U Jakarta HttpClient Project1 0USimple Test Http Server00,*H80Su)RJ.R%!DλbP0\~4l)' T@JUϟfmOM#hEtWbKī.b:0 *H800-kБ4r޿S'7ˬNl} -o_X3K/j?9nGcommons-httpclient-3.1/src/test/org/apache/commons/httpclient/ssl/SimpleSSLTestProtocolSocketFactory.java